Click here to Skip to main content
15,885,979 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I get this error when set value from DataTable to DataGridView Cell Note: I create Columns manually. This is my code

What I have tried:

C#
public void LoadPermissionDetails()
        {
            DataTable dt_Det = new DataTable();
            dt_Det.Clear();
            SqlCommand cmd = new SqlCommand("Select * From PermissionDetails Where Per_id=@Per_id", conn);
            cmd.Parameters.AddWithValue("Per_id", NoTXT.Text);
            conn.Open();
            dt_Det.Load(cmd.ExecuteReader());
            conn.Close();
            cmd = null;
            DataRow[] rows;
            rows = dt_Det.Select("Per_id = '" + NoTXT.Text + "'");
            for (int i = 0; i < rows.Length; i++)
            {
                DataGridView1.CurrentRow.Cells["Colitem"].Value = rows[i][2].ToString();
            }
        }
Posted
Updated 25-Jun-21 6:52am
Comments
Richard Deeming 29-Jun-21 7:18am    
1) You've already filtered the records you are returning by passing a parameter to your query; why would you need to filter them again using the Select method?

2) Inside your loop, you always update the current row, but that doesn't change. Every iteration of your loop sets the same column on the same row. Why not just skip the loop, and update the value based on the last row?

3) Don't use select * from, especially since you're only interested in one column. Explicitly list the column(s) you want to load.

4) Don't store database connections in class-level fields. Instead, create them when you need them, and wrap them in using blocks to ensure they're always disposed of correctly.

5) You don't need to clear the dt_Det variable, since you've only just created it.

DataTable dt = new DataTable();

using (SqlConnection conn = new SqlConnection("..."))
using (SqlCommand cmd = new SqlCommand("SELECT YourColumnName FROM PermissionDetails WHERE Per_id = @Per_id", conn))
{
    cmd.Parameters.AddWithValue("@Per_id", NoTXT.Text);
    
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    da.Load(dt);
}

if (dt.Rows.Count != 0)
{
    DataRow row = dt.Rows[dt.Rows.Count - 1];
    DataGridView1.CurrentRow.Cells["Colitem"].Value = row[0];
}

This is one of the most common problems we get asked, and it's also the one we are least equipped to answer, but you are most equipped to answer yourself.

Let me just explain what the error means: You have tried to use a variable, property, or a method return value but it contains null - which means that there is no instance of a class in the variable.
It's a bit like a pocket: you have a pocket in your shirt, which you use to hold a pen. If you reach into the pocket and find there isn't a pen there, you can't sign your name on a piece of paper - and you will get very funny looks if you try! The empty pocket is giving you a null value (no pen here!) so you can't do anything that you would normally do once you retrieved your pen. Why is it empty? That's the question - it may be that you forgot to pick up your pen when you left the house this morning, or possibly you left the pen in the pocket of yesterday's shirt when you took it off last night.

We can't tell, because we weren't there, and even more importantly, we can't even see your shirt, much less what is in the pocket!

Back to computers, and you have done the same thing, somehow - and we can't see your code, much less run it and find out what contains null when it shouldn't.
But you can - and Visual Studio will help you here. Run your program in the debugger and when it fails, VS will show you the line it found the problem on. You can then start looking at the various parts of it to see what value is null and start looking back through your code to find out why. So put a breakpoint at the beginning of the method containing the error line, and run your program from the start again. This time, VS will stop before the error, and let you examine what is going on by stepping through the code looking at your values.

But we can't do that - we don't have your code, we don't know how to use it if we did have it, we don't have your data. So try it - and see how much information you can find out!
 
Share this answer
 
1. You did not ask a question.
2. Based on your title, that error means that something you are trying to access is null.
3. Look at the line of code that is causing the error and debug it. Put a breakpoint on it, run your code and then see what is null and figure out why.

Only you can do this because we cannot run your code. And it's super simple anyway.
 
Share this answer
 
Comments
Member 13356291 25-Jun-21 12:20pm    
My code failed in this point
DataGridView1.CurrentRow.Cells["Colitem"].Value = rows[i][2].ToString();
RedDk 25-Jun-21 12:49pm    
In THAT case, add Debug.Print statements to the code block. Find the immediate window (under main menu "View" (it's possibly "Call Hierarchy" in VS)) where print statements are made. There are many steps to take when debugging; look up "Debugging applications in C#". Everywhere. As did savoir faire.
SeeSharp2 25-Jun-21 12:55pm    
1. Do you have a field named Colitem in PermissionDetails table?
2. Is CurrentRow null? Your code keeps overwriting the value of CurrentRow.

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