C# – DataBinding DropDownList inside GridView EditItemTemplate

asp.netcgridview

I have a Gridview which populates data witht a Dataset.
I also have a DropDownlist which is a an EditTemplate of a TemplateField.
I want to bind it to the dataset so that it can populate data from it.I searched it but it doesn't seem to work.I'm new to this. If not the code,Some help me to get hands on a good tutorial.

Heres my code snippet:

`

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;
}`

The commented code is what I tried.

Thanks

Best Answer

Try this.

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

Unless you pass the rows DropDownList as a parameter, how would your BindDropDown recognize which DropDownList to bind to?