【问题标题】:Insert and Update Data from Check Combo-box to SQL server using c#使用 c# 将数据从 Check Combo-box 插入和更新到 SQL Server
【发布时间】:2019-10-18 20:11:57
【问题描述】:

Combobox-Checkbox SQL

我是 C# 新手。我从 NuGet https://www.nuget.org/packages/Common.CheckComboBox/(带有组合框的多个复选框)安装了一个库。如果选中该复选框,则在 SQL Server 中插入 1,否则在 SQL Server 中插入 0。在普通复选框中,我知道如何插入数据,但它在组合框中的多个复选框帮助我解决了问题。

代码:

 string[] color = new string[6] { "Blue", "Red", "Orange", "Pink", "White","Grey" };
 for (int i = 0; i < color.Length; i++)
    {
       checkedComboBox1.Items.Add(color[i]);
    }
 checkedComboBox1.SetItemChecked(1, true);

【问题讨论】:

  • 你用什么访问SQL数据库?您使用的是 .NET Framework SqlClient、EntityFramework 还是其他?你试过什么了。这有点模糊。
  • .NET Framework SqlClient,

标签: c# sql checkbox combobox


【解决方案1】:

使用 .NET Framework 中内置的 SqlClient 类:

using (SqlConnection conn = new SqlConnection())
{
     conn.Open();
     for (int i = 0; i < checkedComboBox1.Items.Count; i++)
     {
         using (SqlCommand cmd = new SqlCommand())
         {
             cmd.Connection = conn;
             bool isChecked = checkedComboBox1.GetItemChecked(i);
             string colour = checkedComboBox1.Items[i].ToString();
             cmd.CommandText = $"UPDATE TableName SET [{colour}] = '{(isChecked ? 1 : 0)}'";
             cmd.ExecuteNonQuery();
          }
     }
     conn.Close();
}

对于一次所有颜色的 INSERT,由于下拉列表是硬编码的字符串数组,您可以这样做,但硬编码不是很好的做法。

string blueChecked = checkedComboBox1.GetItemChecked(0) ? "1" : "0";
string redChecked = checkedComboBox1.GetItemChecked(1) ? "1" : "0";
string orangeChecked = checkedComboBox1.GetItemChecked(2) ? "1" : "0";
string pinkChecked = checkedComboBox1.GetItemChecked(3) ? "1" : "0";
string whiteChecked = checkedComboBox1.GetItemChecked(4) ? "1" : "0";
string greyChecked = checkedComboBox1.GetItemChecked(5) ? "1" : "0";

using (SqlConnection conn = new SqlConnection())
{
     conn.Open();
     using (SqlCommand cmd = new SqlCommand())
     {
          cmd.Connection = conn;
          cmd.CommandText = $"INSERT INTO Colors VALUES ({blueChecked}, {redChecked}, {orangeChecked}, " +
          $"{pinkChecked}, {whiteChecked}, {greyChecked})";
          cmd.ExecuteNonQuery();
     }
     conn.Close();
}

【讨论】:

  • 感谢您的回复我更新了我的图片。我想你明白我的问题是这张图片
  • 请查看更新后的答案,让我知道您的进展情况:)
  • 错误是什么?您可以将 CommandText 从“UPDATE”更改为“INSERT INTO”以插入一行,但这将继续插入新行而不更新任何现有行。
  • cmd.CommandText = $"插入颜色 [{colour}] = '{(isChecked ? 1 : 0)}'";语法错误
  • 抱歉,插入应该是 INSERT INTO Colors (Columns, To, Insert, Into) VALUES (Value, Value, Value, Value)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-23
相关资源
最近更新 更多