protected void gdvList_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DropDownList dropdownList = new DropDownList();
            dropdownList.DataSource = addressList;
            dropdownList.DataTextField = "Name";
            dropdownList.DataValueField = "ID";
            dropdownList.DataBind();
            TableCell tc = new TableCell();
            tc.CssClass = "grid-content left";
            tc.Width = 60;
            tc.Controls.Add(dropdownList);
            e.Row.Cells.AddAt(3, tc);
        }
    }问题是control能加在第3列,可是原有的cell向右移了一个,导致每行cell数量比gridview columns数量多一个。如何替换当前cell,不是加一个。

解决方案 »

  1.   

    e.Row.Cells.AddAt(3, tc)
    改成
    e.Row.Cells[3].Controls.Add(dropdownList);不要增加 TableCell 了
      

  2.   

    用 e.Row.Cells[3].Controls.Add(dropdownList); 当然可以,不过这样会导致另外一个问题。page上还有一个button,当click这个button后,这个dropdownlist会变成空的,而且位置还会向前移一个。如果在
    e.Row.Cells.AddAt(3, tc)
    后面加上
    e.Row.Cells.RemoveAt(_cellIndex + 1);
    又会出现另外一个问题。click button后,
    报错,control 的数量和位置在postback时,和以后还必须一样。Failed to load viewstate.  The control tree into which viewstate is being loaded must match the control tree that was used to save viewstate during the previous request.  For example, when adding controls dynamically, the controls added during a post-back must match the type and position of the controls added during the initial request. 
      

  3.   

    其实,如果操作复杂,完全不用动态创建,你可以先放置一个,根据情况进行显示或者隐藏,或者Remove掉都可以