简体   繁体   English

使用TextBox(C#)过滤DataGridView

[英]Filtering DataGridView with TextBox (C#)

I'm trying to filter my dgv (via database), by using a textbox. 我正在尝试通过使用文本框来过滤dgv(通过数据库)。

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: 您的SQL读取中可能引用了错误的列名:

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. 仔细检查这些列引用的拼写和大写与数据库中的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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