Click here to Skip to main content
15,881,089 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hello

i have a datagridview.
I save the data of 3 columns in a txt file.
The third column is entered text by user.
then I save the data in a txt file.
So far so good.
But if some one leaves the third column empty.
then I still want to save the file.
but then i get an error from the compiler.
System.NullReferenceException
I think I should apply an exception but I don't know how.
Please help

What I have tried:

C#
TextWriter sw = new StreamWriter(@"C:\folder\Test.txt", true);
                int rowcount = dataGridView1.Rows.Count;
                for (int i = 0; i < rowcount - 0; i++)
                {
                    sw.WriteLine(dataGridView1.Rows[i].Cells[1].Value.ToString() + "\t"
                                 + dataGridView1.Rows[i].Cells[2].Value.ToString() + "\t"
                                   + dataGridView1.Rows[i].Cells[4].Value.ToString() + "\t");
                }
                sw.Close();
                MessageBox.Show("FILE SAVED");
Posted
Updated 24-Nov-21 8:47am
v2

Taken you use C# 6 or later you can try using Null-conditional operator. For example if the cell itself is null
C#
sw.WriteLine(dataGridView1.Rows[i].Cells[1]?.Value.ToString() + "\t"
+ dataGridView1.Rows[i].Cells[2]?.Value.ToString() + "\t"
+ dataGridView1.Rows[i].Cells[4]?.Value.ToString() + "\t");

or if the value in an existing cell is null
C#
sw.WriteLine(dataGridView1.Rows[i].Cells[1].Value?.ToString() + "\t"
+ dataGridView1.Rows[i].Cells[2].Value?.ToString() + "\t"
+ dataGridView1.Rows[i].Cells[4].Value?.ToString() + "\t");

For more information, see Member access operators and expressions - C# reference | Microsoft Docs[^]
 
Share this answer
 
v2
hypotheses:

1) there is no Column #4: but, if that were true, you'd get an IndexOutOfRange error.

2) the ColumnType of Column #4 is not a standard (TextBox, Button, etc.) ColumnType, but, a custom Control. however, you imply that the user can edit that Column. is #4 a custom Column ? if yes, it needs a ToString implementation that will avoid failure trying to convert null.

so, having ruled out the most likely scenarios, you need to:

1) describe the versions of Visual Studio and C#/FrameWork you are using.

2) is the DataGridView the standard one provided in WinForms ?

TRY this with your DataGridView and look at the output:

when i want to debug a DataGridView, or build a string representation of all its rows/columns/values, i use this:
public string DGVToString(DataGridView dgv)
{
    StringBuilder sb = new StringBuilder();

    for (int i = 0; i < dataGridView1.Rows.Count; i++)
    {
        sb.AppendLine($"Row: {i}");

        for (int j = 0; j < dataGridView1.Columns.Count; j++)
        {
            sb.Append($"Column: {j}\t");
            var value = dataGridView1.Rows[i].Cells[j].Value;

            // using older .NET versions
            value = value == null ? "null" : value.ToString();

            // using newer .NET versions
            // value ??= "null";

            sb.Append($"value: {value}");
            sb.Append("\t");
        }

        sb.AppendLine();
    }

    return sb.ToString();
}

// to save the data:
// using (TextWriter sw = new StreamWriter(@"C:\folder\Test.txt", true", true))
// {
//    sw.WriteLine(DGVToString(dataGridView1));
//    sw.Close();
// }
Note the use of StringBuilder to reduce the number of string allocations and build the output faster. Note the test for 'null that avoids an error when ToString is called on a null vak=lue
 
Share this answer
 
v4
Comments
[no name] 16-Nov-21 21:12pm    
Hi Thanks for jou help
it's working
But now on the end of the text file is one empty line to match.
because if I want to load the txt file back into the datagrid
I get an error from the compiler again
if i manually
in the text file on the last line once i use backspace.
Then I can load the text file back into the datagrid without error.
I use the following code for that

string newline;
while ((newline = file.ReadLine()) != null)
{
string[] Sp_Keram_line = newline.Split(';');
if (File.Exists(Application.StartupPath + "\\images\\" + Sp_Keram_line[1] + ".png"))
{
Bitmap imgx = new Bitmap(Application.StartupPath + "\\images\\" + Sp_Keram_line[1] + ".png");
Bitmap imgxx = new Bitmap(imgx, new Size(143, 107));
dataGridView3.Rows.Add(Sp_Keram_line[0], Sp_Keram_line[1], Sp_Keram_line[2], imgxx, Sp_Keram_line[4]);

}
else
{
Bitmap imgxxx = new Bitmap(Application.StartupPath + "\\NoImageAvailable.png");
Bitmap imgxxxx = new Bitmap(imgxxx, new Size(143, 107));
dataGridView3.Rows.Add(Sp_Keram_line[0], Sp_Keram_line[1], Sp_Keram_line[2], imgxxx, Sp_Keram_line[4]);

}
}
BillWoodruff 16-Nov-21 21:51pm    
"if I want to load the txt file back into the datagrid I get an error from the compiler again"

I wish I were psychic :) What error: where did it occur ?

Set break-points and single-step through your code (F11) until you find exaxtly where an error occurs.
You're already using a TextWriter, so the simplest solution would be:
C#
using (TextWriter sw = File.AppendText(@"C:\folder\Test.txt"))
{
    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        sw.Write(row.Cells[1].Value);
        sw.Write('\t');
        sw.Write(row.Cells[2].Value);
        sw.Write('\t');
        sw.Write(row.Cells[3].Value);
        sw.WriteLine();
    }
}

MessageBox.Show("FILE SAVED");
 
Share this answer
 
v2
Comments
[no name] 17-Nov-21 7:04am    
HiIf use you code.
I cat error Compiler Error CS1061
Richard Deeming 17-Nov-21 7:06am    
Try replacing var row in ... with DataGridViewRow row in ....

If that doesn't work, you'll need to specify which line the error is pointing to.
[no name] 17-Nov-21 7:22am    
Hello
this works.
Is it also possible if one row and the last cell is empty lets say cell[3]
that this line will not save and the rest will
Thanks in advice
Richard Deeming 17-Nov-21 7:24am    
Yes; just add a check within the foreach loop. For example:
foreach (DataGridViewRow row in dataGridView1.Rows)
{
    object value = row.Cells[3].Value;
    if (value is null || string.IsNullOrEmpty(Convert.ToString(value))) continue;
    
    sw.Write(row.Cells[1].Value);
    sw.Write('\t');
    sw.Write(row.Cells[2].Value);
    sw.Write('\t');
    sw.Write(value);
    sw.WriteLine();
}
[no name] 17-Nov-21 7:30am    
Thanks
This works

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900