0

我有一个现有的 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();
}
4

1 回答 1

1

您必须过滤 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;
    }
}
于 2012-05-09T07:35:35.257 回答