开发者

Problem with writing IDs to DB

I have a dropdown with names of project managers and a checkboxlist with names of team members. What I want to do is write the IDs of selections made from the dropdown and checkboxlist to the DB. I am using the following code, but only IDs from the checkboxlist are stored in the table. What can I do to store the ID from the dropdown simultaneously? Thanks for your help.

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();

            }
}


The problem seems to be with these lines:

param[0] = new SqlParameter("@member_id", SqlDbType.Int);
param[0].Value = project_manager.SelectedValue;
param[0].Value = project_members.Items[i].Value;

you are assigning param[0] with project_manager.SelectedValue; then you are overwriting it with project_members.Items[i].Value;


You should not create new parameters every loop iteration.

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();
    }
}

Note that I assumed that the selected mananger played a different role than the "normal" members. If the manager should be handled like any member, try that:

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();
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜