C# 设置dropdownlist的值
我的作业有些问题。我试图在GridView中编辑数据时设置dropdownlist的值。但当我将作业发送给我的朋友时,他告诉我他可以毫无错误地运行作业(他使用Visual Studio 2010)。我使用Visual Studio 2008和2010,但无法运行代码。请帮帮我C# 设置dropdownlist的值,c#,asp.net,ado.net,C#,Asp.net,Ado.net,我的作业有些问题。我试图在GridView中编辑数据时设置dropdownlist的值。但当我将作业发送给我的朋友时,他告诉我他可以毫无错误地运行作业(他使用Visual Studio 2010)。我使用Visual Studio 2008和2010,但无法运行代码。请帮帮我 SqlConnection cn=new SqlConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings["cn"].To
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吗
DropDownList ddl = GridView1.Rows[e.NewEditIndex].FindControl("ddl") as DropDownList;
ddl.DataSource = LoadCategory().Tables[0];
试试这个
ddl.ClearSelection();
ddl.Items.FindByText(categoryname).Selected = true;
为什么你不能运行它?请给我们一个例外。任务?这是家庭作业吗?