设置下拉列表的值

时间:2011-11-12 23:22:30

标签: c# asp.net ado.net

我的任务有问题。当我编辑数据时,我尝试在GridView中为dropdownlist设置值。但当我将我的作业发送给我的朋友时,他告诉我他可以毫无错误地运行它(他使用的是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;        
}

2 个答案:

答案 0 :(得分:1)

试试这个

ddl.ClearSelection();
ddl.Items.FindByText(categoryname).Selected = true;

答案 1 :(得分:0)

在找到你的DDL时你不能这样做吗?

DropDownList ddl = GridView1.Rows[e.NewEditIndex].FindControl("ddl") as DropDownList;
ddl.DataSource = LoadCategory().Tables[0];