0

A nice chap called Darin kindly provided me with some code in order for me to retrieve an image by its file path.

However, when I attempt to execute the code, I receive a "NullReferenceException was unhandled by user code; Use the 'new' keyword to create an object instance" on the first var line.

The code can be found below:

   var connectionString = ConfigurationManager.ConnectionStrings["SomeCN"].ConnectionString;
        using (var cn = new SqlConnection("Data Source=STRSQL04;Initial Catalog=PDC;Integrated Security=True"))
        using (var cmd = cn.CreateCommand())
        {
            cn.Open();
            cmd.CommandText = "Select imageID from accounts where MemberID = FM00012";
            cmd.Parameters.AddWithValue("FM00012",5);
            using (var reader = cmd.ExecuteReader())
            {
                if (reader.Read())
                {
                    var filepath = reader.GetString(0);
                Image1.ImageUrl = filepath;
                }
            }
        }

Can someone point out the error in my ways please?

Apologies as always for asking, what I suspect are, ridiculous questions.

1 Answer 1

1

You don't have a connection string called "SomeCN" (or whatever you're using for real) in your app config, so when you try to access the ConnectionString.ConnectionString parameter, it throws a nullref.

Can you post the contents of your app.config, or at least the ConnectionStrings element, so we can see?

Sign up to request clarification or add additional context in comments.

2 Comments

Ok cool, so I need to set up my connection string in my config. I'll go research how to do that!
Sorted, it was in my webconfig file anyway. Top stuff, thank you for pointing/pushing me in the right direction!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.