你调用的对象是空的

时间:2011-02-13 17:08:18

标签: c# asp.net sql

我使用以下代码检查以前添加到复选框列表中的db表的值,但是在这里得到“对象引用没有设置为对象的实例”错误:

ListItem currentCheckBox = chkbx.Items.FindByValue(rdr["MemberID"].ToString());

这是代码,感谢您的帮助!

SqlDataReader rdr = null;
SqlConnection conn = new SqlConnection(GetConnectionString());
SqlCommand cmd5 = new SqlCommand("SELECT MemberID FROM ProjectIterationMember WHERE ProjectIterationID IN (SELECT ProjectIterationID FROM Iterations WHERE ProjectID = '" + proj_id + "')", conn);

try
{
    conn.Open();
    rdr = cmd5.ExecuteReader();

    CheckBoxList chkbx = (CheckBoxList)FindControl("project_members");
    while (rdr.Read())
    {
        ListItem currentCheckBox = chkbx.Items.FindByValue(rdr["MemberID"].ToString());
        if (currentCheckBox != null)
        {
            currentCheckBox.Selected = true;
        }
    }
}
finally
{
    if (rdr != null)
    {
        rdr.Close();
    }

    if (conn != null)
    {
        conn.Close();
    }
}

2 个答案:

答案 0 :(得分:3)

还要考虑将代码重构为单独的表示逻辑和数据访问逻辑:

private void SelectProjectMembers(int projectId)
{
    CheckBoxList chkbx = (CheckBoxList)FindControl("project_members");
    // verify if chkbx found

    foreach (string memberId in GetMemberIdsFor(projectId))
    {
        ListItem memberItem = chkbx.Items.FindByValue(memberId);

        if (memberItem != null)
            memberItem.Selected = true;
    }
}

private IEnumerable<string> GetMemberIdsFor(int projectId)
{
    List<string> memberIds = new List<string>();
    string query = String.Format("SELECT MemberID FROM ProjectIterationMember WHERE ProjectIterationID IN (SELECT ProjectIterationID FROM Iterations WHERE ProjectID = '{0}')", projectId);

    // using statements will dispose connection, command and reader object automatically
    using (SqlConnection conn = new SqlConnection(GetConnectionString()))
    using (SqlCommand cmd5 = new SqlCommand(query, conn))
    {
        conn.Open();

        using (SqlDataReader rdr = cmd5.ExecuteReader())
        {
            while (rdr.Read())
                memberIds.Add(rdr["MemberID"].ToString());
        }
    }

    return memberIds;
}

答案 1 :(得分:1)

rdr["MemberID"]返回null或chkbx为空,因为无法找到控件。请尝试rdr[0]代替案例,在第二种情况下,请确保找到您的控件。