数据库某字段保存的为listbox的选项值(多选,值之间以#隔开。如#1#8#10#13),我用下面方法使listbox中对应值的选中。调试时listbox1.Items.Count总是为0,不知为何???
ListBox我是通过拖一个SqlDataSource直接绑定的,明明有多条记录! protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
LoadInfomation();
}
}
private void LoadInfomation()
{
......
string Chance_Type = news_info.companys.ToString();//Chance_Type是从数据库中取出的选项值,形如#1#8#10#13
string[] arrStr = Chance_Type.Substring(1).Split('#');//值是以"#"隔开
foreach (string str in arrStr)
{
for (int i = 0; i < listbox1.Items.Count; i++)//此句总为0,循环不能继续 { if (this.listbox1.Items[i].Value == str)
{
this.listbox1.Items[i].Selected = true;
}
}
}
......
}
ListBox我是通过拖一个SqlDataSource直接绑定的,明明有多条记录! protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
LoadInfomation();
}
}
private void LoadInfomation()
{
......
string Chance_Type = news_info.companys.ToString();//Chance_Type是从数据库中取出的选项值,形如#1#8#10#13
string[] arrStr = Chance_Type.Substring(1).Split('#');//值是以"#"隔开
foreach (string str in arrStr)
{
for (int i = 0; i < listbox1.Items.Count; i++)//此句总为0,循环不能继续 { if (this.listbox1.Items[i].Value == str)
{
this.listbox1.Items[i].Selected = true;
}
}
}
......
}
{
int i = 0;
this.listBox1.Items.add(str);
this.listbox1.Items[i].Selected = true;
i++;
}
}
{
if (!Page.IsPostBack)
{
LoadInfomation();
}
}
private void LoadInfomation()
{
......
string Chance_Type = news_info.companys.ToString();//Chance_Type是从数据库中取出的选项值,形如#1#8#10#13
string[] arrStr = Chance_Type.Substring(1).Split('#');//值是以"#"隔开
for(int i=1 ; i<arrStr.Length ; i++)
{
this.listbox1.add(arrStr[i]);
}
foreach (string str in arrStr)
{
for (int i = 0; i < listbox1.Items.Count; i++)//此句总为0,循环不能继续 { if (this.listbox1.Items[i].Value == str)
{
this.listbox1.Items[i].Selected = true;
}
}
}
......
}
{
this.listbox1.add(arrStr[i]); }
这句不对吧。this.listbox1.Items.Add(arrStr[i]);
自己写了个方法,放在LoadInfomation()之前就可以了!
谢谢各位!问题解决。