我有一个用数据集填充数据的Gridview。我还有一个DropDownlist,它是一个TemplateField的EditTemplate。我想将它绑定到数据集,这样它就可以从它填充数据。我搜索了它,但它似乎不起作用。我是新手。如果不是代码,一些可以帮助我获得一个好的教程。
下面是我的代码片段:
`
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;
}`注释代码就是我尝试过的。
谢谢
发布于 2011-08-03 14:16:20
尝尝这个。
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?
发布于 2011-08-03 13:46:18
我想你已经很接近了-在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),然后对其执行操作。
https://stackoverflow.com/questions/6922142
复制相似问题