0

I'm testing the code that I got as an example to try, but I'm getting the error

Object reference not set to an instance of an object

I did look into the meaning of this error which I found out it occurs when the object references NULL.

The error is generated on this line

string conString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;

The only problem is I do not know how the NULL is being generated, hence, unable to fix.

How can I resolve this?

protected void Page_Load(object sender, EventArgs e)
{
            if (!IsPostBack)
            {
                string query = "select CountryId, CountryName from Countries";
                BindDropDownList(ddlCountries, query, "CountryName", "CountryId", "Select Country");
                ddlStates.Enabled = false;
                ddlCities.Enabled = false;
                ddlStates.Items.Insert(0, new ListItem("Select State", "0"));
                ddlCities.Items.Insert(0, new ListItem("Select City", "0"));
            }
}

private void BindDropDownList(DropDownList ddl, string query, string text, string value, string defaultText)
{
            string conString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
            SqlCommand cmd = new SqlCommand(query);

            using (SqlConnection con = new SqlConnection(conString))
            {
                using (SqlDataAdapter sda = new SqlDataAdapter())
                {
                    cmd.Connection = con;
                    con.Open();
                    ddl.DataSource = cmd.ExecuteReader();
                    ddl.DataTextField = text;
                    ddl.DataValueField = value;
                    ddl.DataBind();
                    con.Close();
                }
            }
            ddl.Items.Insert(0, new ListItem(defaultText, "0"));
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
ikask
  • 318
  • 2
  • 11
  • 23

1 Answers1

0

There is a file in your project called a web.config. The "conString" references the exact connection in the web.config look at the example in the following documentation for more information. They use northwind instead of conString. If ConString does not exist you will get a null reference which is C# saying I can't find that connection string and I can't continue

https://msdn.microsoft.com/en-us/library/ms178411.aspx

Micah Armantrout
  • 6,781
  • 4
  • 40
  • 66