comboBox项由两列填充INSERT INTO SqlCommand仅一列-SelectedItem

本文关键字:SqlCommand -SelectedItem 一列 INTO 两列 comboBox 填充 INSERT | 更新日期: 2023-09-27 18:24:18

我有下面的代码,它在一个项目(组合框中的行)中用2个值填充组合框,现在我只想在没有tval1(char)的情况下将val1(数字9,2)项目插入到DB中。如果我想根据所选值仅插入数据库val1、val2或val3,SqlCommand INSERT INTO会是什么样子?我知道如何插入简单的填充组合框,但如何设置我想插入数据库的内容?

var cb4 = new SqlCommand("SELECT cena1,cena2,cena3,tcena1,tcena2,tcena3 FROM zajezd WHERE akce=" + zakce.Text, spojeni);
 SqlDataReader dr4 = cb4.ExecuteReader();
        while (dr4.Read())
        {
            string val1 = Convert.ToString(dr4["cena1"]);
            string val2 = Convert.ToString(dr4["cena2"]);
            string val3 = Convert.ToString(dr4["cena3"]);
            string tval1 = Convert.ToString(dr4["tcena1"]);
            string tval2 = Convert.ToString(dr4["tcena2"]);
            string tval3 = Convert.ToString(dr4["tcena3"]);
            comboBox4.Items.Add(val1 + " " + tval1);
            comboBox4.Items.Add(val2 + " " + tval2);
            comboBox4.Items.Add(val3 + " " + tval3);
        }
        dr4.Close();
        dr4.Dispose();
        spojeni.Close();

感谢您花时间阅读本文。我不知道该怎么做。

这是我插入具有单个值的comboBox的代码-

  prikaz.Parameters.AddWithValue("@variable", comboBox1.Text);

我应该如何改进它以只保存val1?非常感谢

comboBox项由两列填充INSERT INTO SqlCommand仅一列-SelectedItem

首先,您必须创建自己的类。

public class ComboboxItem
{
    public string val { get; set; }
    public string tval { get; set; }
    public  string DisplayText {get  { return val + " " + tval;}  }
}

然后,更改您的代码:

var cb4 = new SqlCommand("SELECT cena1,cena2,cena3,tcena1,tcena2,tcena3 FROM zajezd WHERE akce=" + zakce.Text, spojeni);
SqlDataReader dr4 = cb4.ExecuteReader();
while (dr4.Read())
    {
        string val1 = Convert.ToString(dr4["cena1"]);
        string val2 = Convert.ToString(dr4["cena2"]);
        string val3 = Convert.ToString(dr4["cena3"]);
        string tval1 = Convert.ToString(dr4["tcena1"]);
        string tval2 = Convert.ToString(dr4["tcena2"]);
        string tval3 = Convert.ToString(dr4["tcena3"]);
        ComboboxItem cbxItem1 = new ComboboxItem();
        cbxItem1.val = val1;
        cbxItem1.tval = tval1;
        comboBox4.Items.Add(cbxItem1);
        ComboboxItem cbxItem2 = new ComboboxItem();
        cbxItem2.val = val2;
        cbxItem2.tval = tval2;
        comboBox4.Items.Add(cbxItem2);
        ComboboxItem cbxItem3 = new ComboboxItem();
        cbxItem3.val = val3;
        cbxItem3.tval = tval3;
        comboBox4.Items.Add(cbxItem3);
        //Set display member and value member
        comboBox1.DisplayMember = "DisplayText";
        comboBox1.ValueMember = "val";
    }
    dr4.Close();
    dr4.Dispose();
    spojeni.Close();

最后,要插入,必须使用组合框的selectedValue:

prikaz.Parameters.AddWithValue("@variable", comboBox1.SelectedValue);