GridView EditItemTemplate中的DataBinding DropDownList

我有一个Gridview,它使用数据集填充数据。 我还有一个DropDownlist,它是TemplateFieldEditTemplate 。 我想将它绑定到数据集,以便它可以从中填充数据。我搜索它但它似​​乎不起作用。我是新手。 如果不是代码,有些人帮助我获得一个好的教程。

inheritance我的代码片段:

`

 protected void Page_Load(object sender, EventArgs e) { if (Page.IsPostBack == false) { BindGrid(); } } private void BindGrid() { //Get dataset //bind DataSet ds = new DataSet("Employees"); SqlConnection con = new SqlConnection("Password=admin;User ID=admin;Initial Catalog=asptest;Data Source=dbsvr"); SqlDataAdapter da = new SqlDataAdapter("select * from employees", con); da.Fill(ds); gvEmp.DataSource = ds; gvEmp.DataBind(); } protected void gvEmp_RowEditing(object sender, GridViewEditEventArgs e) { gvEmp.EditIndex = e.NewEditIndex; BindGrid(); BindDropDown(); } private void BindDropDown() { //DataSet ds = new DataSet("Employees"); //SqlConnection con = new SqlConnection("Password=priyal;User ID=priyal;Initial Catalog=asptest;Data Source=dbsvr"); //SqlDataAdapter da = new SqlDataAdapter("select deptno from employees", con); //da.Fill(ds); //gvEmp.DataSource = ds; //gvEmp.FindControl("ddlDept").DataBind(); } protected void gvEmp_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) { //this means that no index is selected gvEmp.EditIndex = -1; }` 

评论的代码是我尝试过的。

谢谢

试试这个。

 protected void gvEmp_RowEditing(object sender, GridViewEditEventArgs e) { DemoGrid.EditIndex = e.NewEditIndex; BindGrid(); DropDownList dropdown = gvEmp.Rows[e.NewEditIndex].FindControl("DropDownList1") as DropDownList; BindDropDown(dropdown); } private void BindDropDown(DropDownList temp) { string connectionString = "Password=priyal;User ID=priyal;Initial Catalog=asptest;Data Source=dbsvr"; string query = "select deptno from employees"; DataSet dataset = new DataSet("Employees"); using (SqlConnection connection = new SqlConnection(connectionString)) { using (SqlDataAdapter adapter = new SqlDataAdapter(query, connection)) { adapter.Fill(dataset); } } temp.DataSource = dataset; temp.DataTextField = "deptno"; temp.DataValueField = "deptno"; temp.DataBind(); } 

除非您将DropDownList行作为参数传递,否则您的BindDropDown如何识别要绑定的DropDownList

我认为你很接近 – 在BindDropDown()方法中尝试这个:

 // Set the DropDownList's DataSource (originally you were setting the GridView's DataSource ((DropDownList)gvEmp.FindControl("ddlDept")).DataSource = ds; // Call DataBind() on the DropDownList ((DropDownList)gvEmp.FindControl("ddlDept")).DataBind(); 

您需要在GridView中找到控件,将其转换为正确的控件类型(在本例中为DropDownList),然后对其执行操作。