[英]Binding search results to data grid
我想在程序中添加搜索功能。 有一个具有此功能的类:
public DataTable Search()
{
string SQL = "Select * from Customer where " + mField + " like '%" + mValue + "%'";
DataTable dt = new DataTable();
dt = dm.GetData(SQL);
return (dt);
}
有mField
和mValue
setter和getter属性。 DM
是DataManagement
类的对象,该类具有方法GetData
:
public DataTable GetData(string SQL)
{
SqlCommand command = new SqlCommand();
SqlDataAdapter dbAdapter = new SqlDataAdapter();
DataTable DataTable = new DataTable();
command.Connection = clsConnection.GetConnection();
command.CommandText = SQL;
dbAdapter.SelectCommand = command;
dbAdapter.Fill(DataTable);
return (DataTable);
}
搜索功能当前是这样实现的:
private void btnfind_Click(object sender, EventArgs e)
{
//cust is the object of class customer//
if (tbCustName.Text != "")
{
cust.Field="CustName";
cust.Value = tbCustName.Text;
}
else if (tbAddress.Text != "")
{
cust.Value = tbAddress.Text;
cust.Field="Address";
}
else if (tbEmail.Text != "")
{
cust.Value = tbEmail.Text;
cust.Field="Email";
}
else if (tbCell.Text != "")
{
cust.Value = tbCell.Text;
cust.Field = "Cell";
}
DataTable dt = new DataTable();
dt = cust.Search();
dgCustomer.DataSource = dt;
RefreshGrid();
}
private void RefreshGrid()
{
DataTable dt = new DataTable();
dt = cust.GetCustomers();
dgCustomer.DataSource = dt;
}
这是行不通的。 我不知道为什么 请帮忙。
在RefreshGrid()
方法中添加一个DataBind()
语句,以使新结果实际显示在Grid上。
private void RefreshGrid()
{
DataTable dt = cust.GetCustomers();
dgCustomer.DataSource = dt;
dgCustomer.DataBind();
}
也可以考虑修改其他方法:
btnfind_Click
不必结束两次调用cust.Search()
。
private void btnfind_Click(object sender, EventArgs e) { //<snip> // no need to do all this twice. // DataTable dt = new DataTable(); // dt = cust.Search(); // dgCustomer.DataSource = dt; RefreshGrid(); }
您的RefreshGrid
方法正在覆盖您在btnfind_Click
设置的DataSource
...不要调用它,只需调用DataBind
private void btnfind_Click(object sender, EventArgs e)
{
...
DataTable dt = cust.Search();
dgCustomer.DataSource = dt;
dgCustomer.DataBind();
}
顺便说一句,如果您立即将新的DataTable
设置为cust.Search
的结果,则cust.Search
为dt分配新的DataTable
...您只需创建一个实例即可(我在上面的代码中对其进行了修复)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.