数据绑定 CheckBoxList 中的第一项未显示
假设我有一个名为“Facility”的 SQL 表,如下所示:
|| FacilityID || Name ||
0 Lecture Theatre
1 Seminar Room
2 Computer Lab
3 Electronics Lab
... ...
并针对 30 多个不同的房间设施继续这样。我正在尝试将这些数据绑定到 ASP.NET (C#) 中的 CheckBoxList,如下所示:
<asp:CheckBoxList ID="FacilityCheckList" AutoPostBack="true" runat="server">
</asp:CheckBoxList>
我用来在 C# 中实现此目的的代码如下所示:
String strSQL;
strSQL = "SELECT * FROM Facility";
SqlCommand cmd3 = new SqlCommand(strSQL, DBConnection);
DBConnection.Open();
SqlDataReader FacilityData;
FacilityData = cmd3.ExecuteReader();
FacilityData.Read();
FacilityCheckList.DataSource = FacilityData;
FacilityCheckList.DataValueField = "Name";
FacilityCheckList.DataBind();
DBConnection.Close();
现在这工作得很好,除了一件事:它不不显示列表中第一项“演讲厅”的复选框。列表中的所有其他设施都显示有一个复选框,但没有 - 我不知道为什么!
这在 SQL 方面不是问题,因为当我单独运行查询时,它会返回完整列表。我不认为它特定于 CheckBoxList,因为当我尝试绑定到 DropDownList 时,我遇到了同样的问题。我很困惑为什么要这样做,所以任何见解将不胜感激!
干杯
Suppose I have an SQL table entitled "Facility" which looks like this:
|| FacilityID || Name ||
0 Lecture Theatre
1 Seminar Room
2 Computer Lab
3 Electronics Lab
... ...
and continues as such for 30-odd different room facilities. I'm trying to Databind these to a CheckBoxList in ASP.NET (C#) which looks like this:
<asp:CheckBoxList ID="FacilityCheckList" AutoPostBack="true" runat="server">
</asp:CheckBoxList>
The code I'm using to achieve this in C# looks like this:
String strSQL;
strSQL = "SELECT * FROM Facility";
SqlCommand cmd3 = new SqlCommand(strSQL, DBConnection);
DBConnection.Open();
SqlDataReader FacilityData;
FacilityData = cmd3.ExecuteReader();
FacilityData.Read();
FacilityCheckList.DataSource = FacilityData;
FacilityCheckList.DataValueField = "Name";
FacilityCheckList.DataBind();
DBConnection.Close();
Now this works absolutely fine, apart from one thing: it doesn't display a CheckBox for the first item in the list, Lecture Theatre. Every other facility in the list shows up with a CheckBox just fine, but not Lecture Theatre - and I have no idea why!
It's not a problem on the SQL side cos when I run the query on its own, it returns the full list. And I don't think it's specific to CheckBoxList, because when I tried binding to a DropDownList instead, I got the same problem. I'm pretty much stumped as to why it is doing this, so any insight would be much appreciated!
Cheers
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
删除该行:
这会导致阅读器向前移动一个档次,从而使您丢失第一个项目
Remove the line:
This is causing the reader to move forward one notch making you lose the first item
不要在
SqlReader
上调用Read()
。只需在调用 ExecuteReader() 后将其指定为 CheckBoxList 的数据源即可。当您将其设置为数据源时,它首先调用 Read(),因此在您的情况下,第一条记录将被跳过。
Don't call
Read()
onSqlReader
. Just assign it as a datasource for your CheckBoxList after callingExecuteReader()
.When you set it as a DataSource, it starts by calling Read(), and thus in your case the first record gets skipped.