在下拉列表中设置“值”
本文关键字:设置 下拉列表 | 更新日期: 2023-09-27 18:14:14
我的作业有点问题。当我在GridView中编辑数据时,我尝试为下拉列表设置值。但是当我把我的作业发给我的朋友时,他告诉我他可以毫无错误地运行它(他使用Visual Studio 2010)。我使用Visual Studio 2008和2010,但我不能运行我的代码。请帮帮我。
SqlConnection cn=new SqlConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings["cn"].ToString());
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
LoadProduct();
}
}
public DataSet LoadCategory()
{
SqlDataAdapter da = new SqlDataAdapter("select * from categories", cn);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
private void LoadProduct()
{
//throw new NotImplementedException();
SqlDataAdapter da=new SqlDataAdapter("select * from products,categories where products.categoryID=categories.categoryID",cn);
DataTable db=new DataTable();
da.Fill(db);
GridView1.DataSource=db;
GridView1.DataBind();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
LoadProduct();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
Literal ltr=GridView1.Rows[e.NewEditIndex].FindControl("Literal1") as Literal;
string categoryname = ltr.Text;
GridViewRow row=GridView1.Rows[e.NewEditIndex];
LoadProduct();
DropDownList ddl = row.Cells[3].Controls[1] as DropDownList;
ddl.DataSource = LoadCategory().Tables[0];// when I run there is a error. "Object reference not set to an instance of an object"
ddl.DataTextField = "categoryName";
ddl.DataValueField = "categoryID";
ddl.DataBind();
ddl.Items.FindByText(categoryname).Selected = true;
}
试试这个
ddl.ClearSelection();
ddl.Items.FindByText(categoryname).Selected = true;
在查找DDL时不能这样做吗?
DropDownList ddl = GridView1.Rows[e.NewEditIndex].FindControl("ddl") as DropDownList;
ddl.DataSource = LoadCategory().Tables[0];