C# 为文本框文本筛选我的Datagridview
实际上,我正在尝试从特定列的文本框中筛选Datagridview中的文本。问题是,我从另一个线程中选择了代码,但它一直告诉我Datagridview的数据源为“Null” 我的Datagridview代码C# 为文本框文本筛选我的Datagridview,c#,visual-studio,datagridview,filter,C#,Visual Studio,Datagridview,Filter,实际上,我正在尝试从特定列的文本框中筛选Datagridview中的文本。问题是,我从另一个线程中选择了代码,但它一直告诉我Datagridview的数据源为“Null” 我的Datagridview代码 private void Icon_Picker_Load(object sender, EventArgs e) { string[] first = {"0","1","2","3","4","5","6","7","8","9","10","11","12","13","14",
private void Icon_Picker_Load(object sender, EventArgs e)
{
string[] first = {"0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17"};
dataGridView1.Rows.Clear();
dataGridView1.Refresh();
//image directory
DirectoryInfo dir = new DirectoryInfo(@"C:\Users\Daniel\Documents\Visual Studio 2013\Projects\WindowsFormsApplication1\WindowsFormsApplication1\images");
//getting all files from the Directory
foreach(FileInfo file in dir.GetFiles())
{
try
{
this.img16x16.Images.Add(Image.FromFile(file.FullName));
this.img32x32.Images.Add(Image.FromFile(file.FullName));
for (int j = 0; j < img16x16.Images.Count; j++)
{
var row = new DataGridViewRow();
dataGridView1.Rows.Add(row);
dataGridView1.Rows[j].Cells[0].Value = first[j];
//Resizing icons to 16x16 icons
img16x16.ImageSize = new Size(16, 16);
//adding icons to the datagridview
dataGridView1.Rows[j].Cells[1].Value = img16x16.Images[j];
//Resizing icons to 32x32 icons
img32x32.ImageSize = new Size(32, 32);
//adding icons to the datagridview
dataGridView1.Rows[j].Cells[2].Value = img32x32.Images[j];
}
}catch
{
Console.WriteLine("This is not an image file");
}
}
感谢您的帮助。您最初将datagridview绑定到哪里。。?使用调试器并逐步完成代码。。告诉我们您注意到datagridview为null的确切行。。另外,最初在哪里绑定数据源?在哪里分配数据源。。?此外,您的过滤器不应该像
那样,而不是=
dataGridView1.Rows.Add(row)
您正在直接向DGV添加行,并且没有使用数据源,因此任何使用DS相关ops(如DataView或筛选器)的尝试都不会起作用…您可以手动迭代行,并将不匹配行的.Visible
设置为false。您可以按照Puropoix的建议隐藏DataGridView
行,或者更改设置网格的方式。不要在DGV中创建列和行,而是在数据表中创建它们。然后将其设置为源代码,上面的过滤代码应该可以工作。我给出了一个设置DataTable
的例子,并给出了不同的过滤选项,如MethodMan提到的。好的,谢谢大家。我只是改变了填充datagridview的方式,就像Ohbouse在他的例子中所做的那样。非常感谢:)
private void txtFilter_TextChanged(object sender, EventArgs e)
{
(dataGridView1.DataSource as DataTable).DefaultView.RowFilter = string.Format("Field = '{0}'", txtFilter.Text);
}