gridview中的参考特定复选框

时间:2013-09-27 12:22:27

标签: c# asp.net gridview checkbox

我有一个GridView,它显示从数据库中恢复的数据。我使用以下代码将TemplateField(CheckBox)制作成GridView:

<asp:GridView ID="dbRecordsContent" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1" OnSelectedIndexChanged="dbRecordsContent_SelectedIndexChanged">
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:CheckBox ID="myCheckBox" runat="server" />
            </ItemTemplate>
        </asp:TemplateField>
        <asp:BoundField DataField="title" HeaderText="title" SortExpression="title" />
        <asp:BoundField DataField="url" HeaderText="url" SortExpression="url" />
        <asp:BoundField DataField="category" HeaderText="category" SortExpression="category" />
        <asp:BoundField DataField="isChecked" HeaderText="isChecked" SortExpression="isChecked" />
    </Columns>
</asp:GridView>

我的网格视图如下所示:

enter image description here

我的问题是:我如何知道检查了哪个复选框ID?例如:

按“删除”按钮时,我想删除第2行。当然我会检查第二个Checkbox,但我怎么知道要删除哪个记录?如何引用代码中的第二个复选框?

2 个答案:

答案 0 :(得分:2)

在删除按钮的单击事件处理程序中,您需要遍历网格中的所有行,如果选中了复选框,则需要执行删除逻辑,如下所示:

protected void DeleteButton_Click(object sender, EventArgs e)
{
    foreach(GridViewRow row in dbRecordsContent.Rows)
    {
        // Only look for check boxes in data rows, ignoring header 
        // and footer rows
        if (row.RowType == DataControlRowType.DataRow)
        {
            if (((CheckBox)row.FindControl("myCheckBox")).Checked)
            {
                // Do delete logic here
            }
        }
    }
}

更新:

要获取行号,请使用GridViewRow.RowIndex属性,如下所示:

int rowNumber = row.RowIndex;

阅读GridViewRow.RowIndex Property了解详情。

答案 1 :(得分:0)

试试这个,

<asp:TemplateField>
        <ItemTemplate>
            <asp:CheckBox ID="myCheckBox" runat="server" AutoPostBack="true"
                       oncheckedchanged="CheckBox1_CheckedChanged" />
        </ItemTemplate>
</asp:TemplateField>

代码方,

protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
    GridViewRow row = ((GridViewRow)((CheckBox)sender).NamingContainer);
    int index = row.RowIndex;
    CheckBox cb1 = (CheckBox)Gridview.Rows[index].FindControl("myCheckBox");
    string checkboxstatus;
    if (cb1.Checked)
    {
      //write your code
    }        
    else
    {
      //write your code
    }
}