我有 gridview,其中包含作为模板字段的复选框。我已经很努力了,但我仍然无法得到想要的结果,也就是说,如果复选框被选中,则执行 action-1,否则执行 action-2,但每次它都在执行 action-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>
我为检查 radio 和复选框所做的代码:
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 的评论编辑
您需要检查您绑定(bind)网格的方式是否在回发时未绑定(bind)它。
if(!Page.IsPostBack)
{
//bind here
}
关于c# - 选中 gridview 中的复选框是否选中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15607897/