gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 21:17:06 24 4
gpt4 key购买 nike

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com