2015-12-15 69 views
1

below is sql data in database.如何時,在文本框中輸入文本和號碼顯示在數據網格視圖的SQL數據

This is my win form

如何時,在文本輸入文本顯示在數據網格視圖SQL數據box.for例如:在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(); 
    } 
} 

它顯示輸出象下面這樣: enter image description here

+0

你應該設置列的** DataPropertyName **綁定到表。 –

+0

使用where子句 – Angelo

回答

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:如果你絕對要設置列在啓動時則不要使用數據源,但是,數據表b.rows 使用foreach循環再行添加到datagridview1

DtataGridView1.Rows.Add(b["Product_Name],..,...) 

2樣磊說你可以使用DataPropertyNametoo

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在設計時創建的,則應當刪除所有數據。

+0

Mohit if(isNumeric(textBox2.Text))is not working.When I debug it is isNumeric does not exist in current centext –

+0

not working.Its顯示與我在上面question.My datagrid視圖有列,當我按下文本框2中的輸入時,它會在數據網格視圖中添加相同的列。 –

+0

您應該刪除在設計時創建的DGV的所有數據。 –

相關問題