包含CheckBoxList的ListView - 未显示为已选中的所选项目

时间:2009-07-28 09:37:20

标签: c# asp.net linq listview checkboxlist

我有一个ListViewEditItemTemplate调用方法onItemEditing

在我的ListViewCheckBoxList使用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; } } } } 方法中将其设置为已选中,也未选中{{1}}。

这是方法:

{{1}}

任何想法如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

问题是在绑定了checkboxlist之后listView被绑定了。

我删除了绑定并且它有效!

答案 1 :(得分:0)

我希望我的回答不会太迟;)

我在ListView中有一个CheckBoxList,它应该像其他控件一样使用DataBind。数据库中的值是此枚举中的计算值:

public enum SiteType
{
    Owner = 1,
    Reseller = 2,
    SubReseller = 4,
    Distributor = 8
    Manufacturer = 16,
    Consumer = 32
}

如果值为24,则表示分销商和制造商(8 + 16)。

我在ListView中的EditItem中添加了一个HiddenField,用于数据绑定值:

<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通过另一个DataSource填充,该DataSource返回一个包含枚举数据的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à!

相关问题