我有一个包含项目经理姓名的下拉列表和一个包含团队成员姓名的复选框列表。我想要做的是将下拉列表和复选框列表中的选择ID写入数据库。我使用以下代码,但只有checkboxlist中的ID存储在表中。我该怎么做才能同时存储下拉列表中的ID?谢谢你的帮助。
for (int i = 0; i < project_members.Items.Count; i++)
{
if (project_members.Items[i].Selected)
{
SqlParameter[] param = new SqlParameter[1];
param[0] = new SqlParameter("@member_id", SqlDbType.Int);
param[0].Value = project_manager.SelectedValue;
param[0].Value = project_members.Items[i].Value;
for (int j = 0; j < param.Length; j++)
{
cmd2.Parameters.Add(param[j]);
}
cmd2.CommandType = CommandType.Text;
cmd2.ExecuteNonQuery();
cmd2.Parameters.Clear();
}
}
答案 0 :(得分:1)
问题似乎与这些问题有关:
param[0] = new SqlParameter("@member_id", SqlDbType.Int);
param[0].Value = project_manager.SelectedValue;
param[0].Value = project_members.Items[i].Value;
您正在使用param[0]
分配project_manager.SelectedValue;
,然后使用project_members.Items[i].Value;
覆盖{/ 1}
答案 1 :(得分:0)
每次循环迭代都不应创建新参数。
SqlParameter managerParameter = new SqlParameter("@manager_id", SqlDbType.Int);
cmd2.Parameters.Add(managerParameter);
managerParameter.Value = project_manager.SelectedValue;
SqlParameter memberParameter = new SqlParameter("@member_id", SqlDbType.Int);
cmd2.Parameters.Add(memberParameter);
cmd2.CommandType = CommandType.Text;
// For better performance in the loop, you could prepare the query:
cmd2.Prepare();
for (int i = 0; i < project_members.Items.Count; ++i)
{
if (project_members.Items[i].Selected)
{
memberParameter = project_members.Items[i].Value;
cmd2.ExecuteNonQuery();
}
}
请注意,我认为选定的管理者扮演的角色与“普通”成员不同。如果经理应该像任何成员一样处理,请尝试:
SqlParameter memberParameter = new SqlParameter("@member_id", SqlDbType.Int);
cmd2.Parameters.Add(memberParameter);
cmd2.CommandType = CommandType.Text;
// For better performance in the loop, you could prepare the query:
cmd2.Prepare();
memberParameter.Value = project_manager.SelectedValue;
cmd2.ExecuteNonQuery();
for (int i = 0; i < project_members.Items.Count; ++i)
{
if (project_members.Items[i].Selected)
{
memberParameter = project_members.Items[i].Value;
cmd2.ExecuteNonQuery();
}
}