2014-04-08 25 views
0

我已經搜索了這個,但找不到任何解決方案textchanged gridview外的事件導致結果的變化。我無法附加作爲新手的形象。我希望通過數據表在gridview中顯示的結果根據我在gridview外部放置的文本框中輸入的內容進行更新。代碼在C#將不勝感激。最後,我想按ENTER鍵檢索ID以進一步使用。在gridview外的textbox_TextChanged事件更新gridview的內容

private void textBox1_TextChanged(object sender, EventArgs e) 
    { 
     DataTable table = new DataTable(); 
      string sql; table.Columns.Add("Name"); 


      dbconnect db = new dbconnect(); 
      db.createconnection(); 
      sql = "select custcompany from customer"; 
      db.dbadapter = new OleDbDataAdapter(sql, db.dbconnection); 
      DataTable dtt = new DataTable(); 
      db.dbadapter.Fill(dtt); 

      for (int i = 0; i < dtt.Rows.Count; i++) 
      { 
       table.Rows.Add(dtt.Rows[i][0]); 
      } 

      sql = "select suppcompany from supplier"; 
      db.dbadapter = new OleDbDataAdapter(sql, db.dbconnection); 
      DataTable dtt1 = new DataTable(); 
      db.dbadapter.Fill(dtt1); 

      for (int i = 0; i < dtt1.Rows.Count; i++) 
      { 
       table.Rows.Add(dtt1.Rows[i][0]); 
      } 
      dataGridView1.DataSource = table; 


      if (textBox1.Text != "") 
      { 

       DataView dv = new DataView(); 
       dv.RowFilter = string.Format("Name = '{0}'", textBox1.Text); 
       dataGridView1.DataSource = dv; 


      } 
      else if (textBox1.Text == "") 
      { 
       dataGridView1.DataSource = table; 
      } 
     } 

table是在Load事件上填充的DataTable的名稱。

+1

您以前試過的是什麼? – Bharadwaj

+0

你在正確的方向。在聲明'DataSource'後,'Databind'就是gridview。但必須關注文本框以查看更改。 –

+0

@Bharadwaj我編輯過的問題。 – user3510905

回答

2

如果測試盒有價值,您正在創建DataView的新實例並將其指定給dataGridView1,我的問題是DataView對象中是否有值?如果你正在做的正是你給的問題,那麼它將無法正常工作,因爲dv沒有價值顯示在dataGridView1

通過訪問數據庫獲取有關TextChanged事件的table數據。如果您有將數據庫值存入table的任何代碼,請在綁定到DataGridView1之前在此事件中使用它。

因爲table值將在PostBack之後丟失。所以你需要重新將值重新加載到table。請嘗試以下,

private void textBox1_TextChanged(object sender, EventArgs e) 
{ 
    //table = fill the table with proper values by accessing the database 
    if (textBox1.Text != "") 
    { 
     DataView dv = table.DefaultView; 
     dv.RowFilter = string.Format("Name = '{0}'", textBox1.Text); 
     dataGridView1.DataSource = dv; 
     dataGridView1.DataBind(); 
    } 
    else if (textBox1.Text == "") 
    { 
     dataGridView1.DataSource = table; 
     dataGridView1.DataBind(); 
    } 
} 

更新

要搜索的是開頭字母使用的名稱,

dv.RowFilter = string.Format("Name like '{0}%'", textBox1.Text); 

要搜索包含一個字母使用的名稱,

dv.RowFilter = string.Format("Name like '%{0}%'", textBox1.Text); 

搜索以字母結尾的名字,

dv.RowFilter = string.Format("Name like '%{0}'", textBox1.Text); 
+0

我現在在gridview中獲取結果,但它只顯示結果,當它匹配表中可用的完整名稱時。我怎麼能顯示人的姓名,即使他們匹配一個「字母」?就像我寫「john」一樣,它會填充網格,但即使按「j」時也要顯示「john」。 – user3510905

+0

@ user3510905「if-else」塊之外的第一個賦值('dataGridView1.DataSource = table;')不是必須的,那麼無論何時分配'DataSource',都需要添加'dataGridView1.DataBind();'。而不是'DataView dv = new DataView();'添加'DataView dv = table.DefaultView;'。 – Bharadwaj

+0

@ user3510905 **或**在for for塊結束後,使用我在答案中添加的if-else塊。 – Bharadwaj