1

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

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();

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

这是我插入单值组合框的代码 -

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

我应该如何改进它以仅保存 val1?太感谢了

4

1 回答 1

1

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

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);
于 2013-07-22T13:54:59.260 回答