DataBinding DropDownList inside GridView EditItemTemplate
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
开发者_如何学GogvEmp.EditIndex = -1;
}`
The commented code is what I tried.
Thanks
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?
I think you were close - try this in the BindDropDown() method:
// 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();
You need to locate the control in the GridView, cast it to the correct type of control (in this case, DropDownList) and then perform actions on it.
精彩评论