【问题标题】:Combobox value is not adding to the database组合框值未添加到数据库中
【发布时间】:2013-10-09 17:38:09
【问题描述】:

我的代码没有向数据库添加组合框值。这里可能有什么问题?

private void Submit_Click(object sender, EventArgs e)
{
    string connectionString = @"Data Source=CEX-PC\SQLEXPRESS;"
                              + "Initial Catalog=inventorydatabase;"
                              + "Integrated Security=True";

    SqlConnection con = new SqlConnection(connectionString);

    con.Open();
    string query
        = "INSERT INTO userdetail (username, password, position) VALUES ('"
        + username.Text + "', '" + password.Text + "', '"
        + position.SelectedValue + "' )";

    SqlCommand command = new SqlCommand(query, con);

    command.ExecuteNonQuery();
    con.Close();
}

【问题讨论】:

  • 名称和密码是否插入?
  • Windows 或 Web 应用程序
  • @Bart Friederichs 是的
  • @Steve 没有错误信息
  • 我的代码有什么问题吗?

标签: c# sql winforms sql-server-express


【解决方案1】:

如果它的网络应用程序考虑这个:

string connectionString = @"Data Source=CEX-PC\SQLEXPRESS;Initial     
                     Catalog=inventorydatabase;Integrated Security=True";
                     SqlConnection con = new SqlConnection(connectionString);

con.Open();
string query = "INSERT INTO userdetail (username, password, position) VALUES(@username,@password,@val )";

SqlCommand command = new SqlCommand(query, con);

command.CommandType= CommandType.Text;
command.Parameters.AddWithValue("@username",txt1.text);
command.Parameters.AddWithValue("@password",txt2.text);
command.Parameters.AddWithValue("@val",ddl.SelectedItem.Value);

command.ExecuteNonQuery();

con.Close(); 

【讨论】:

  • 我建议包括using(SqlConnection con = new ...){ con.Open(); ... } 而不是关闭。这将确保如果发生异常,它会得到正确处理。
  • 错误 1 ​​'object' 不包含 'Value' 的定义,并且找不到接受类型为 'object' 的第一个参数的扩展方法 'Value'(您是否缺少 using 指令或程序集参考?)//我像上面一样更改代码现在显示错误
  • command.Parameters.AddWithValue("@val", position.SelectedItem.Value);
  • 你试过了吗? command.Parameters.AddWithValue("@val", position.Items[position.SelectedIndex].Value);
猜你喜欢
  • 1970-01-01
  • 2019-08-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-08
  • 2015-08-03
  • 2012-05-12
  • 1970-01-01
相关资源
最近更新 更多