检查gridview内的复选框是否已选中?

时间:2013-03-25 04:54:27

标签: c#

我有gridview,其中包含复选框作为templatefield。我已经尝试过如此努力,但我仍然无法获得所需的结果,即如果选中复选框,则执行操作-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
     }
}

每次进入最后的其他地方......为什么?

3 个答案:

答案 0 :(得分:4)

使用逻辑和运算符&&代替按位&运算符来组合if语句中的条件。

更改

if (chk != null & chk.Checked)

if (chk != null && chk.Checked)
根据OP的评论

修改

您需要检查绑定网格的方式,使其在回发时没有绑定。

if(!Page.IsPostBack)
{
       //bind here
} 

答案 1 :(得分:0)

确保您在页面加载时没有再次绑定gridview,如果您那么必须应用IsPostback检查

答案 2 :(得分:0)

试试这个

<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;
    }       
}