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>
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;
}
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();
}
}
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With