Click here to Skip to main content
15,889,462 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello,

I have been trying to get the values from DataGridView. My stupid logic works a bit when accessing the individual cells of the Data Grid Row.
This is the the code that I am using.

C#
private void btn_fetch_Click(object sender, EventArgs e)
        {
            string result = "";
            string part1 = "";
            string part2 = "";

            for (int i = 1; i <= DGV_CsvFile.Rows.Count; i++)
            {
                part1 = DGV_CsvFile.Rows[i].Cells[0].Value.ToString();
                part2 = DGV_CsvFile.Rows[i].Cells[1].Value.ToString();
                result =result + part1+" : "+part2+"\n";
            }
                        
        }

But the problem comes when it completes its iteration, the following exception comes on my face. :(

"Object reference not set to an instance of an object."
and it selects the first line of the loop.

Need urgent help fellows.
Thanx in advance.
Posted
Updated 21-Jul-10 6:33am
v2
Comments
Sandeep Mewara 21-Jul-10 12:33pm    
Use PRE tags to format the code part. It makes the question readable.

Error is in this part of code:
C#
for (int i = 1; i <= DGV_CsvFile.Rows.Count; i++)            {                
   part1 = DGV_CsvFile.Rows[i].Cells[0].Value.ToString();                
   part2 = DGV_CsvFile.Rows[i].Cells[1].Value.ToString();                
   result =result + part1+" : "+part2+"\n";            
}

Well, indexing in the Datagrid rows start from zero (0) and not one.


If you have 5 rows, you are trying to access 1 to 5 instead it should be 0 to 4.

Make the following change:
C#
for (int i = 0; i < DGV_CsvFile.Rows.Count; i++)

i started from zero and the limiting condition is till rowCount.
 
Share this answer
 
v2
Check if any of the values in the cells are null.
If they are you need to modify your code to check for null conditions before using ToString().
 
Share this answer
 
Thanks for quick responses but I have checked the loop while starting it like this

for (int i = 0; i < DGV_CsvFile.Rows.Count-1; i++)

as the last cell is null. In this case, the exception is removed but I cant get my results either.

Thanx for the responses.
 
Share this answer
 
Comments
Sandeep Mewara 21-Jul-10 13:41pm    
Did you tried what I said? Copy paste it and try. Mark the answer accepted only once your issue resolves.

P.S. : Use comments feature to interact with answers.

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