根据名字填充下拉列表

时间:2012-10-24 08:08:33

标签: c# asp.net

  

可能重复:
  Populate dropdownlist inside a gridview

我有一个下拉列表,我在gridview中填充它。在第一列我有Firstname,在第二列我有一个DDL,我想加载与firstname相关联的姓氏,我怎么能实现这个?

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();


        }

    }

1 个答案:

答案 0 :(得分: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();

}

}