Kyle Uithoven
Kyle Uithoven

Reputation: 2444

C# DataGridView.Rows.ToString()

I am trying to store the values of each of my rows in a string.

If I try to do DataGridView.Rows.ToString() I get

System.Windows.Forms.DataGridViewRowCollection

Not even close to what I need.

Any ideas?

Upvotes: 3

Views: 13080

Answers (4)

harlam357
harlam357

Reputation: 1491

I think you're looking for something on a per row basis. If so, I suggest the following.

  private static IEnumerable<string> GetRowValues(this DataGridView dgv)
  {
     var list = new List<string>(dgv.Rows.Count);
     foreach (DataGridViewRow row in dgv.Rows)
     {
        var sb = new StringBuilder();
        foreach (DataGridViewCell cell in row.Cells)
        {
           sb.Append(cell.ToString());
        }
        list.Add(sb.ToString());
     }
     return list.AsReadOnly();
  }

Upvotes: 4

Kevin Holditch
Kevin Holditch

Reputation: 5303

Foreach(Var row in DataGridView.Rows)
{
    Foreach(Var cell in row.Cells)
    {
        Var str = cell; // this is the string you want
    }
}

Something like the code above. Excuse the formatting typed on iPad.

Upvotes: 0

Standage
Standage

Reputation: 1517

Use the for each statement to iterate through each row in the Datagridview.

foreach (DataGridViewRow datarow in dataGridView.Rows)
{
    string col1 = datarow.Cells["Col1"].Value.ToString();
    string col2 = datarow.Cells["Col2"].Value.ToString();
    string col3 = datarow.Cells["Col3"].Value.ToString();
}

Upvotes: 2

Jetti
Jetti

Reputation: 2458

You need to do something like this:

StringBuilder sb = new StringBuilder();
for(int row=0; row<DataGridView.Rows.Count; row++)
{
    for(int col=0; col < DataGridView.Columns.Count; col++)
    {
        sb.Append(DataGridView.Row[row][col].ToString());
    }
}
sb.ToString(); // that will give you the string you desire

EDIT I didn't run this through to check that it runs but it should at least give you a starting point. Also, this will give you all rows. If you want just one row, change the variable row to the row number you need (keep in mind that it is zero-based).

Upvotes: 2

Related Questions