2012-09-19 118 views
0

我正在一個asp.net項目。我有一個gridview和rowdatabound我想把一個下拉列表到行的每個單元格。所以我有以下方法。Gridview行與下拉列表

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) 
{ 
    DropDownList ddl = new DropDownList(); 
    ddl.DataSource = getImpacts(); 
    ddl.DataBind(); 
    if (e.Row.RowType != DataControlRowType.Header) 
    { 

     for (int i = 0; i < e.Row.Cells.Count; i++) 
     { 
      e.Row.Cells[i].Controls.Add(ddl); 

     } 
    } 
} 

問題是dropdouwnlist只添加到最後一個單元格!當我調試時,for循環從所有單元格傳遞!這怎麼可能 ?

+0

必須重新創建動態創建的控件回發。由於'RowDataBound'僅在DataView中觸發時,您應該使用'RowCreated'。但是你應該在'RowDataBound'中數據綁定你的'DropDownList': –

回答

1

需要創建下拉列表中的每一列的實例

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) 
{ 
    if (e.Row.RowType != DataControlRowType.Header) 
    { 
     for (int i = 0; i < e.Row.Cells.Count; i++) 
     { 
      DropDownList ddl = new DropDownList(); 
      ddl.DataSource = getImpacts(); 
      ddl.DataBind(); 
      e.Row.Cells[i].Controls.Add(ddl); 
     } 
    } 
} 
+0

在'Row_DataBound'的'Row_Created',數據綁定控件中創建控件。 Othwerwise,當網格不是數據綁定時,你會在回發時遇到問題。 –

1

您可以在迴路中插入,並反覆對每個單元上的每個

 for (int i = 0; i < e.Row.Cells.Count; i++) 
     { 
      DropDownList ddl = new DropDownList(); 
      ddl.DataSource = getImpacts(); 
      ddl.DataBind(); 

      e.Row.Cells[i].Controls.Add(ddl); 
     }