如何将组合框中的每个值转换为sql数据库

时间:2018-01-26 15:21:17

标签: c# sql database visual-studio combobox

好的,这就是我的代码。一切正常并保存到数据库中。 但是,它只存储组合框中显示的当前值。 我希望它存储所有3个值,因为每个值都有自己的复选框。 我将如何编写保存3个值的相应内容以及相应的数据库复选框(sql)?

Form     ,代码

    private void button1_Click(object sender, EventArgs e)
    {
        if (con.State == ConnectionState.Closed)
        {

            con.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandText = "insert into cloggingInfo(Date, PID, Operator, Type)values('"+labelTime.Text+"', '" + cboStatePid.Text + "', '" + cboStateOperator.Text + "', '" + cboStateType.Text + "')";
            cmd.ExecuteNonQuery();
            cmd.Dispose();
            con.Close();
            MessageBox.Show("Start added succesfully");
            listView1.Items.Clear();
            AddToListView();
        }
    }

2 个答案:

答案 0 :(得分:0)

尝试使用“combobox.SelectedItem”或“combobox.SelectedValue”。如果你的组合框填充了数据源,你需要为它定义“DisplayMember”和“ValueMember”。

 private void button1_Click(object sender, EventArgs e)
    {
        if (con.State == ConnectionState.Closed)
        {

            con.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandText = "insert into cloggingInfo(Date, PID, Operator, Type)values('"+labelTime.Text+"', '" + cboStatePid.SelectedItem+ "', '" + cboStateOperator.SelectedItem+ "', '" + cboStateType.SelectedItem+ "')";
            cmd.ExecuteNonQuery();
            cmd.Dispose();
            con.Close();
            MessageBox.Show("Start added succesfully");
            listView1.Items.Clear();
            AddToListView();
        }
    }

答案 1 :(得分:0)

尝试获取每个组合框的组合框项目,如下所示,然后保存。

private void button1_Click(object sender, EventArgs e) { StringBuilder comboBox1Items = new StringBuilder(); foreach (var item in comboBox1.Items) { comboBox1Items.Append(item + " "); } string cb1Items = comboBox1Items.ToString(); }