大家好我有这些插入INSTO INTO和SELECT的SqlCommands。我需要添加到prikaz2(INSERT INTO)条件,它只会INSERT INTO这些由CHECKBOX选择的行。
我很长时间都对此感到好奇,但我的代码都没有能够做到这一点。
你们有人会建议我吗?在我看来,我必须添加“WHERE”?
SqlCommand comm = new SqlCommand("Select MAX (ID_K) FROM klient", spojeni);
spojeni.Open();
int max = (int)comm.ExecuteScalar();
spojeni.Close();
for (int i = 0; i < dtg_ksluzby.Rows.Count; i++)
{
SqlCommand prikaz2 = new SqlCommand("INSERT INTO klisluz(text,pocet,akce,subkey) values(@val1,@val2,@val3,@val4) ", spojeni); // here I need to add condition to INSERT INTO only selected rows
prikaz2.Parameters.AddWithValue("@val1", dtg_ksluzby.Rows[i].Cells["text"].Value);
prikaz2.Parameters.AddWithValue("@val2", dtg_ksluzby.Rows[i].Cells["pocet"].Value);
prikaz2.Parameters.AddWithValue("@val3", dtg_ksluzby.Rows[i].Cells["akce"].Value);
prikaz2.Parameters.AddWithValue("@val4", max + 1); spojeni.Open();
prikaz2.ExecuteNonQuery();
spojeni.Close();
}
private void dtg_ksluzby_CellValueChanged(object sender,
DataGridViewCellEventArgs e)
这是我选择row.e的代码。
foreach (DataGridViewRow row in dtg_ksluzby.Rows)
{
DataGridViewCheckBoxCell chk1 = row.Cells[3] as DataGridViewCheckBoxCell;
if (Convert.ToBoolean(chk1.Value) == true)
{
MessageBox.Show("Služba byla vybrána");
}
else
{
}
}
答案 0 :(得分:2)
加入这两个声明怎么样?
INSERT INTO klisluz(text,pocet,akce,subkey)
VALUES (@val1,
@val2,
@val3,
COALESCE((Select MAX (ID_K) FROM klient) + 1, 1)
答案 1 :(得分:2)
所以用forEach替换你的for循环遍历dtg_ksluzby.Rows并执行检查以查看它是否在循环内被检查。
foreach (DataGridViewRow row in dtg_ksluzby.Rows)
{
if (Convert.ToBoolean(row.Cells[3].Value) == true) // check this line here
{
SqlCommand prikaz2 = new SqlCommand("INSERT INTO klisluz(text,pocet,akce,subkey) values(@val1,@val2,@val3,@val4) ", spojeni);
prikaz2.Parameters.AddWithValue("@val1", row.Cells["text"].Value);
prikaz2.Parameters.AddWithValue("@val2", row.Cells["pocet"].Value);
prikaz2.Parameters.AddWithValue("@val3", row.Cells["akce"].Value);
prikaz2.Parameters.AddWithValue("@val4", max + 1);
spojeni.Open();
prikaz2.ExecuteNonQuery();
spojeni.Close();
}
}