datagridview 查询
时间: 2023-10-21 17:05:44 浏览: 35
如果你想在 DataGridView 中进行查询,可以考虑以下步骤:
1. 获取用户输入的查询条件。
2. 遍历 DataGridView 中的每一行,比较是否符合查询条件。
3. 将符合条件的行添加到一个新的 DataGridView 中展示。
下面是一个示例代码,展示如何实现简单的查询功能:
```csharp
private void btnSearch_Click(object sender, EventArgs e)
{
string keyword = txtKeyword.Text;
if (string.IsNullOrWhiteSpace(keyword)) return;
var filteredRows = new List<DataGridViewRow>();
foreach (DataGridViewRow row in dataGridView1.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
if (cell.Value != null && cell.Value.ToString().Contains(keyword))
{
filteredRows.Add(row);
break;
}
}
}
if (filteredRows.Count > 0)
{
var newDataGridView = new DataGridView();
newDataGridView.Columns.AddRange(dataGridView1.Columns.Cast<DataGridViewColumn>().ToArray());
foreach (var row in filteredRows)
{
newDataGridView.Rows.Add(row.Cells.Cast<DataGridViewCell>().ToArray());
}
newDataGridView.Dock = DockStyle.Fill;
var form = new Form();
form.Controls.Add(newDataGridView);
form.ShowDialog();
}
else
{
MessageBox.Show("No match found.");
}
}
```
在这个示例中,我们首先获取用户输入的查询关键字,然后遍历 DataGridView 中的每一行,比较每一个单元格是否包含关键字。如果某一行中包含关键字,我们就将这一行添加到一个新的 DataGridView 中展示。
请注意,这个示例仅仅是一个简单的演示,还有很多可以优化的地方,比如支持更灵活的查询条件,以及对大型数据集的处理。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)