vijay rags

vijay rags

  • NA
  • 68
  • 163.3k

How to Bind dropdown list from code behind with data from database.

Aug 12 2012 2:56 AM
Dear All,

                 I want to populate a dropdownlist from database in code behind. I tried with the following code but while binding it is throwing an error "Object Reference not set to an Instance". Please find the code appended.Thanks in advance.

Code:

Sample.aspx:

    <asp:DropDownList ID="ddlSample" runat="server"  CssClass="textbox" Width="38%"></asp:DropDownList>


Sample.aspx.cs

 System.Data.SqlClient.SqlConnection conn = null;
                SqlDataReader drFailureCode = null;
                string sqlQuery =  string.Empty;

 System.Data.SqlClient.SqlConnection conn = null;
                SqlDataReader drFailureCode = null;
                string sqlQuery =  string.Empty;
                sqlQuery = "select distinct * from <tablename>";
                conn = SqlHelperConnection.getConnection();
                drFailureCode = SqlHelper.ExecuteReader(conn, CommandType.Text, sqlQuery);

                if (drFailureCode.HasRows)
                {
                    ddlSample.DataSource = drFailureCode;
                    ddlSample.DataTextField = "FailureID";
                    ddlSample.DataValueField = "FailureName";
                    ddlSample.DataBind();
                }
                drFailureCode.Close();
                ddlSample.Items.Insert(0, new ListItem("--Select--", "0"));


Thanks In Advance.

     

Answers (7)