Reputation: 422
I have a existing datagridview and a search textbox.
When I type a search text and click on the search button based on the below method (using stored procedures), I like to have it auto reload the datagridview with the search results.
How can I achieve this?
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();
}
Upvotes: 0
Views: 1034
Reputation: 83
You have to filter your DataGridView's DataSource...like the following way...It's not required to clear,bind or refresh the datagridview...
From the CellEndEidt this is possible....
Simply you can filter the DataGridView's 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;
}
}
Upvotes: 1