Click here to Skip to main content
15,891,136 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Getting error object reference not set to an instance of an object while refreshing again and again and sometimes its work perfectly not able to understand what is the issue. Pin


What I have tried:

<pre>public static DataTable filldt(string qry)
    {
        try
        {
            string connectionString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
            DataTable dt = new DataTable();
            using (con = new SqlConnection(connectionString))
            using (SqlCommand command = new SqlCommand(qry, con))
            using (SqlDataAdapter dataAdapter = new SqlDataAdapter(command))
                dataAdapter.Fill(dt);
            con.Close();
            return (dt);
        }
        catch (Exception ex)
        {
            throw ex;
        }
        //finally
        //{
        //    con.Close();
        //}
    }
Posted
Updated 13-Dec-17 6:45am
Comments
F-ES Sitecore 9-Dec-17 6:37am    
This question is asked every day, moreso where connection strings are involved. Please do basic research like using google before you post, and if you are posting about code that generates an error always say what line the error is on, remember we can't access your system.
Richard Deeming 13-Dec-17 12:32pm    
That method is going to force you to write code which is vulnerable to SQL Injection[^]. NEVER use string concatenation to build a SQL query. ALWAYS use a parameterized query.

Everything you wanted to know about SQL injection (but were afraid to ask) | Troy Hunt[^]
How can I explain SQL injection without technical jargon? | Information Security Stack Exchange[^]
Query Parameterization Cheat Sheet | OWASP[^]
Richard Deeming 13-Dec-17 12:34pm    
Also, if you're going to catch and re-throw an exception, just use throw;, not throw ex; - the latter destroys the stack trace.
catch (Exception ex)
{
    throw;
}


But in this case, since you're not doing anything with the exception, just remove the try..catch block altogether, and let exceptions propagate naturally.

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 yesterdays 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
 
Comments
Oshtri Deka 10-Dec-17 21:43pm    
Oh boy, that is one long explanation for a common error. :)
Anyhow, it is honest and educational.
5.
I completely agree with everything written by OriginalGriff, but I somewhat have need to give you a hint.
Your qry parameter or connection string is null.
It is a good defensive practice to validate input data and connection strings.
i.e.
C#
if(string.IsNullOrWhitespace(qry))
{
    throw new ArgumentNullException(nameof(qry));
}
...and...
C#
var connStringSettings = ConfigurationManager.ConnectionStrings["ConString"];

if(connStringSettings == null || string.IsNullOrWhitespace(connStringSettings.ConnectionString))
{
    // Do something. Throw custom exception. Do some logging. Return null...
    Debug.WriteLine("No connection string with name \"ConString\"");
}
 
Share this answer
 
v2
Comments
Richard Deeming 13-Dec-17 12:43pm    
Good points, but if the connection string is missing from the config file, you'll still get a NRE on the ConfigurationManager.ConnectionStrings["ConString"].ConnectionString call. :)
Oshtri Deka 14-Dec-17 4:12am    
Thanks.
Fixing various problems with your method:
C#
private static void PrepareCommand(SqlCommand command, string query, object[] parameters)
{
    if (parameters != null && parameters.Length != 0)
    {
        string[] names = new string[parameters.Length];
        for (int index = 0; index < parameters.Length; index++)
        {
            string name = $"@p{index}";
            command.Parameters.AddWithValue(name, parameters[index]);
            names[index] = name;
        }
        
        query = string.Format(CultureInfo.InvariantCulture, query, names);
    }
    
    command.CommandText = query;
    command.CommandType = CommandType.Text;
}

public static DataTable filldt(string query, params object[] parameters)
{
    if (string.IsNullOrWhiteSpace(query)) throw new ArgumentNullException(nameof(query));
    
    var connection = ConfigurationManager.ConnectionStrings["ConString"];
    if (connection == null) throw new InvalidOperationException("Connection string not found!");
    
    using (var con = new SqlConnection(connection.ConnectionString))
    using (var command = new SqlCommand(string.Empty, con))
    {
        PrepareCommand(command, query, parameters);
        
        using (var dataAdapter = new SqlDataAdapter(command))
        {
            var dt = new DataTable();
            dataAdapter.Fill(dt);
            return dt;
        }
    }
}

Usage:
C#
string someValue = SomeTextBox.Text;
DateTime someOtherValue = DateTime.Now;
DataTable dt = filldt("SELECT * FROM SomeTable WHERE SomeColumn = {0} And SomeOtherColumn = {1}", someValue, someOtherValue);
 
Share this answer
 

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