gpt4 book ai didi

c# - Datagrid 没有过滤

转载 作者:行者123 更新时间:2023-11-28 23:33:54 24 4
gpt4 key购买 nike

我有一个数据网格,它使用 loadStudentTable() 方法填充表格数据。

我有一个搜索框,我在其中尝试使用包含的值过滤 dataGrid。

它似乎不起作用。指出错误:

Object reference not set to an instance of an object.

搜索文本更改

private void SearchTxt_TextChanged(object sender, EventArgs e)
{
try
{
(studentGridView.DataSource as DataTable).DefaultView.RowFilter = string.Format("Student_FName LIKE '%{0}%'", SearchTxt.Text);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}

学生表加载

 //Fills out Student table
private void loadStudentTable()
{
SqlConnection conn2 = new SqlConnection(@"Data Source=(LocalDB)\v11.0; AttachDbFilename=C:\Users\Donald\Documents\Visual Studio 2013\Projects\DesktopApplication\DesktopApplication\Student_CB.mdf ;Integrated Security=True");
conn2.Open();

try
{
SqlCommand cmdDatabase2 = new SqlCommand("Select * from Student", conn2);
SqlDataAdapter sda2 = new SqlDataAdapter();
sda2.SelectCommand = cmdDatabase2;
DataTable dbdataset2 = new DataTable();
sda2.Fill(dbdataset2);
BindingSource bSource2 = new BindingSource();

bSource2.DataSource = dbdataset2;
studentGridView.DataSource = bSource2;
sda2.Update(dbdataset2);

studentGridView.Columns[0].Width = 92;
studentGridView.Columns[1].Width = 200;
studentGridView.Columns[2].Width = 180;
studentGridView.Columns[3].Width = 180;
studentGridView.Columns[4].Width = 170;
studentGridView.Columns[5].Width = 170;
studentGridView.Columns[6].Width = 130;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

conn2.Close();
}

加载表格很好,它只是过滤搜索文本框中使用的输入。

请提供任何想法或帮助。

最佳答案

如下所示拆分您的代码并尝试..

private void SearchTxt_TextChanged(object sender, EventArgs e)
{
try
{

var bindData = (BindingSource)studentGridView.DataSource;
var dataTable = (DataTable)bindData.DataSource;
dataTable.DefaultView.RowFilter = string.Format(""Student_FName LIKE '%{0}%'", SearchTxt.Text);
studentGridView.Refresh();

}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}

关于c# - Datagrid 没有过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36402159/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com