从SQL Server数据库中的下拉列表中检索数据

时间:2014-08-09 11:55:23

标签: sql-server c#-4.0

我有两个表,一个是dept,另一个是emp,其中emp.deptid的主键和外键关系是dept.id的外键。我有一个aspx网页,我有一个下拉列表,我想用它来选择dname表格下拉列表。但是当我尝试执行此代码时出现错误

  

Fill:SelectCommand.Connection属性尚未初始化。

这是我的代码:

 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 个答案:

答案 0 :(得分:1)

你的使用函数的右括号位于错误的位置,你的连接对象需要传递给你的函数。

 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();          
     }
相关问题