I want to take each row in a datagridview and add it to a string variable that I will then print using a custom PrintDocument class. Everything in my program works, except for getting the data from the datagridview into the string variable. I can’t find an example on how to do this. Wouldn’t I just use a “foreach(DataRow Row in dataGridView1)…” to loop through the data table and add it to my string variable? Can someone show me an example of this?
Right now, my code looks like this, but it won’t compile (getting an error message on the way I’m trying to get the value from the column.row into the string. The error message is “The best overloaded method match for ‘System.Windows.Form.DataGridViewRowCollection.This[int]’ has some invalid arguments).:
//Loop through the dataGridView1 and add it to the text
//that we want to print
foreach (DataRow row in dataGridView1.Rows)
{
textToPrint = textToPrint + dataGridView1.Rows[row][0].ToString() + "\t" +
dataGridView1.Rows[row][1].ToString() + "\t" +
dataGridView1.Rows[row][2].ToString() + "\t" +
dataGridView1.Rows[row][3].ToString() + "\t";
}
I recommend a more generic method for doing this so you don’t have to rewrite it in the future. This will also be independent of how many columns you might have in your
DataGridView.