[英]Cant View CheckBoxList from the database
I have 2 pages , one to add data to database , and the other to edit it, so in the add I have a CheckBoxList , I added them as follow in the database 我有2个页面,一个页面将数据添加到数据库,另一页面进行编辑,因此在添加页面中,我有一个CheckBoxList,如下所示将它们添加到数据库中
URLS : 1,2,3,4,5 and the numbers are the values "keys" from the checkbox URL:1、2、3、4、5,数字是复选框中的“键”值
I used this code 我用了这段代码
String values = "";
foreach (ListItem i in CheckBoxList1.Items)
{
if (CheckBoxList1.Items.Count == 1)
values += i.Value;
else
if (i.Selected)
{
values += i.Value + ",";
}
}
and then I added the values to the database , and it worked perfect , now my problem is in the edit page ,as first I want to show the checked boxes from the database , I used this but its not working 然后我将值添加到数据库中,并且工作正常,现在我的问题在编辑页面中,因为首先我想显示数据库中的复选框,所以我使用了它,但是它不起作用
in the page load 在页面加载中
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
... connection to the database .. etc
try
{
con.Open();
rd = cmd.ExecuteReader();
if (rd.Read())
{
String values = rd["urls"].ToString();//workes perfect
string[] arr = values.Split(',');//works perfect
int x = CheckBoxList1.Items.Count;//this will get me a zero
foreach (ListItem item in CheckBoxList1.Items)// doesnt enter here
{
foreach (string s in arr)
{
if (item.Text == s)
{
item.Selected = true;
}
}
}
.... //exceptions handling
my code for the aspx page 我的aspx页面代码
<asp:CheckBoxList ID="CheckBoxList1" runat="server" DataSourceID="urls_ds"
DataTextField="name" DataValueField="id">
</asp:CheckBoxList>
<asp:SqlDataSource ID="urls_ds" runat="server"
ConnectionString="<%$ ConnectionStrings:testing_cs %>"
SelectCommand="SELECT * FROM [tbl_urls]"></asp:SqlDataSource>
I am getting the checkboxlist from the database using SqlDataSource , and in the page I can see them put as I print the count of the items its zero 我正在使用SqlDataSource从数据库中获取清单列表,并且在页面中我可以看到它们的位置,因为我打印的项目计数为零
where could be the problem ?? 问题可能在哪里??
Thanks 谢谢
Edit : This post describes your problem exactly http://forums.asp.net/t/1488957.aspx/1 , and offers two solutions 编辑:这篇文章准确地描述了您的问题http://forums.asp.net/t/1488957.aspx/1 ,并提供了两种解决方案
Here is what I see 这是我所看到的
if(!Page.IsPostBack)
This means you are on a NEW copy of the page, so CheckBoxList1 is empty until you load it with data. 这意味着您在页面的新副本上,因此CheckBoxList1为空,直到您向其加载数据为止。 which I bet happens further down in your code.
我敢打赌,它会在您的代码中进一步发生。 Just make sure you load it before you use it.
只需确保在使用前加载它即可。
Edit : When using a SqlDataSource to populate controls, you must remember that controls referencing it bind AFTER Page_Load execution. 编辑:使用SqlDataSource填充控件时,必须记住引用它的控件在Page_Load执行之后绑定。 The link above gives two work around methods (either manually calling Control.DataBind or handling the Control.Databound event).
上面的链接提供了两种解决方法(手动调用Control.DataBind或处理Control.Databound事件)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.