当前位置: 代码迷 >> ASP.NET >> “DropDownList1”有一个无效 SelectedValue,由于它不在项目列表中
  详细解决方案

“DropDownList1”有一个无效 SelectedValue,由于它不在项目列表中

热度:10363   发布时间:2013-02-25 00:00:00.0
“DropDownList1”有一个无效 SelectedValue,因为它不在项目列表中
2个表table1,table2
table1列:id,name        
table2列:id,name,sort1 //table1的name=table2的sort1

DropDownList1绑定table1
GridView1绑定table2
点修改,DropDownList1显示相应的 一级分类


protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            SqlConnection conn = new SqlConnection(ConnectionString);
            string sql = "select * from table1";
            SqlDataAdapter da = new SqlDataAdapter(sql, conn);
            DataSet ds = new DataSet();
            da.Fill(ds);

            DropDownList1.DataSource = ds;
            DropDownList1.DataTextField = "name";
            DropDownList1.DataValueField = "name";
            DropDownList1.DataBind();

            string sql2 = "select * from table2";
            SqlDataAdapter da2 = new SqlDataAdapter(sql2, conn);
            DataSet ds2 = new DataSet();
            da2.Fill(ds2);
            GridView1.DataSource = ds2;
            GridView1.DataBind();
        }
    }
    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        int index = int.Parse(e.CommandArgument.ToString());
        int id = int.Parse(this.GridView1.DataKeys[index].Value.ToString());
        if (e.CommandName == "Edit")
        {
            SqlConnection conn = new SqlConnection(ConnectionString);
            string sql = "select * from table2 where id=" + id + "";
            SqlDataAdapter da = new SqlDataAdapter(sql, conn);
            DataSet ds = new DataSet();
            da.Fill(ds);
            DropDownList1.SelectedValue = ds.Tables[0].Rows[0]["sort1"].ToString();
            //Response.Write(ds.Tables[0].Rows[0]["sort1"].ToString());