ASP.NET How To Get Multiple Selected Rows From GridView

Last modified: July 17, 2021
public class Stock { public string Name { get; set; } public int Qty { get; set; } } public partial class _Default : Page { protected void Page_Load(object sender, EventArgs e) { var stock = new List<Stock>() { new Stock {Name = "iphone8", Qty= 445}, new Stock {Name = "iphone10", Qty= 445}, new Stock {Name = "iphone11", Qty= 445}, new Stock {Name = "iphone11pro", Qty= 445}, new Stock {Name = "iphone12", Qty= 445}, new Stock {Name = "iphone12pro", Qty= 445}, }; if (!IsPostBack) { GridViewStock.DataSource = stock; GridViewStock.DataBind(); } } protected void ButtonSelect_Click(object sender, EventArgs e) { foreach (GridViewRow item in GridViewStock.Rows) { if ((item.Cells[0].FindControl("Select") as CheckBox).Checked) { var name = item.Cells[1].Text; } } } }
<asp:Button ID="ButtonSelect" runat="server" Text="Multi-Select" OnClick="ButtonSelect_Click" /> <asp:GridView ID="GridViewStock" AutoGenerateColumns="false" runat="server"> <Columns> <asp:templatefield HeaderText="Select"> <itemtemplate> <asp:checkbox ID="Select" runat="server"></asp:checkbox> </itemtemplate> </asp:templatefield> <asp:boundfield DataField="Name" HeaderText="Name"></asp:boundfield> <asp:boundfield DataField="Qty" HeaderText="Qty"></asp:boundfield> </Columns> </asp:GridView>