Click here to Skip to main content
15,891,943 members
Please Sign up or sign in to vote.
2.00/5 (2 votes)
See more:
I am getting a null reference in this part of the code...
C#
dr["Column" + counter.ToString()] = cell.Value.ToString();

the metrogrid is just like datagridview

What I have tried:

C#
DataTable dt = new DataTable();
            for (int i = 0; i <= metroGrid1.Columns.Count; i++)
            {
                dt.Columns.Add("Column" + i.ToString() );
            }
foreach (DataGridViewRow row in metroGrid1.Rows)
            {
                DataRow dr = dt.NewRow();
                int counter = 0;
                foreach (DataGridViewCell cell in row.Cells)
                {
                        dr["Column" + counter.ToString()] = cell.Value.ToString();
                        counter++;
                        
                }
                dt.Rows.Add(dr);
            }



now i notice that the datagridview add a 1 data from your original data so if your original data is 50, when you transfer it to datagridview is became 51. how can i prevent it from reading the added data cos it throws a null error? thanks!
Posted
Updated 24-Feb-16 1:35am
v4
Comments
_bluRe_ 23-Feb-16 23:05pm    
is it because of the counter?
[no name] 23-Feb-16 23:26pm    
Just check cell.Value is NULL?
_bluRe_ 23-Feb-16 23:30pm    
no sir. it has a rowindex=49
_bluRe_ 23-Feb-16 23:31pm    
or maybe because it still count the last value which is nothing?
[no name] 24-Feb-16 0:10am    
Just debug and find out at which line the error is creating?

okay.. so that extra row is from the new line, the DataGridView shows for users to add a new line.

just set the DataGridView.AllowUserToAddRows Property[^] to False and that line is gone..
if you need that users can add rows..
you can check if the row you are reading is just an empty new line with the DataGridViewRow.IsNewRow Property (System.Windows.Forms)[^]

as addition .. have a look at this c# - How to make a DataTable from DataGridView without any Datasource? - Stack Overflow[^] accessing the columns by index is sure faster as searching it with that concatenated string ColumnName you use.

and second. Like Sergey already mentioned, you need to check if cell.value is null! I'm pretty sure it can be and you just will get your next Null Exception there!!!
 
Share this answer
 
Comments
_bluRe_ 24-Feb-16 10:26am    
thank you for this sir. null error is gone.
Please see my comments to the question. It's just boring to list what potentially could be null. It could be dr["Column" + counter.ToString()], hardly cell, but cell.Value could again be null. You had to simply check it all, to find the root of the problem. You cannot ask such question every time such things happen, but really have to learn to deal with such very basic situations all by yourself.

Not to worry. This is one of the very easiest cases to detect and fix. It simply means that some member/variable of some reference type is dereferences by using and of its instance (non-static) members, which requires this member/variable to be non-null, but in fact it appears to be null. Simply execute it under debugger, it will stop the execution where the exception is thrown. Put a break point on that line, restart the application and come to this point again. Evaluate all references involved in next line and see which one is null while it needs to be not null. After you figure this out, fix the code: either make sure the member/variable is properly initialized to a non-null reference, or check it for null and, in case of null, do something else.

Please see also: want to display next record on button click. but got an error in if condition of next record function "object reference not set to an instance of an object".

Sometimes, you cannot do it under debugger, by one or another reason. One really nasty case is when the problem is only manifested if software is built when debug information is not available. In this case, you have to use the harder way. First, you need to make sure that you never block propagation of exceptions by handling them silently (this is a crime of developers against themselves, yet very usual). The you need to catch absolutely all exceptions on the very top stack frame of each thread. You can do it if you handle the exceptions of the type System.Exception. In the handler, you need to log all the exception information, especially the System.Exception.StackTrace:
http://msdn.microsoft.com/en-us/library/system.exception.aspx,
http://msdn.microsoft.com/en-us/library/system.exception.stacktrace.aspx.

The stack trace is just a string showing the full path of exception propagation from the throw statement to the handler. By reading it, you can always find ends. For logging, it's the best (in most cases) to use the class System.Diagnostics.EventLog:
http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog.aspx.

Good luck,
—SA
 
Share this answer
 
v2
Comments
F. Xaver 24-Feb-16 3:21am    
5ed
_bluRe_ 24-Feb-16 6:04am    
i updated the question sir. thanks!
Sergey Alexandrovich Kryukov 24-Feb-16 8:18am    
All right, but I already explained everything. You have to deal with you 50 and 51 yourself, as well as null value; I just explained how.
—SA
_bluRe_ 24-Feb-16 10:26am    
thank you for the reminder sir.
Sergey Alexandrovich Kryukov 24-Feb-16 23:37pm    
You're very welcome.
—SA

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