【问题标题】:Display database values in textbox在文本框中显示数据库值
【发布时间】:2015-09-01 12:41:58
【问题描述】:

我有一个包含 2 列的数据表,IDName,我已经用列 ID 填充了我的组合框。

string Query = "SELECT * FROM [Database]";
OleDbConnection me = new OleDbConnection(connection);
OleDbCommand constr = new OleDbCommand(Query, me);
me.Open();
OleDbDataReader reader = constr.ExecuteReader();    
while(reader.Read())
{
     textBox15.Text = (reader["Name"].ToString());   
}   
reader.Close();

当我从组合框中选择一个项目时,我想从同一行中的列 Name 中检索值。例如,我从数据行 1 中的组合框中选择一个值,它与表 Name

中的数据行 1 匹配

有没有办法做到这一点?


我现在在这里

{
string Query = "SELECT * FROM [Database] where Name ='" + comboBox6.Text + "' ";              string y = textBox15.Text
                OleDbConnection me = new OleDbConnection(connection);
                OleDbCommand constr = new OleDbCommand(Query, me);

                me.Open();
                OleDbDataReader reader = constr.ExecuteReader();
                constr.Parameters.Add(new OleDbParameter("@Name", y));


                while (reader.Read())
                {
                  textBox15.Text = reader["Name"].ToString();



                }

                me.Close();
            }




}

我仍然收到错误"No parameters given for one or more values" 我确定代码是正确的。

【问题讨论】:

    标签: c# database combobox datatable


    【解决方案1】:

    您需要在 SQL 查询中添加一个参数。例如:

    string myName = myComboBox.SelectedItem.Text;
    string Query = "SELECT * FROM [Database] WHERE Name = ?";
    OleDbConnection conn = new OleDbConnection(connection);
    OleDbCommand cmd = new OleDbCommand(Query, conn);
    
    cmd.Parameters.Add(new OleDbParameter("@name", myName));
    
    conn.Open();
    OleDbDataReader reader = cmd.ExecuteReader();
    
    while(reader.Read())
    etc...
    

    我不确定 OLE DB .NET 提供程序的确切语法,但希望这会有所帮助。

    【讨论】:

    • 字符串“myname”代表什么?我正在寻找取决于所选内容的值,而不仅仅是一个值
    • @JamesFoley myName 只是为了说明参数的使用——您可能会将其替换为 myComboBox.SelectedItem.Text 之类的东西(或任何您的组合框 ID)。
    • @JamesFoley 更新了答案以说明从组合框中获取值。
    猜你喜欢
    • 2019-05-14
    • 2013-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-12
    • 2023-03-04
    • 1970-01-01
    相关资源
    最近更新 更多