Bootstrap

C# 调用SQL Server存储过程,传入参数,返回查询结果,更新dataGridView

调用SQL Server存储过程,传入参数,返回查询结果

                using (SqlConnection conn = new SqlConnection(connectionString))
                {
                    String cmdText = "Screen";//存储过程名
                    SqlCommand cmd = new SqlCommand(cmdText, conn);
                    cmd.CommandType = CommandType.StoredProcedure;//执行类型为存储过程
                    cmd.Parameters.Add("@代码", SqlDbType.VarChar, 50).Value = str1;
                    cmd.Parameters.Add("@日期", SqlDbType.VarChar, 50).Value = str2;
                    conn.Open();
                    cmd.ExecuteNonQuery();
                    // 执行sql语句
                     cmdText = "SELECT * FROM ##temp" ;
                    cmd = new SqlCommand(cmdText, conn);
                    SqlDataAdapter adp = new SqlDataAdapter(cmd);
                    DataSet ds = new DataSet();
                    DataTable dt = new DataTable();
                    adp.Fill(ds);
                    dt = ds.Tables[0];
                    if (dt.Rows.Count != 0)
                    {
                    	//dt数据绑定dataGridView1
                        this.Invoke(new MethodInvoker(delegate { BindDataGridView(dt, this.dataGridView1); }));
                        MessageBox.Show("数据处理完成");
                    }

更新dataGridView
BindDataGridView()

private void BindDataGridView(DataTable dt, DataGridView dgv)
        {
            dataGridView1.Rows.Clear();
            if (dt == null || dt.Rows.Count == 0 || dt.Rows[0][0].ToString() == "") return;
            if (dt.Columns.Count < 1) return;
            int index = 0;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                dgv.Rows.Add(1);
                index = dgv.Rows.Count - 1;
                dgv.Rows[index].Cells["代码"].Value = dt.Rows[i]["代码"].ToString();
                dgv.Rows[index].Cells["日期"].Value = dt.Rows[i]["日期"].ToString();
            }
        }
;