如何检查网格中的特定复选框?

时间:2011-12-07 14:20:44

标签: c# asp.net telerik

我有一个DataTable,其中包含大约五个(此数字可能会有所不同)的产品(DataTable列是ProductID和ProductName)。我也有一个网格,一列中有CheckBox,之后有产品名称。

我需要检查CheckBox中存在的DataTable es。网格中的其余CheckBox es应保持未选中状态。我在ItemDataBound事件中添加了以下代码,但它不起作用。即使CheckBox显示五种产品,也会取消选中所有DataTable个。

dt = objProduct.GetProducts();

if (dt.Rows.Count > 0)
{
    for (int i = 0; i < dt.Rows.Count; i++)
    {
        if (lblname.Text.ToString() == dt.Rows[i]["ProductName"].ToString())
        {
            CheckBox1.Checked = true;
        }
        else
        {
            if (CheckBox1.Checked != true)
            {
                CheckBox1.Checked = false;
            }
            else
            {
                CheckBox1.Checked = true;
            }
        }
    }
}

这是.aspx标记:

<telerik:GridTemplateColumn UniqueName="PName" Visible="false">
    <ItemTemplate>
        <asp:Label runat="server" ID="lblname" Text='<%#Eval("ProductName") %>'></asp:Label>
        <asp:Label runat="server" ID="lblProductID" Text='<%#Eval("ProductID") %>'></asp:Label>
    </ItemTemplate>
</telerik:GridTemplateColumn>

2 个答案:

答案 0 :(得分:0)

您无需遍历itemdatabound事件中的所有行。参数将控件和数据源范围限定为刚刚绑定的行。

我认为您需要像这样使用ItemDataBound事件并从那里设置复选框

protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)           
{
     //.. this is your data item for the bound row
     GridDataItem item = (GridDataItem)e.Item;  
     string productName = item["ProductName"].ToString();

     //.. set check boxes in here              
     CheckBox myCheckBox = e.Item.FindControl["ckBoxId"] as CheckBox;

     //.. your logic to set check box based on datasource


}

答案 1 :(得分:0)

我认为simpilist是为CheckBox创建一个OnPreRender事件,如:

<asp:TemplateField>
   <ItemTemplate>
     <asp:CheckBox ID="cbSelector" runat="server" OnPreRender="cbSelector_OnPreRender" />
   </ItemTemplate>
   <ItemStyle HorizontalAlign="Center" Width="25px" />
</asp:TemplateField>

然后在后面的代码中:

protected void cbSelector_OnPreRender(object sender, EventArgs e)
{
    MyRecord record = // Get your record for the row
    CheckBox cb = sender as CheckBox;
    cb.Checked = record.Checked;
}