如何在文本框中输入文本时在数据网格视图中显示sql数据。例如:dBase中有wai wai和britannia。我想在product_name中显示数据网格列中数据库的所有信息或者product_id在产品名称中输入:textbox。我尝试了以下代码:但它不起作用:
private void textBox2_KeyDown(object sender, KeyEventArgs e)
{
if(e.KeyData==Keys.Enter)
{
SqlConnection con = new SqlConnection("Data Source=SUMIT;Initial Catalog=Project;Integrated Security=True");
SqlDataAdapter a = new SqlDataAdapter("select product_Name,product_Id,purchase_Price,discount,beforevat_Price,vat_Rate,actual_Cost,Margin,actual_Sp from Product", con);
DataTable b = new DataTable();
a.Fill(b);
dataGridView1.DataSource = b;
textBox3.Focus();
}
}
答案 0 :(得分:0)
你实际上可以这样做
string WhrCond = "";
int n;
if(int.TryParse(textBox2.Text, out n))
{
WhrCond = "product_Id = " + textBox2.Text.Trim() ;
}
else
{
WhrCond = "product_Name LIKE '%" + textBox2.Text.Trim() + "%'";
}
if(string.IsNullOrEmpty(textBox2.Text))
{
WhrCond = "1 = 1";
}
SqlConnection con = new SqlConnection("Data Source=SUMIT;Initial Catalog=Project;Integrated Security=True");
SqlDataAdapter a = new SqlDataAdapter("select product_Name as [Product Name],
actual_Cost as [Actual Cp],
Margin,
actual_Sp as [Actual SP],
product_Id as [Product Id],
purchase_Price as [Purchase Price],
discount as [Discount],
beforevat_Price as [Before Vat Price],
vat_Rate as [Vat%] from Product WHERE " + WhrCond , con);
DataTable b = new DataTable();
a.Fill(b);
dataGridView1.DataSource = b;
textBox3.Focus();
您将从设计时创建的DGV中删除所有数据。
答案 1 :(得分:0)
我假设你的datagridview在这里没有设置列(因为我们使用数据源)尝试擦除它们。
private void textBox2_TextChanged(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=SUMIT;Initial Catalog=Project;Integrated Security=True " + "connection timeout=300");
conn.Open();
string query = "Select * from Product where product_Name like '%"+textBox2.Text+"%'";
SqlDataAdapter a = new SqlDataAdapter(query,conn);
DataTable b = new DataTable();
a.Fill(b);
dataGridView1.DataSource = b;
}
PS:如果你绝对想在开始时设置列,那么不要使用DataSource 在数据表b.rows上使用foreach循环,然后将行添加到datagridview1
DtataGridView1.Rows.Add(b["Product_Name],..,...)
2-like lei说你可以使用DataPropertyNametoo