abc
abc

Reputation: 57

How to extract rows from gridview in asp.net c#

I have created datatable kept in session & assigned to gridview.I have to extract those records ,for that i have written code as follows but its giving value as null :

//To find gridview in Formview1
    GridView GridView1 = (GridView)Formview1.FindControl("GridView1");
    GridView1.DataSource = (DataTable)Session["tabdetails"];
    GridView1.DataBind();

    string str, str1, str2, str3, str4, str5, str6;
    for (int i = 0; i < GridView1.Rows.Count; i++)
    {
        str = GridView1.Rows[i].Cells[0].Text;
        str1 = GridView1.Rows[i].Cells[1].Text;
        str3 = GridView1.Rows[i].Cells[2].Text;
        str4 = GridView1.Rows[i].Cells[3].Text;
        str5 = GridView1.Rows[i].Cells[4].Text;
    }

Please suggest me to do right changes? Thank you. Asp.net c#

Upvotes: 0

Views: 15653

Answers (3)

Carter Medlin
Carter Medlin

Reputation: 12495

If you have controls in your gridview cells, the Text value will be empty. If you have a simple textbox you should modify your code to use the "Controls" collection.

str = ((TextBox)GridView1.Rows(i).Cells(0).Controls(1)).Text;

Use Index [1] instead of [0] because typically index [0] will be a literal control.

Upvotes: 0

Pankaj Agarwal
Pankaj Agarwal

Reputation: 11309

You can extract grid view rows using for each loop

foreach (GridViewRow GR in GridView1.Rows)
{
     if (GR.RowType == DataControlRowType.DataRow)
        {                    
             string myField = GR.Cells[1].Text;

             // You can also find grid view inside controls here

             TextBox tb = (TextBox)tt.FindControl("TextBox1");
        }
}

Upvotes: 2

James Johnson
James Johnson

Reputation: 46077

Use data keys to store the values that you need to retrieve.

<asp:GridView ID="GridView1" runat="server" DataKeyNames="SomeColumnName, AnotherColumnName, SomeOtherColumnName" ... >

And in your code behind:

for (int i = 0; i < GridView1.Rows.Count; i++)
{
    GridViewRow row = GridView1.Rows[i];
    string str = GridView1.DataKeys[row.RowIndex]["SomeColumnName"];
}

Upvotes: 1

Related Questions