我有一个listcheckedbox,列出了员工编号,我希望能够添加参加培训课程的每位员工,以便在培训课程中显示。但是,当我尝试提交要插入数据库的信息时,它只会添加一个选定的员工。我怎样才能让超过1名员工提交课堂会议?
try
{
string cmdstring = "INSERT INTO [SESSION] (PrincipleName, Comments, SessionDate, SessionName, TellerNum) VALUES (@principle, @comments, @date, @session, @teller)";
using (OleDbCommand cmd = new OleDbCommand(cmdstring, con))
{
cmd.Parameters.AddWithValue("@principle", comboBox12.Text);
cmd.Parameters.AddWithValue("@comments", textBox3.Text);
cmd.Parameters.AddWithValue("@date", dateTimePicker1.Value);
cmd.Parameters.AddWithValue("@session", comboBox1.Text);
cmd.Parameters.AddWithValue("@teller", checkedListBox1.Text);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Submitted Successfully");
}
}
catch (Exception ex)
{
MessageBox.Show("Failed due to " + ex.Message);
}
以下是LarsTech回答
后的更新代码 con.Open();
string cmdstring = "INSERT INTO [SESSION] (PrincipleName, Comments, SessionDate, SessionName, TellerNum) VALUES (@principle, @comments, @date, @session, @teller)";
foreach (int s in checkedListBox1.CheckedItems)
{
using (OleDbCommand cmd = new OleDbCommand(cmdstring, con))
{
cmd.Parameters.AddWithValue("@principle", comboBox12.Text);
cmd.Parameters.AddWithValue("@comments", textBox3.Text);
cmd.Parameters.AddWithValue("@date", dateTimePicker1.Value.ToShortDateString());
cmd.Parameters.AddWithValue("@session", comboBox1.Text);
cmd.Parameters.AddWithValue("@teller", s);
cmd.ExecuteNonQuery();
}
}
con.Close();
MessageBox.Show("Submitted Successfully");
textBox3.Clear();
checkedListBox1.ClearSelected();
comboBox1.Refresh();
comboBox12.Refresh();
dateTimePicker1.Refresh();
答案 0 :(得分:1)
您必须遍历CheckedItems集合:
foreach (string s in checkedListBox1.CheckedItems)
{
using (OleDbCommand cmd = new OleDbCommand(cmdstring, con))
{
cmd.Parameters.AddWithValue("@principle", comboBox12.Text);
cmd.Parameters.AddWithValue("@comments", textBox3.Text);
cmd.Parameters.AddWithValue("@date", dateTimePicker1.Value);
cmd.Parameters.AddWithValue("@session", comboBox1.Text);
cmd.Parameters.AddWithValue("@teller", s);
cmd.ExecuteNonQuery();
}
}