Link to home
Start Free TrialLog in
Avatar of mbart
mbart

asked on

Object reference not set to an instance of an object.

I am trying to populate a dropdown list for my datagrid but keep getting the above error.  I know I must be missing something simple but I am new to this and need fast help.  Below is my code.
protected void slatergrid_OnItemDataBound(object sender, DataGridItemEventArgs e)
        {
            //    Get the data from DB to populate the DropDownlist
            SqlConnection dbConn = null;
            SqlCommand dcmd = new SqlCommand();
            string strConnection = null;
            SqlDataReader drReader = null;
            strConnection = System.Configuration.ConfigurationManager.ConnectionStrings["APPLY"].ToString();
            dbConn = new SqlConnection(strConnection);
            dbConn.Open();
            dcmd.Connection = dbConn;
            string SQL = "Select * from RPC";
            dcmd.Connection = dbConn;
            dcmd.CommandText = SQL;
            drReader = dcmd.ExecuteReader();
            if (drReader.HasRows)
            {
                while (drReader.Read())
                {
                    if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
                    {
                         //    Find the drop down control from datagrid items
                        DropDownList list = (DropDownList)
                        e.Item.FindControl("rpc_select");

                        //    Set the text and value properties for the dropdown list to appropriate columns
                        list.DataTextField = Convert.ToString(drReader["description"]);
                        list.DataValueField = Convert.ToString(drReader["RPC"]);
                        list.DataBind();
                    }
                }
               
            }
             
        }
Avatar of Guy Hengel [angelIII / a3]
Guy Hengel [angelIII / a3]
Flag of Luxembourg image

on which line does the error occur?
that is essential to debug the problem.
ASKER CERTIFIED SOLUTION
Avatar of JimBrandley
JimBrandley
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of pallosp
pallosp

In which line do you get the error message?

I suspect that the SQL query returns records that have NULL values. You should check if the fields equal to DBNull.Value before convering them to string.

Another tip: check if the
DropDownList list = (DropDownList)e.Item.FindControl("rpc_select");
line finds the dropdownlist or returns null.

Is RPC both a table name and a column name?
Avatar of mbart

ASKER

Sorry, it was on the description line.  Added check for null and seems to be working.  List is empty but that may be a different issue.