views:

267

answers:

3

I have this loop, which I am using to get the values of all cells within all rows of a gridview and then write it to a csv file. My loop looks like this:

string filename = @"C:\Users\gurdip.sira\Documents\Visual Studio 2008\WebSites\Supressions\APP_DATA\surpressionstest.csv";
StreamWriter sWriter = new StreamWriter(filename);
string Str = string.Empty;

string headertext = "";

sWriter.WriteLine(headertext);

for (int i = 0; i <= (this.GridView3.Rows.Count - 1); i++)
{
    for (int j = 0; j <= (this.GridView3.Columns.Count - 1); j++)
    {
        Str = this.GridView3.Rows[i].Cells[j].Text.ToString();
        sWriter.Write(Str);
    }

sWriter.WriteLine();

} 

sWriter.Close();

The problem with this code is that, when stepping through, the 2nd loop (the one going through the columns) does not begin as the debugger does not hit this loop and thus my file is empty.

Any ideas on what is causing this? The code itself looks fine.

Thanks

+1  A: 

I think the inner loop should access the Cells, not the columns:

    for (int i = 0; i <= (this.GridView3.Rows.Count - 1); i++)
    {

        for (int j = 0; j <= (this.GridView3.Rows[i].Cells.Count - 1); j++)
        {

            Str = this.GridView3.Rows[i].Cells[j].Text.ToString();


            sWriter.Write(Str);
        }
    }
EFrank
A: 

Adding in line numbers, if I understand your question correctly, you're saying that when debugging, you never reach line 8. If that is the case then I would expect your issue is that when you're actually processing through the loop there are no rows in your gridview. To figure out why that is the case, I would recommend looking at where you are in the post cycle for your page

     string filename = @"C:\Users\gurdip.sira\Documents\Visual Studio 2008\WebSites\Supressions\APP_DATA\surpressionstest.csv";//1
     StreamWriter sWriter = new StreamWriter(filename);//2
     string Str = string.Empty;//3
     string headertext = ""; //4
     sWriter.WriteLine(headertext);  //5
     for (int i = 0; i <= (this.GridView3.Rows.Count - 1); i++)   //6
     {         //7
        for (int j = 0; j <= (this.GridView3.Columns.Count - 1); j++)  //8
        { //9
               Str = this.GridView3.Rows[i].Cells[j].Text.ToString();//10
               sWriter.Write(Str);//11
        }//12
        sWriter.WriteLine();//13
      }//14
      sWriter.Close();//15
}//16
Timothy Carter
A: 

That works, thanks!

Blade
You can vote up and/or click the checkmark by the answer that helped.
Timothy Carter