ListView包含CheckBoxList - 选择的项目不显示为检查
问题描述:
我有一个ListView
与EditItemTemplate
调用方法onItemEditing
。ListView包含CheckBoxList - 选择的项目不显示为检查
在我的ListView
我有一个CheckBoxList
绑定使用LINQ
。
在我的onItemEditing
方法中,我试图检查某些CheckBoxes
,如果它们出现在链接用户与扇区的查找表中。
然而,当我加载EditItemTemplate
没有CheckBoxes
,尽管我已经将它们设置为在onItemEditing
方法选择被选中。
这里的方法:
protected void onItemEditing(object sender, ListViewEditEventArgs e)
{
ListView1.EditIndex = e.NewEditIndex;
ListView1.DataBind();
int regId = Convert.ToInt32(((Label)ListView1.Items[e.NewEditIndex].FindControl("LblRegId")).Text);
CheckBoxList cbl = (CheckBoxList) ListView1.Items[e.NewEditIndex].FindControl("chkLstSectors");
//test to see if forcing first check box to be selected works - doesn't work
cbl.Items[0].Selected = true;
SqlConnection objConn = new SqlConnection(ConfigurationManager.ConnectionStrings["DaresburyConnectionString"].ToString());
SqlCommand objCmd = new SqlCommand("select * from register_sectors where register_id= " + regId, objConn);
objConn.Open();
SqlDataReader objReader = objCmd.ExecuteReader();
if (objReader != null)
{
while (objReader.Read())
{
ListItem currentCheckBox = cbl.Items.FindByValue(objReader["sector_id"].ToString());
if (currentCheckBox != null)
{
currentCheckBox.Selected = true;
}
}
}
}
任何想法如何解决这个问题?
答
问题是listView绑定checkboxlist后被绑定了。
我删除了绑定,它的工作原理!
答
我希望我不是我的回答为时已晚;)
我在数据绑定应该像其他控件一个ListView一个CheckBoxList的。在数据库中的值是从该枚举的计算值:
public enum SiteType
{
Owner = 1,
Reseller = 2,
SubReseller = 4,
Distributor = 8
Manufacturer = 16,
Consumer = 32
}
如果该值为24,这意味着分发服务器和生产者(8 + 16)。
我添加了一个HiddenField到EditItem在我的ListView数据绑定的值:
<EditItemTemplate>
<tr>
<td>
<asp:CheckBoxList ID="cblSiteTypes" runat="server" RepeatLayout="Flow"
DataSourceID="ObjectDataSource4" DataTextField="Key" DataValueField="Value" />
<asp:HiddenField ID="hfSiteTypes" runat="server" Value='<%# Bind("SiteType") %>' OnDataBinding="hfSiteTypesBnd" />
</td>
</tr>
<!-- other data... -->
</EditItemTemplate>
的的CheckBoxList通过另一个数据源,它返回与来自枚举数据Dictionary对象填补。在后面的代码中,我使用HiddenField的OnDataBinding方法进行选择:
protected void hfSiteTypesBnd(object sender, EventArgs e)
{
// read the value
HiddenField hf = (HiddenField)sender;
short val = Convert.ToInt16(hf.Value);
// find the checkboxlist
CheckBoxList cblSiteTypes = (CheckBoxList)hf.Parent.FindControl("cblSiteTypes");
// clear the selection (may be not needed)
cblSiteTypes.ClearSelection();
// for each item
foreach (ListItem li in cblSiteTypes.Items)
{
// get the value from each item and...
short v = Convert.ToInt16(li.Value);
// ...look up whether this value is matching or not
if ((val & v) == v) li.Selected = true;
}
}
etvoilà!
你在哪里创建控件?在加载时,在init? – 2009-07-30 03:46:42