2016-06-30 34 views
-1

我正在創建一個程序,我需要在網格的每一列中進行搜索,但該搜索文本框應該應用到DataGridView的單元格中。我的意思是 DataGridView的最頂行作爲搜索行,它將在其下面的數據中應用搜索。在DataGridView中自定義搜索

如下面的例子:

enter image description here

此的DataGridView具有適用搜到它下面的值,在第一行中搜索細胞。

+0

你在做什麼:Winforms,WPF,ASP ..? __Always__正確標記您的問題! – TaW

+1

winforms。將從現在開始記住這一點。 –

+0

嗨@OmerWaheed,歡迎來到Stack Overflow。要添加建議的標籤,點擊編輯並將新標籤添加到列表中(在編輯摘要和保存按鈕上方)。 – ardila

回答

0

這是可以做到的,正如你在下面看到的,它並不是你需要的很多代碼。但是,你需要使用一些技巧,所以這裏是你可能想研究例如:

enter image description here

假定您綁定到DataTableAllowUserToAddRows集到DataGridView假。

你想的第一件事就是搶編輯控制,通常是TextBox當用戶開始編輯:

DataGridViewTextBoxEditingControl editDgvEc = null; // at class level! 

我們抓住它,在這種情況下:

private void dataGridView1_EditingControlShowing(object sender, 
          DataGridViewEditingControlShowingEventArgs e) 
{ 
    // unhook the old handle 
    if (editDgvEc != null) editDgvEc.TextChanged -= editDgvEc_TextChanged; 
    // store a reference 
    editDgvEc = e.Control as DataGridViewTextBoxEditingControl; 
    // hook up the TextChanged event 
    editDgvEc.TextChanged += editDgvEc_TextChanged; 
} 

TextChanged事件我們做一些測試,然後選擇所有適合的行:

void editDgvEc_TextChanged(object sender, EventArgs e) 
{ 
    if (dataGridView1.CurrentCell.RowIndex == 0) 
    { 
     int col = dataGridView1.CurrentCell.ColumnIndex; 
     if (editDgvEc.Text == "") dataGridView1.ClearSelection(); 
     else 
      foreach (DataGridViewRow row in dataGridView1.Rows) 
      { 
       if (row.Index > 0) row.Selected = 
        row.Cells[col].Value.ToString().Contains(editDgvEc.Text); 
      } 
    } 
} 

因此,您可以在鍵入時看到工作中的選擇過程。如果有很多行,則可能需要更改,可能是通過從編輯文本框中獲取搜索文本,但是從CellEndEdit事件中的單元本身獲取搜索文本。

最後我們要設置搜索行。我們需要做的是,DataTable dt後填充:

dataGridView1.DataSource = dt; 
DataRow dr = dt.NewRow(); 
dt.Rows.InsertAt(dr, 0); 
dataGridView1.Rows[0].Frozen = true; 
dataGridView1.Rows[0].DividerHeight = 2; 
dataGridView1.Rows[0].DefaultCellStyle.BackColor = Color.LightBlue; 

對於一個更漂亮的觸摸我們可以編寫代碼CellPainting事件畫一個自定義的RowHeader

private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) 
{ 
    if (e.ColumnIndex >= 0 || e.RowIndex != 0) return; 
    e.Graphics.DrawString("$", new Font("Wingdings",11f), Brushes.Black, e.CellBounds); 
    e.Handled = true; 
} 

如果DGV沒有數據綁定代碼只需將搜索行直接添加到DGV而不是將其添加到數據源即可。

+0

THANKYOU這麼多!!!! ...這正是我需要的。驗證。謝謝 –