0

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();          
 }
1
  • Please improve the indentation! Commented Aug 9, 2014 at 11:57

1 Answer 1

1

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();          
     }
Sign up to request clarification or add additional context in comments.

Comments

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.