c# - 选中 gridview 中的复选框是否选中?

标签 c#

我有 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/

相关文章:

c# - Web 服务 API 设计 - 输入验证和错误响应?

C# - 将列表转储到下拉列表

c# - 使用 linq 生成合并列表

c# - 我需要在 LINQ 查询后强制 Dispose 吗?

c# - 以较低的位深度保存 jpg(例如 24 到 16)(C#)

c# - 复制 .csproj 的最佳方法是什么(用于创建具有不同命名 exe 的相同应用程序)?

c# - TextBoxFor 和 PasswordFor 元素由于未知原因显示默认值

c# - 在 C# 中访问/解析 "msDS-AllowedToActOnBehalfOfOtherIdentity"AD 属性

c# - 安装了 .Net Core 最新 SDK 但获取 'Framework ' Microsoft.AspNetCore.App',未找到版本 '2.1.0'

c# - 从 PCM 数据中获取音频信息