2011-02-13 145 views
2

我正在使用以下代碼來檢查以前添加到複選框列表中的數據庫表中的值,但在此處得到'未設置爲對象實例的對象引用'錯誤:未將對象引用設置爲對象的實例

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

Verfy那(CheckBoxList的)的FindControl( 「project_members」)發現你的控制。而且rdr [「MemberID」]不能從數據庫返回空值。 – 2011-02-13 17:11:20

+0

非常感謝lazyberezivsky - 我在手風琴上有了自己的checkboxlist ...現在就開始工作了。 – MiziaQ 2011-02-13 17:27:39

+1

這些問題是練習排除故障的好地方! (即調試器,更緊密的堆棧跟蹤分析和推理,本地測試,分而治之/日誌記錄等) – 2011-02-13 19:17:49

回答

1

要麼rdr["MemberID"]返回null或chkbx是null作爲控制找不到。嘗試使用rdr[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; 
} 
相關問題