简体   繁体   中英

WinForm DataGridView Sorting by string from column c#

I am trying to filter a table of several thousands entries in a datagridview by searching for a string from a textbox which is limited by the column name chosen from a combobox. I'd like the search to happen in real time, updated through the textbox_TextChanged class. I wrote some code that should do what I need, through research. However, whenever I type into the textbox, prompting the textchanged class, I get an error:

"Exception thrown: 'System.Data.SyntaxErrorException' in System.Data.dll"

Note that the datagridview does show all of the data entries prior to typing into the textbox, and the combobox options are exactly the same case as the columns in the datagridview.

My code:

private void searchTerms_TextChanged(object sender, EventArgs e)
    {
        BindingSource bs = new BindingSource();
        bs.DataSource = shareholderDataGrid.DataSource;
        bs.Filter = string.Format(searchItem + " like '%{0}%'", searchTerms.Text.Trim().Replace("'", "''"));
        shareholderDataGrid.DataSource = bs;
    }

shareholderDataGrid is the datagrid, searchItem refers to the string selected from the combobox, and searchTerms refers to the textbox the user types into.

Any help is appreciated, if you need more information ask.

I think the issue might be your call to .Replace("'", "''") . Have you tried without?

I found out why it was throwing that exception! The column name in the data source had spaces in the it, and when I did the same for the combo box it was screwing up. Upon editing the access database table to have the columns be free of spaces, and putting those same changes to the choices in the combo box, it was fixed. It works flawlessly. Here is the final code I used, as I had to make a whole new visual studio project because of an unrelated error.

private void searchBox_TextChanged(object sender, EventArgs e)
    {
        BindingSource bs = new BindingSource();
        bs.DataSource = dataGridView1.DataSource;
        bs.Filter = string.Format(columnChoice.Text + " LIKE '*{0}*'", searchBox.Text.Trim().Replace("'","''"));
        dataGridView1.DataSource = bs;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM