mardi 9 février 2021

asp net c# get value of specific row in gridview using checkbox

I have a gridview with three columns admin id, admin name and checkbox, and there is a single button below the gridview,

I want to get the value of admin name column and display it in a label when I check the checkbox and then click the button,

I tried doing this and its working fine but I can get one value only for example if I checked two checkbox and then clicked the button it get only the last value, and I want to get them all.

<asp:GridView ID="GridView1"  CssClass="datatable"  runat="server" AutoGenerateColumns="False" AllowPaging="True"  PageSize="10"  
             AllowSorting="True" EnableViewState="false" width="863px" DataSourceID="SqlDataSource1"  >

<Columns >
                                                                                                                                            
    <asp:TemplateField HeaderText="req_id"  >          
         <ItemTemplate >
             <asp:Label ID="label_id" runat="server" Text='<%# Eval("admin_id") %>' ></asp:Label>
         </ItemTemplate>
         <ItemStyle Width="20px" />
         <HeaderStyle  Width="30px" />
         <FooterStyle Width="20px" />  
     </asp:TemplateField>
            
     <asp:TemplateField HeaderText="admin_number">          
         <ItemTemplate >
             <asp:Label ID="label_name" runat="server" Text='<%# Eval("admin_name") %>' ></asp:Label>
         </ItemTemplate>
         <ItemStyle Width="20px" />
         <HeaderStyle  Width="60px" />
         <FooterStyle Width="60px" />  
     </asp:TemplateField>
                                                                                                                                            
    <asp:TemplateField HeaderText="privileges" >
        <ItemTemplate>
            <asp:CheckBox ID="CheckBox_privileges" runat="server"  Checked='<%#   Convert.ToInt32(Eval("prev_1")) == 1 ?  true : false %>'  />

        </ItemTemplate>
        <ItemStyle Width="90px" />
        <HeaderStyle  Width="90px" />
        <FooterStyle Width="90px" />  
    </asp:TemplateField>

 </Columns>

</asp:GridView>

    protected void btn_save(object sender, EventArgs e)
    {

          foreach (GridViewRow row in GridView1.Rows)
          {
           if (row.RowType == DataControlRowType.DataRow)
            {
            CheckBox chkRow = (row.Cells[2].FindControl("CheckBox_privileges") as CheckBox);
            if (chkRow.Checked)
            {
                string name= (row.Cells[1].FindControl("label_name") as Label).Text;

                Label4.Text = name;
            }
            }
          }
          
      
 }



Aucun commentaire:

Enregistrer un commentaire