我是新手。我使用GetSelectedIndices
和foreach
来获取数组中的每个值。
此后,我为insert语句提供了这些值。如何从foreach中的insert语句获取query_TheLoai?我在网络表单上工作
var TheLoaiIds = lbxTheLoai.GetSelectedIndices();
foreach (var TheLoaiId in TheLoaiIds)
{
string query_TheLoai = "SELECT @MaPhim = SCOPE_IDENTITY();INSERT INTO ChiTietTL VALUES ('" + TheLoaiId + "', @MaPhim)";
}
很抱歉尴尬
答案 0 :(得分:0)
var TheLoaiIds = lbxTheLoai.GetSelectedIndices();
string CStr = "YourConnectionString";
string Query = "INSERT INTO ChiTietTL VALUES ('" + TheLoaiId + "', @MaPhim)";
using(var conn = new SqlConnection(CStr))
{
foreach (var TheLoaiId in TheLoaiIds)
{
using(var cmd = new SqlCommand(Query, conn))
{
try
{
cmd.Parameters.AddWithValue("@MaPhim", TheLoaiId);
cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}
答案 1 :(得分:0)
var TheLoaiIds = lbxTheLoai.GetSelectedIndices();
string CStr = "YourConnectionString";
string Query = "SELECT @MaPhim = SCOPE_IDENTITY(); INSERT INTO ChiTietTL VALUES (@TheLoaiId, @MaPhim)";
using(var conn = new SqlConnection(CStr))
{
foreach (var TheLoaiId in TheLoaiIds)
{
using(var cmd = new SqlCommand(Query, conn))
{
try
{
cmd.Parameters.AddWithValue("@TheLoaiId", TheLoaiId);
cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}