简体   繁体   中英

DataGridView to text file on Windows Forms C#

I have a datagridview that I want to write to a text file. Here is my code:

private void WriteToFile_Click(object sender, EventArgs e)
{
    StreamWriter sW = new StreamWriter("list.txt");
    for (int i = 0; i < 6; i++)
    {
        string lines = "";
        for (int col = 0; col < 6; col++)
        {
            lines += (string.IsNullOrEmpty(lines) ? " " : ", ") + 
                dataGridView.Rows[i].Cells[col].Value.ToString();
        }
        sW.WriteLine(lines);
        sW.Close();
    }
}

and when I click the button it gives me an error:

System.NullReferenceException

Joe,

Try using a for each for your loops:

StreamWriter sW = new StreamWriter("list.txt");
foreach (DataGridViewRow r in dataGridView.Rows) {
    string lines = "";
    foreach (DataGridViewCell c in r.Cells) {
        lines += (string.IsNullOrEmpty(lines) ? " " : ", ") + dataGridView.Rows[i].Cells[col].Value == null ? string.Empty : dataGridView.Rows[i].Cells[col].Value;
    }

    sW.WriteLine(lines);
}

one or more values in your grid are null , or, to put it in other words, 'nothing'. So, when you're using accessing dataGridView.Rows[i].Cells[col].Value property, and then converting it to string, you're trying to covertz null to string which then throws exception. You should check for null values, something like this:

(if you're using .net 4.6)

lines += (string.IsNullOrEmpty(lines) ? " " : ", ") + dataGridView.Rows[i].Cells[col].Value?.ToString();

notice the extra question mark after Value

(if you're using older .net)

lines += (string.IsNullOrEmpty(lines) ? " " : ", ") + dataGridView.Rows[i].Cells[col].Value == null ? string.Empty : dataGridView.Rows[i].Cells[col].Value;

Hope this helps.

EDIT: Since you're getting System.ArgumentOutOfRangeException , make sure you're not getting out of grid's bounds - trying to access a row or column to many. To be sure you're in the bound, use

for (int i = 0; i < dataGridView.RowCount; i++)

for your first loop and

for (int col = 0; col < dataGridView.ColumnCount; col++)

for second

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM