我有一个现有的datagridview和一个搜索文本框。
当我输入搜索文本并根据以下方法点击搜索按钮(使用存储过程)时,我希望让它自动使用搜索结果重新加载datagridview。
我怎样才能做到这一点?
public static void searchAny(String searchFields, String tblName, String connectionString, SqlCommand tblscmd, SqlDataAdapter tbldataadaptor, DataTable tbldatatable, SqlCommandBuilder cmbuilder, DataGridView DataGridViewName)
{
using (SqlConnection tblconn = new SqlConnection(connectionString))
{
tblconn.Open();
SqlCommand tblcmd = new SqlCommand();
tblcmd.Connection = tblconn;
tblcmd.CommandType = CommandType.StoredProcedure;
tblcmd.CommandText = "usp_searchany";
tblcmd.Parameters.Add("@stringToFind", SqlDbType.NVarChar);
tblcmd.Parameters["@stringToFind"].Value = "%" + searchFields + "%";
tblcmd.Parameters.Add("@table", SqlDbType.NVarChar);
tblcmd.Parameters["@table"].Value = tblName;
cmbuilder.DataAdapter = tbldataadaptor;
tbldatatable.DefaultView.AllowDelete = true;
tbldatatable.DefaultView.AllowEdit = true;
tbldataadaptor.Fill(tbldatatable);
DataGridViewName.ReadOnly = false;
DataGridViewName.DataSource = tbldatatable;
tblconn.Close();
}
}
private void SearchButton_Click(object sender, EventArgs e)
{
tbldatatable.Clear();
String searchFields = SearchTextBox.Text;
GeneralMethods.searchAny(searchFields, "tblClients", connectionString, tblcmd, tbldataadaptor, tbldatatable, cmbuilder, dataGridView);
dataGridView.DataSource = tbldatatable;
dataGridView.Refresh();
}
答案 0 :(得分:1)
您必须过滤DataGridView的DataSource ...就像以下方式一样......不需要清除,绑定或刷新datagridview ......
从CellEndEidt开始,这是可能的......
只需过滤DataGridView的DataSource
即可private void MyDataGrid1_CellEndEdit(object sender, System.Windows.Forms.DataGridViewCellEventArgs e)
{
if (e.RowIndex == 0)
{
if (myDataGrid1.CurrentCell.Value.ToString().Trim().Length > 0)
{
MyFilterString="Field1=Feild2 and Field3>Field4";
}
MyDtb1.DefaultView.RowFilter = FilterString;
}
}