我想選擇所有客戶信息,其中customerid =存儲在組合框中的選定customerid並在datagridview中顯示結果我試過這段代碼,但gridview沒有顯示結果。如何在Windows窗體中選擇Where語句
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(constring);
int id = Convert.ToInt32(comboBox1.SelectedValue);
string cmdstring=string.Format("select *from customers where customer_id={0}",id);
SqlCommand cmd = new SqlCommand(cmdstring,con);
//cmd.Parameters.AddWithValue("@id",id);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
//da.Fill(ds, "customers");
//dataGridView1.DataSource = ds.Tables["customers"];
con.Open();
SqlDataReader red = cmd.ExecuteReader();
con.Close();
dataGridView1.DataSource = red;
button = new DataGridViewButtonColumn();
button.HeaderText = "edit";
button.Tag = ds.Tables["customers"].Columns["customer_id"];
dataGridView1.Columns.Add(button);
}
你不應該使用字符串連接來創建查詢;你打開自己的SQL注入。您應該使用參數化查詢。 – Servy
你可以將你的代碼包裝在你正在做cmd.ExecuteReader的嘗試catch中。 – MethodMan
首先讓我們開始讓你的DataTable正確地返回,然後我們可以轉移到獲取Column信息,很難告訴你的代碼是什麼或者在哪裏拋出錯誤沒有適當的異常處理 – MethodMan