检查gridview中的复选框是否被选中
本文关键字:是否 gridview 检查 复选框 | 更新日期: 2023-09-27 18:05:44
我有gridview,其中包含复选框作为模板字段。我已经很努力了,但我仍然无法得到想要的结果,也就是说,如果复选框被选中,那么执行操作1或执行操作2,但每次都执行操作2。下面是我的代码,我需要你的帮助。
Gridview代码:<asp:GridView ID="final" runat="server" AutoGenerateColumns="False";>
<Columns>
<asp:BoundField DataField="name" HeaderText="Employee Name" SortExpression="date" />
<asp:BoundField DataField="ldate" HeaderText="Date Of Leave" SortExpression="ldate"
/>
<asp:TemplateField HeaderText="Half/Full">
<ItemTemplate>
<asp:RadioButtonList ID="RadioButtonList1" runat="server">
<asp:ListItem Enabled="true" Value="Half">Half</asp:ListItem>
<asp:ListItem Enabled="true" Value="Full">Full</asp:ListItem>
</asp:RadioButtonList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Approve">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
选中单选和复选框的代码:
DataTable dtable = new DataTable();
dtable.Columns.Add(new DataColumn("Date", typeof(DateTime)));
dtable.Columns.Add(new DataColumn("Half/Full", typeof(float)));
dtable.Columns.Add(new DataColumn("Status", typeof(string)));
Session["dt"] = dtable;
SqlConnection conn = new SqlConnection();
conn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["leave"].ConnectionString;
conn.Open();
foreach (GridViewRow gvrow in final.Rows)
{
dtable=(DataTable)Session["dt"];
CheckBox chk = (CheckBox)gvrow.FindControl("CheckBox1");
if (chk != null & chk.Checked)
{
RadioButtonList rButton = (RadioButtonList)gvrow.FindControl("RadioButtonList1");
if (rButton.SelectedValue == "Half")
{
//perform action-1
}
else
{
//perform action-1
}
}
else
{
perform action-2
}
}
每次进入最后一个else…为什么?
使用逻辑运算符&&
代替位运算符&
来组合if语句中的条件
if (chk != null & chk.Checked)
if (chk != null && chk.Checked)
根据OP
的评论编辑您需要检查您绑定网格的方式,使其不会在回发时绑定。
if(!Page.IsPostBack)
{
//bind here
}
确保在页面加载时没有再次绑定gridview,如果是,则必须应用IsPostback检查
try this
<asp:CheckBox ID="CheckBox1" runat="server" OnCheckedChanged="CheckBox1_CheckedChanged" AutoPostBack="true"/>
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
CheckBox chk = (CheckBox)sender;
GridViewRow gr = (GridViewRow)chk.Parent.Parent;
RadioButtonList RadioButtonList1 = (RadioButtonList)gr.FindControl("RadioButtonList1");
if (RadioButtonList1 != null)
{
RadioButtonList1.Items.FindByText("Full").Selected = true;
}
}