Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get GridView values from asp:BoundField?

I have a GridView that retrieves values from a DataSource that joins two tables, and I need to get those values in the code-behind and pass them as a String. Any ideas on what would be the best approach? Below is my GridView in aspx:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
        DataSourceID="SqlDsPoNumber" EnableModelValidation="True" Visible="True" 
        DataKeyNames="PO_NUMBER,SITE_NAME">
        <Columns>
            <asp:BoundField DataField="PO_NUMBER" HeaderText="PO_NUMBER" 
                SortExpression="PO_NUMBER" />
            <asp:BoundField DataField="SITE_NAME" HeaderText="SITE_NAME" 
                SortExpression="SITE_NAME" />
        </Columns>
</asp:GridView>
like image 912
Jacman Avatar asked Apr 07 '14 22:04

Jacman


3 Answers

You can try the foreach loop to accomplish your requirement which binds the GridViewRow class to your GridView Source.

foreach (GridViewRow gr in GridView1.Rows)
{         
    string cell_1_Value = gr.Cells[0].Text; 
    string cell_2_Value = gr.Cells[1].Text; 
}
like image 109
karz Avatar answered Oct 11 '22 12:10

karz


As you know, the Grid View has multiple rows. So you can get the values from any of the rows.

Getting it using the Data Keys:

var ponumber = GridView1.DataKeys[rowIndex].Values[0].ToString();
var sitename = GridView1.DataKeys[rowIndex].Values[1].ToString();

Getting it by cells:

// easiest way, but not the most recommended.
var ponumber = GridView1.Rows[rowIndex].Cells[0].Text; // try 0 or 1

you can also get the data in the Row Data Bound Event:

protected void GridView1_RowDataBound(Object sender, GridViewRowEventArgs e)
{
     if(e.Row.RowType == DataControlRowType.DataRow)
     {
       var ponumber = GridView1.DataKeys[e.Row.RowIndex].Values[0].ToString();
       var sitename = GridView1.DataKeys[e.Row.RowIndex].Values[1].ToString();
     }
}
like image 27
Raja Nadar Avatar answered Oct 11 '22 12:10

Raja Nadar


foreach (GridViewRow gr in userGrid.Rows)
{
    CheckBox check = (CheckBox)gr.FindControl("chkSelect");
    if (check.Checked == true)
    {
        string order = userGrid.Rows[gr.RowIndex].Cells[3].Text;
        gl.updatetracking (order);
    }
}
like image 4
mohan prasath Avatar answered Oct 11 '22 14:10

mohan prasath