Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 565
Kyle Uithoven Avatar asked May 21 '26 19:05

Kyle Uithoven


2 Answers

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();
  }
like image 107
harlam357 Avatar answered May 24 '26 09:05

harlam357


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).

like image 40
Jetti Avatar answered May 24 '26 08:05

Jetti



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!