我想在我的程序中添加搜索功能。有一个具有此功能的类:
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;
}
这不起作用。我不知道为什么。请帮忙。
答案 0 :(得分:1)
在DataBind()
方法中添加RefreshGrid()
语句,让您的新结果真正显示在网格上。
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();
}
答案 1 :(得分:0)
您的RefreshGrid
方法会覆盖您在DataSource
中设置的btnfind_Click
...请勿拨打电话,只需拨打DataBind
private void btnfind_Click(object sender, EventArgs e)
{
...
DataTable dt = cust.Search();
dgCustomer.DataSource = dt;
dgCustomer.DataBind();
}
顺便说一句,如果您立即将其设置为DataTable
的结果,则无需为dt指定新的cust.Search
...您只需为其创建实例什么都没有(我在上面的代码中修复了它)