简体   繁体   中英

Filtering DataGridView with TextBox (C#)

I'm trying to filter my dgv (via database), by using a textbox.

The problem I run into, is that when I enter a valid item name into the textbox, I get an error that tells me that I didn't enter a valid column name into the textbox...which is weird...because I'm pretty sure I have it looking for items by name, and not looking for columns:/

Here is my code:

     private void button3_Click(object sender, EventArgs e)
        {
        //CLEAR CURRENT DATA IN DGV
        datagridview1.Rows.Clear();
        datagridview1.Refresh();

        Connection();
        sqlconnection.Open();

        using (sqlcmd = new SqlCommand("SELECT * FROM inventory_table WHERE Item= " + searchbox.Text, sqlconnection))
        {
           using (SqlDataReader sqldr = sqlcmd.ExecuteReader())
           {
                while (sqldr.Read())
                {
                    datagridview1.Rows.Add(new object[]{
                    sqldr.GetValue(sqldr.GetOrdinal("Item")),
                    sqldr.GetValue(sqldr.GetOrdinal("Quantity")),
                    sqldr.GetValue(sqldr.GetOrdinal("id")),
                });
                }

                sqldr.Close();
            }
        }
        sqlconnection.Close();
    }

How do I fix this?

It is possible you are referencing the wrong column name in your SQL reads:

sqldr.GetValue(sqldr.GetOrdinal("id")), // Check that "id" and other columns are correct.

Double check the spelling and capitalization of those column references with what is in your database.

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