C# 在列中的DataGridView中搜索值
我希望用户能够在DataGridView(dgv)的列中搜索数字。dgv可以保存许多记录。每个记录都有一个项目编号。因此,我希望用户能够在“项目编号”列中搜索项目编号。我拥有的列是:ProjectID(不可见);图像(无标题文本);项目编号;项目名称;公司;联系方式 这是我的密码:C# 在列中的DataGridView中搜索值,c#,winforms,datagridview,datagridviewcolumn,C#,Winforms,Datagridview,Datagridviewcolumn,我希望用户能够在DataGridView(dgv)的列中搜索数字。dgv可以保存许多记录。每个记录都有一个项目编号。因此,我希望用户能够在“项目编号”列中搜索项目编号。我拥有的列是:ProjectID(不可见);图像(无标题文本);项目编号;项目名称;公司;联系方式 这是我的密码: private void btnSearch_Click(object sender, EventArgs e) { string searchValue = textBox1.Text; int r
private void btnSearch_Click(object sender, EventArgs e)
{
string searchValue = textBox1.Text;
int rowIndex = -1;
dgvProjects.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
try
{
foreach (DataGridViewRow row in dgvProjects.Rows)
{
if (row.Cells[row.Index].Value.ToString().Equals(searchValue))
{
rowIndex = row.Index;
dgvProjects.Rows[row.Index].Selected = true;
break;
}
}
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
}
问题#1:到目前为止它做了什么:用户在TextBox1中键入项目编号。当他/她单击按钮时,代码在行中搜索该字符串,当找到项目编号时,该行被选中。它工作正常,但只工作一次。当我想搜索其他项目编号时,什么也没有发生
问题#2:我认为这可以通过更好的方式完成,只搜索列项目名称的值。但我应该如何正确地做到这一点呢
我用来搜索的代码来自于使用row.Cells[row.Index]的原因。您需要指定要搜索的列的索引(问题2)。例如,您需要将row.Cells[row.Index]更改为row.Cells[2],其中2是列的索引:
private void btnSearch_Click(object sender, EventArgs e)
{
string searchValue = textBox1.Text;
dgvProjects.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
try
{
foreach (DataGridViewRow row in dgvProjects.Rows)
{
if (row.Cells[2].Value.ToString().Equals(searchValue))
{
row.Selected = true;
break;
}
}
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
}
为什么不先构建一个
数据表
,然后将其分配给数据网格视图
作为数据源
:
DataTable table4DataSource=new DataTable();
table4DataSource.Columns.Add("col00");
table4DataSource.Columns.Add("col01");
table4DataSource.Columns.Add("col02");
...
(手动、圆形或通过数据库表中的DataReader
添加行)
(分配数据源)
然后使用:
(dtGrdViewGrid.DataSource as DataTable).DefaultView.RowFilter = "col00 = '" + textBoxSearch.Text+ "'";
dtGrdViewGrid.Refresh();
您甚至可以将这段代码放入
textbox\u textchange
事件中,您的过滤值将在写入时显示。直接从DataTable
或Dataset
中过滤数据:
"MyTable".DefaultView.RowFilter = "<DataTable Field> LIKE '%" + textBox1.Text + "%'";
this.dataGridView1.DataSource = "MyTable".DefaultView;
“MyTable.DefaultView.RowFilter=”类似“%”+textBox1.Text+“%”;
this.dataGridView1.DataSource=“MyTable”.DefaultView;
在Textbox
的事件KeyUp
上使用此代码,替换表名或数据集的“MyTable”,替换要进行搜索的字段。“MyTable.DefaultView.RowFilter=”类似“%”+textBox1.Text+“%”;
this.dataGridView1.DataSource=“MyTable”.DefaultView
与数据库连接和数据表的关系如何?我应该如何正确设置DefaultView
我使用以下代码来获取数据:
con = new System.Data.SqlServerCe.SqlCeConnection();
con.ConnectionString = "Data Source=C:\\Users\\mhadj\\Documents\\Visual Studio 2015\\Projects\\data_base_test_2\\Sample.sdf";
con.Open();
DataTable dt = new DataTable();
adapt = new System.Data.SqlServerCe.SqlCeDataAdapter("select * from tbl_Record", con);
adapt.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
最好在另一个方法中分离逻辑,或者在另一个类中分离逻辑 此方法将帮助您检索找到文本的DataGridViewCell对象
/// <summary>
/// Check if a given text exists in the given DataGridView at a given column index
/// </summary>
/// <param name="searchText"></param>
/// <param name="dataGridView"></param>
/// <param name="columnIndex"></param>
/// <returns>The cell in which the searchText was found</returns>
private DataGridViewCell GetCellWhereTextExistsInGridView(string searchText, DataGridView dataGridView, int columnIndex)
{
DataGridViewCell cellWhereTextIsMet = null;
// For every row in the grid (obviously)
foreach (DataGridViewRow row in dataGridView.Rows)
{
// I did not test this case, but cell.Value is an object, and objects can be null
// So check if the cell is null before using .ToString()
if (row.Cells[columnIndex].Value != null && searchText == row.Cells[columnIndex].Value.ToString())
{
// the searchText is equals to the text in this cell.
cellWhereTextIsMet = row.Cells[columnIndex];
break;
}
}
return cellWhereTextIsMet;
}
private void button_click(object sender, EventArgs e)
{
DataGridViewCell cell = GetCellWhereTextExistsInGridView(textBox1.Text, myGridView, 2);
if (cell != null)
{
// Value exists in the grid
// you can do extra stuff on the cell
cell.Style = new DataGridViewCellStyle { ForeColor = Color.Red };
}
else
{
// Value does not exist in the grid
}
}
//
///检查给定列索引处的给定DataGridView中是否存在给定文本
///
///
///
///
///在其中找到searchText的单元格
私有DataGridViewCell GetCellWhereTextExistingRidView(字符串搜索文本、DataGridView DataGridView、int-columnIndex)
{
DataGridViewCell CellWhereTextIsSet=null;
//对于网格中的每一行(显然)
foreach(dataGridView.Rows中的DataGridViewRow行)
{
//我没有测试这个案例,但是cell.Value是一个对象,对象可以为null
//因此,请在使用.ToString()之前检查单元格是否为null
if(row.Cells[columnIndex].Value!=null&&searchText==row.Cells[columnIndex].Value.ToString())
{
//searchText等于此单元格中的文本。
cellWhereTextIsMet=行。单元格[列索引];
打破
}
}
返回cellWhereTextIsMet;
}
私有无效按钮\u单击(对象发送者,事件参数e)
{
DataGridViewCell=GetCellWhereTextExistingRidView(textBox1.Text,myGridView,2);
如果(单元格!=null)
{
//值存在于网格中
//你可以在手机上做额外的事情
cell.Style=newdatagridviewcellstyle{ForeColor=Color.Red};
}
其他的
{
//值在网格中不存在
}
}
谢谢,我已经想到了类似的方法,但当时我使用了错误的值。。。这解决了dgvProjects.SelectionMode=DataGridViewSelectionMode.FullRowSelect这两个问题;必要吗?仅使用foreach循环是不够的?虽然您还没有发表评论的声誉,但这并不是问题的答案
con = new System.Data.SqlServerCe.SqlCeConnection();
con.ConnectionString = "Data Source=C:\\Users\\mhadj\\Documents\\Visual Studio 2015\\Projects\\data_base_test_2\\Sample.sdf";
con.Open();
DataTable dt = new DataTable();
adapt = new System.Data.SqlServerCe.SqlCeDataAdapter("select * from tbl_Record", con);
adapt.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
/// <summary>
/// Check if a given text exists in the given DataGridView at a given column index
/// </summary>
/// <param name="searchText"></param>
/// <param name="dataGridView"></param>
/// <param name="columnIndex"></param>
/// <returns>The cell in which the searchText was found</returns>
private DataGridViewCell GetCellWhereTextExistsInGridView(string searchText, DataGridView dataGridView, int columnIndex)
{
DataGridViewCell cellWhereTextIsMet = null;
// For every row in the grid (obviously)
foreach (DataGridViewRow row in dataGridView.Rows)
{
// I did not test this case, but cell.Value is an object, and objects can be null
// So check if the cell is null before using .ToString()
if (row.Cells[columnIndex].Value != null && searchText == row.Cells[columnIndex].Value.ToString())
{
// the searchText is equals to the text in this cell.
cellWhereTextIsMet = row.Cells[columnIndex];
break;
}
}
return cellWhereTextIsMet;
}
private void button_click(object sender, EventArgs e)
{
DataGridViewCell cell = GetCellWhereTextExistsInGridView(textBox1.Text, myGridView, 2);
if (cell != null)
{
// Value exists in the grid
// you can do extra stuff on the cell
cell.Style = new DataGridViewCellStyle { ForeColor = Color.Red };
}
else
{
// Value does not exist in the grid
}
}