如何检查gridview中的每个复选框

时间:2013-06-07 08:39:40

标签: c# database gridview checkbox

<asp:GridView ID="science_tab" runat="server" AutoGenerateColumns="false"       ShowHeader="false" class="subjects_tab">
<Columns>
<asp:TemplateField>
<ItemTemplate>
    <asp:CheckBox ID="sciencefees_check" runat="server" Text='<%# bind("sub_name") %>' ></asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<label class="rsperhr" for="sciencefees_text">Rupees</label>
    <asp:TextBox ID="sciencefees_text" runat="server" Width="40px"  ></asp:TextBox>
    <label class="rsperhr" for="sciencefees_text">Per Hour</label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

我的科目表中可能有10个项目,因此有10个复选框......

我想要C#代码,它分别检查所有复选框并将检查的复选框交给我,以便我可以将它们插入我的数据库......

2 个答案:

答案 0 :(得分:2)

以下代码将为您提供已检查的ckeckbox ID的列表。

List<int> checkedIDs = new List<int>();

foreach (GridViewRow row in grid1.Rows)
{
  CheckBox chk = (CheckBox)row.FindControl("chkStatus");
  if (chk.Checked){
   checkedMsgIDs.Add(int.Parse(grid1.DataKeys[row.RowIndex].Value.ToString()));
  }
}

答案 1 :(得分:-1)

使用javaScript代码如下:

在aspx页面

<script language="javascript" type="text/javascript">
function checkAllOnGrid() {
    varintRowCount=document.getElementById('ctl00_ContentPlaceHolder1_hdCount').value;
    var chkAll = document.getElementById('ctl00_ContentPlaceHolder1_gvdata_ctl01_chkAll')
    var iStartItemIndex = 2;

    if (chkAll.checked == true) {
        for (i = iStartItemIndex;
             i < parseInt(intRowCount) + parseInt(iStartItemIndex) ; i++) {
            if (i > 9) {
                document.getElementById("ctl00_ContentPlaceHolder1_gvdata_ctl" + i
                                        + "_" + "ChkAction").checked = true;
            } else {
                document.getElementById("ctl00_ContentPlaceHolder1_gvdata_ctl0" + i
                                        + "_" + "ChkAction").checked = true;
            }
        }
    } else {
        for (i = iStartItemIndex;
             i < parseInt(intRowCount) + parseInt(iStartItemIndex) ; i++) {
            if (i > 9) {
                document.getElementById("ctl00_ContentPlaceHolder1_gvdata_ctl" + i
                                        + "_" + "ChkAction").checked = false;
            } else {
                document.getElementById("ctl00_ContentPlaceHolder1_gvdata_ctl0" + i
                                        + "_" + "ChkAction").checked = false;
            }
        }
    }
}

function unCheckHeader() {
    var chkAll=document.getElementById('ctl00_ContentPlaceHolder1_gvdata_ctl01_chkAll')
    if (chkAll.checked == true) { chkAll.checked = false; }
}
</script>

现在将带有ID = hdcount的文本框和gridview中的复选框

现在在aspx.cs页面

protected void fillgrid() {
    DataSet ds = new DataSet();
    ds = obj.FillGrid();
    gvdata.DataSource = ds.Tables[0];
    gvdata.DataBind();
    hdCount.Text = ds.Tables[0].Rows.Count.ToString();
}

此处obj.FillGrid();是您通过存储过程从后端调用值的方法。