GridView遍历各行的控件和控件事件

<div>
    <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
    
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
            onrowcommand="GridView1_RowCommand" DataKeyNames="ID">
        <Columns>
            <asp:TemplateField>
                <ItemTemplate>
                    <asp:CheckBox ID="CheckBox1" runat="server" />
                </ItemTemplate>
            </asp:TemplateField>
            <asp:BoundField DataField="ID" />
            <asp:BoundField DataField="Name" />
            <asp:TemplateField>
                <ItemTemplate>
                    <asp:Button ID="Button2" runat="server" Text="Button" CommandArgument="ID"/>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
    </div>
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {

            DataTable dt = new DataTable();
            dt.Columns.Add("ID", typeof(string));
            dt.Columns.Add("Name", typeof(string));
            for (int i = 0; i < 5; i++)
            {
                DataRow dr = dt.NewRow();
                dr["ID"] = "ID" + i.ToString();
                dr["Name"] = "Name" + i.ToString();
                dt.Rows.Add(dr);
            }
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        foreach (GridViewRow row in GridView1.Rows)
        {
            CheckBox ckb = (CheckBox)row.Cells[0].FindControl("CheckBox1");
            ckb.Checked = true;
        }
    }
    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandArgument == "ID")
        {
            GridViewRow row = ((Button)e.CommandSource).Parent.Parent as GridViewRow;
            CheckBox ckb = (CheckBox)row.Cells[0].FindControl("CheckBox1");
            ckb.Checked = false;
        }
    }
原文地址:https://www.cnblogs.com/yzj1212/p/2585922.html