2012-10-24 160 views
-1

可能重复:
Populate dropdownlist inside a gridview填充下拉列表根据名字

我有一个下拉列表,我填充它一个gridview.In内的第一列我有名字和在第二列我有一个DDL,我想加载与名字相关的姓氏我怎么能实现这?

Protected void GridView1_RowDataBound1(object sender, GridViewRowEventArgs e) 
    { 
     if (e.Row.RowType == DataControlRowType.DataRow) 
     { 
      con.Open(); 
      var ddl = (DropDownList)e.Row.FindControl("DropDownList1"); 
      //int CountryId = Convert.ToInt32(e.Row.Cells[0].Text); 
      SqlCommand cmd = new SqlCommand("select FirstName,LastName from Profile_Master" , con); 
      SqlDataAdapter da = new SqlDataAdapter(cmd); 
      DataSet ds = new DataSet(); 
      da.Fill(ds); 
      con.Close(); 
      ddl.DataSource = ds; 
      ddl.DataTextField = "LastName"; 
      ddl.DataValueField = "FirstName"; 
      ddl.DataBind(); 


     } 

    } 

回答

0
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) 
     { 


      if (e.Row.RowType == DataControlRowType.DataRow) 
      { 

SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=dbname;Integrated Security=True"); 

       SqlCommand cmd = new SqlCommand("select lastname from Profile_Master where firstname='" + e.Row.Cells[0].Text + "'", con); 
       SqlDataAdapter adp = new SqlDataAdapter(cmd); 
       System.Data.DataSet DS=new System.Data.DataSet(); 
       adp.Fill(DS); 



       Control Ctr = e.Row.FindControl("ddl"); 

       DropDownList dd = (DropDownList) Ctr; 
       dd.DataSource = DS; 
       dd.DataTextField = "LastName"; 
       dd.DataValueField = "LastName"; 
       dd.DataBind(); 

} 

} 
+0

当我不喜欢这个我无法加载DDL时,DDL是空 –

+0

你是说,你是无法获得的数据为DDL?我已经测试了这个代码及其工作。你可以请你发布你的代码。 –

+0

dd.DataSource = ds;在这里我得到的对象引用未设置为对象错误的实例。 无法将数据读入DDL –