开发者

ASP.NET Gridview - Checkbox - Select multiple rows and get records

开发者 https://www.devze.com 2023-01-29 08:15 出处:网络
I created a gridview with a checkbox in front of some columns. I need to grab the开发者_开发知识库 data the user is delecting and building an xml file.

I created a gridview with a checkbox in front of some columns. I need to grab the开发者_开发知识库 data the user is delecting and building an xml file.

I can't figure it out. Can someone please help me out in C#.

Here is my code so far.

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataSourceID="ObjectDataSource1"  AllowPaging="True" BackColor="#DEBA84" BorderColor="#DEBA84" 
BorderStyle="None" BorderWidth="1px" CellPadding="3" CellSpacing="2" >
<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />

<Columns>       

<asp:TemplateField>
<HeaderStyle HorizontalAlign="left" />
<HeaderTemplate>
<asp:CheckBox ID="chkSelectAll" ToolTip="Click here to select/deselect all rows"
runat="server" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" />
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="Service Point">
<ItemTemplate>                  
<%# Eval("SERVICEPOINTID")%>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Left" />
<ItemStyle HorizontalAlign="Left" />
</asp:TemplateField>

<asp:TemplateField HeaderText="Start Date">
<ItemTemplate>
<%# Eval("STARTTIME")%>
</ItemTemplate>                 
</asp:TemplateField>

Thank you,

Steve


You can use below code to get values one by one for the checked rows.

foreach (GridViewRow rowItem in GridView1.Rows)
  {
     var chk = (CheckBox)(rowItem.Cells[0].FindControl("chkSelectAll"));

     // chk.checked will access the checkbox state on button click event
     if (chk.Checked)
     {
         //get required values here
     }
  }


ForEach(GridViewRow row in MyGridView.Rows)
{
  if (row.RowType == DataControlRowType.DataRow) //avoid header/footer rows.
  {
    var myCheckBox = (CheckBox)row.FindControl("chkSelect");
    //myCheckBox.Checked tells you if it's checked or not, yay!
    var myPrimaryKey = (GuidOrIntOrSomething)MyGridView.DataKeys[row.RowIndex].Value;
    //now you have your Key and the checkbox for whether the user has checked it 
    //and you can do your update/insert/delete/whatever against the DB.
  }
}

and you really should deal with the excruciating javascript needed to check all the boxes directly using your Check All. It's very counterintuitive and frustrating for users to get a postback when they click that one.

0

精彩评论

暂无评论...
验证码 换一张
取 消