2个表table1,table2
table1列:id,name        
table2列:id,name,sort1 //table1的name=table2的sort1DropDownList1绑定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());
        }
    }
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {    }错误:这是为什么啊

解决方案 »

  1.   

    应该是 DropDownList1绑定的源 不包括元素:ds.Tables[0].Rows[0]["sort1"].ToString();
      

  2.   

    为DropDownList1的SelectedValue的值必须是在DropDownList1中已经存在这个数据值,不然就会报错的
      

  3.   

    看了下你的代码  貌似DropDownList1绑定的是table1  而你现在却把table2的数据 赋给DropDownList1
    DropDownList1数据源并不包含table2 ,  应该就是这个导致报错的。
      

  4.   


    赞同,DropDownList的selectedValue的值必须是该控件绑定的数据源中存在的值!
    还有个不同的用法:就是selectedItem,可以了解一下!
      

  5.   

    上面应该改为:还有个不同的用法:就是SelectedItem.Text,可以了解一下!
      

  6.   

    这个可以
    其实DropDownList1.SelectedValue这样应该也是可以的,以前用过这种方法,数据库是oracle,现在数据库是SQLserver,同样表结构,同样的语句,效果就不一样,有些时候真的有些莫名其妙啊
      

  7.   

    可以去看看DropDownList的SelectedValue和SelectedItem.Text的用法,这两者之间还是有差别的!