c# - 你调用的对象是空的

标签 c# asp.net sql

我使用以下代码来检查之前添加到复选框列表中的数据库表中的值,但在此处收到“对象引用未设置为对象的实例”错误:

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

最佳答案

还请考虑重构代码以分离表示逻辑和数据访问逻辑:

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

关于c# - 你调用的对象是空的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4985545/

相关文章:

c# - 在 Entity Framework Core 中表示复杂对象

c# - Sys.WebForms.PageRequestManager pageLoaded事件缓存函数?

c# - WCF 休息。是否可以将从客户端收到的请求记录到数据库中?

c# - 如何在不退出循环的情况下处理异常?

c# - 委托(delegate)的逆变导致错误 "Cannot convert from ... to ..."

asp.net - ASP.NET session 对象中的 Entity Framework 对象上下文?

c# - 通过字节数组转换发送图像,从 java 到 c#

mysql - 带计数的子选择,SQL 查询

sql - 如何将文件路径或URL放入数据库?

mysql - 具有 max 和多个连接的 sql