在服务器端绑定一个 asp.net 复选框
binding an asp.net checkbox on serverside
我有一个搜索功能,其中复选框应该根据这些复选框是多个的数据被选中或未选中,我在服务器端执行这里我有代码
<asp:CheckBox ID="AApBlue" runat="server"Checked='<%#GetBoolean(Eval("blueFlag").ToString()) %>'/>Blue
.cs file
protected Boolean GetBoolean(string val)
{
return val == "Y" ? true : false;
}
我收到一个错误:
object reference null pointer exception
请帮忙!
方法一:
您应该尝试 ItemDataBound 事件,添加标签并将其设置为可见 false:
<asp:CheckBox ID="AApBlue" runat="server" />
<asp:Label ID="Label1" Text='<% # Eval("blueFlag") %>' Visible="false" runat="server" >
</asp:Label>
.CS File:
protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item ||
e.Item.ItemType == ListItemType.AlternatingItem)
{
CheckBox chk = e.Item.FindControl("AApBlue") as CheckBox;
Label lbl = e.Item.FindControl("Label1") as Label;
chk.Checked = (lbl.Text == "Y") ? true : false;
}
}
注意:不要忘记在 DataList 中添加 OnItemDataBound
事件。
<asp:DataList ID="DataList1" OnItemDataBound="DataList1_ItemDataBound" runat="server">
方法二:
您可以在选中的复选框中使用三元运算符:
Checked='<% # (Eval("blueFlag").ToString() == "Y") ? true : false %>'
我有一个搜索功能,其中复选框应该根据这些复选框是多个的数据被选中或未选中,我在服务器端执行这里我有代码
<asp:CheckBox ID="AApBlue" runat="server"Checked='<%#GetBoolean(Eval("blueFlag").ToString()) %>'/>Blue
.cs file
protected Boolean GetBoolean(string val)
{
return val == "Y" ? true : false;
}
我收到一个错误:
object reference null pointer exception
请帮忙!
方法一:
您应该尝试 ItemDataBound 事件,添加标签并将其设置为可见 false:
<asp:CheckBox ID="AApBlue" runat="server" />
<asp:Label ID="Label1" Text='<% # Eval("blueFlag") %>' Visible="false" runat="server" >
</asp:Label>
.CS File:
protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item ||
e.Item.ItemType == ListItemType.AlternatingItem)
{
CheckBox chk = e.Item.FindControl("AApBlue") as CheckBox;
Label lbl = e.Item.FindControl("Label1") as Label;
chk.Checked = (lbl.Text == "Y") ? true : false;
}
}
注意:不要忘记在 DataList 中添加 OnItemDataBound
事件。
<asp:DataList ID="DataList1" OnItemDataBound="DataList1_ItemDataBound" runat="server">
方法二:
您可以在选中的复选框中使用三元运算符:
Checked='<% # (Eval("blueFlag").ToString() == "Y") ? true : false %>'