如何在网格中选中特定的复选框
本文关键字:复选框 网格 | 更新日期: 2023-09-27 18:17:08
我有一个DataTable
,其中大约有五个(这个数字可能会有所不同)产品(DataTable
列是ProductID和ProductName)。我也有一个网格,其中一列是CheckBox
,后面是Product name。
我需要检查DataTable
中存在的CheckBox
。网格中其余的CheckBox
e应该保持未选中状态。我把下面的代码在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>
您不需要遍历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
}
我认为最简单的方法是为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;
}