Click here to Skip to main content
15,920,633 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to filter listbox data by using datagridview cell instead of using textbox.

What I have tried:

C#
private void searchLedger(string value)
{
    cn.Open();
    SqlCommand cmd = new SqlCommand("Select * from LedgerCreation  Where  ledgerName  like '%" + value + "%' and AddClassification =@AddClassification order by LedgerName", cn);
    cmd.Parameters.AddWithValue("@AddClassification", "Cash/Bank");
    //SqlCommand cmd = new SqlCommand(searchquery, cn);
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    DataTable table = new DataTable();
    da.Fill(table);
    LstReceipt.DataSource = table;
    LstReceipt.DisplayMember = "LedgerName";
    cn.Close();

C#
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
    if (dataGridView1.CurrentCell.ColumnIndex == 1)
    {
        searchLedger(dataGridView1.CurrentRow.Cells[0].FormattedValue.ToString());       
    }
}
Posted
Updated 14-Oct-19 8:12am
v2
Comments
Richard Deeming 14-Oct-19 14:13pm    
new SqlCommand("Select * from LedgerCreation  Where  ledgerName  like '%" + value + "%' and AddClassification =@AddClassification order by LedgerName", cn);

Don't do it like that!

Your code is vulnerable to SQL Injection[^]. NEVER use string concatenation to build a SQL query. ALWAYS use a parameterized query.

Everything you wanted to know about SQL injection (but were afraid to ask) | Troy Hunt[^]
How can I explain SQL injection without technical jargon? | Information Security Stack Exchange[^]
Query Parameterization Cheat Sheet | OWASP[^]

You already know how to use parameters - you've done it for the AddClassification filter.
SqlCommand cmd = new SqlCommand("Select * from LedgerCreation  Where  ledgerName  like @LedgerName and AddClassification = @AddClassification order by LedgerName", cn);
cmd.Parameters.AddWithValue("@AddClassification", "Cash/Bank");
cmd.Parameters.AddWithValue("@LedgerName", "%" + value + "%");
Maciej Los 14-Oct-19 15:17pm    
My virtual 5!
Member 13608869 15-Oct-19 3:14am    
ok I mistakenly used it in this way
Member 13608869 15-Oct-19 3:16am    
sir how I use this query.
When I type in datagridview cell I want that it's filter listbox data

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900