GridView加入checkbox

         <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
            DataSourceID="SqlDataSource1"  DataKeyNames="id" >
        <Columns>
         <asp:TemplateField HeaderText="选?择?">
            <ItemTemplate>
            <asp:CheckBox ID="cbx" runat="server" />
            </ItemTemplate>
         </asp:TemplateField>
            <asp:BoundField HeaderText="ID号?码?" DataField="id"/>
            <asp:BoundField HeaderText="Role名?字Á?" DataField="RoleName" />
            <asp:BoundField HeaderText="Role描¨¨述º?" DataField="RoleDescribe" />
        </Columns>
        </asp:GridView>


在上面的代码中添加入:CheckBox 按钮之后

下面的函数 是得到选中行的List<string>

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public List<string> GetSelectedTarget()
        {
            string editID = null;
            string editRoldName = null;
            string editRoleDesc = null;
            List<string> theAll = new List<string>();
            bool isFind = false;
            for (int i = 0; i < this.GridView1.Rows.Count; i++)
            {
                foreach (System.Web.UI.Control control in this.GridView1.Rows[i].Cells[0].Controls)
                {
       
                    if (control is System.Web.UI.WebControls.CheckBox)
                    {
                        System.Web.UI.WebControls.CheckBox cbx = control as System.Web.UI.WebControls.CheckBox;

                        if (cbx.Checked)
                        {
                            editID = this.GridView1.Rows[i].Cells[1].Text.ToString();
                            editRoldName = this.GridView1.Rows[i].Cells[2].Text.ToString() ;
                            editRoleDesc = this.GridView1.Rows[i].Cells[3].Text.ToString();
                           
                            theAll.Add(editID);
                            theAll.Add(editRoldName);
                            theAll.Add(editRoleDesc);
                            isFind = true;
                            break;
                        }
                    }
                }
                if ((editID != "-1") && (isFind == true))
                {
                    isFind = false;
                }
            }
            return theAll;
        }

原文地址:https://www.cnblogs.com/honkcal/p/2229612.html