Search code examples
c#gridviewbuttonclick

Get Particular Grid Column value on button click?


MY grid view code

       <asp:GridView ID="grdAccidentMaster" runat="server" AutoGenerateColumns="False"
        Width="80%" BackColor="White" BorderColor="#DEDFDE" BorderStyle="Solid" BorderWidth="1px"
        EmptyDataText="No Records found" CellPadding="4" ForeColor="Black" GridLines="Both"
        DataKeyNames="IncidentNo" OnRowDataBound="grdAccidentMaster_RowDataBound">
        <Columns>
            <asp:BoundField DataField="IncidentNo" HeaderText="IncidentNo" />
            <asp:BoundField DataField="CreatedDate" HeaderText="Created Date" />
            <asp:BoundField DataField="AccidentDate" HeaderText="Accident Date" />
            <asp:BoundField DataField="PoliceStation" HeaderText="Police Station" />
            <asp:BoundField DataField="City" HeaderText="City Name" />
            <asp:BoundField DataField="RoadCondition" HeaderText="Road Condition" />
            <asp:BoundField DataField="RoadFeature" HeaderText="Road Feature" />  
            <asp:TemplateField HeaderText="Print">
             <ItemTemplate>
            <asp:Button runat="server" Text="Click" ID="btnClick" OnClick="btnPrint_click" />
             </ItemTemplate>
            </asp:TemplateField>
         </Columns>
    </asp:GridView>

MY grid view Output

enter image description here

If i click the Click button under Print column. I need to get the IncidentNo value '4022' on onclick function.


Solution

  • Add an event in Gridview :

    OnRowCommand="grdAccidentMaster_OnRowCommand"
    

    Change template for button :

        <ItemTemplate>
           <asp:Button runat="server" Text="Click" ID="btnClick" 
          CommandName="SendIncidentNo"  CommandArgument='<%# Eval("IncidentNo") %>' />                    
        </ItemTemplate>
    

    Code behind :

    protected void grdAccidentMaster_OnRowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName != "SendIncidentNo") return;
        int incidentNo = Convert.ToInt32(e.CommandArgument);
        // do something
    }