vidya
vidya

Reputation: 1

Retrieve data in dropdown from SQL Server database

I have two tables, one is dept and the other is emp with primary and foreign key relationship from emp.deptid which is a foreign key to dept.id. I have an aspx webpage and I have a dropdown list on it which I want to use to select dname form dropdown. But when I try to execute this code I get an error

Fill: SelectCommand.Connection property has not been initialized.

This is my code:

 protected void Page_Load(object sender, EventArgs e) 
 {
      string cs = ConfigurationManager.ConnectionStrings["practproject"].ConnectionString;

      using (SqlConnection con = new SqlConnection(cs))              
      { }             

      binddeptdropdown();
 }          

 void binddeptdropdown() 
 {            
      SqlDataAdapter da = new SqlDataAdapter("select * from dept", con); 

      DataSet ds = new DataSet();             

      da.Fill(ds, "dept");

      DropDownList1.DataSource = ds;             
      DropDownList1.DataValueField = "dname";             
      DropDownList1.DataTextField = "deptid";             
      DropDownList1.DataBind();          
 }

Upvotes: 0

Views: 40

Answers (1)

Spevy
Spevy

Reputation: 1325

Your closing brace on your using function is in the wrong place, and your connection object needs to be passed to your function.

 protected void Page_Load(object sender, EventArgs e) 
 {
      string cs = ConfigurationManager.ConnectionStrings["practproject"].ConnectionString;

      using (SqlConnection con = new SqlConnection(cs))              
      {             

      binddeptdropdown(con );
      } 


 } 

 void binddeptdropdown(SQLConnection con) 
     {            
          SqlDataAdapter da = new SqlDataAdapter("select * from dept", con); 

          DataSet ds = new DataSet();             

          da.Fill(ds, "dept");

          DropDownList1.DataSource = ds;             
          DropDownList1.DataValueField = "dname";             
          DropDownList1.DataTextField = "deptid";             
          DropDownList1.DataBind();          
     }

Upvotes: 1

Related Questions