2011-11-21 145 views
0

我想添加一個空的GridView裏面一排,我厭倦了下面的代碼,但到目前爲止沒有運氣:將行添加到空GridView?

 GridViewRow oRow = new GridViewRow(0, 0, DataControlRowType.DataRow, DataControlRowState.Insert); 
     TableCell oCell = new TableCell(); 
     oCell.Text = "XXX"; 
     oRow.Cells.Add(oCell); 
     gvMemberShip.Controls.Add(oRow); 

注:我跑在Page_Load事件的代碼。

回答

2

我們這樣做的方式是擴展GridView。覆蓋的CreateChildControls,喜歡的東西:

public class CustomGridView : GridView 
{ 
    protected override int CreateChildControls(System.Collections.IEnumerable dataSource, bool dataBinding) 
    { 
     int numRows = base.CreateChildControls(dataSource, dataBinding); 
     //no data rows created, create empty table 
     if (numRows == 0) 
     { 
      //create table 
      Table table = new Table(); 
      table.ID = this.ID; 

      //create a new header row 
      GridViewRow row = base.CreateRow(-1, -1, DataControlRowType.Header, DataControlRowState.Normal); 

      //convert the exisiting columns into an array and initialize 
      DataControlField[] fields = new DataControlField[this.Columns.Count]; 
      this.Columns.CopyTo(fields, 0); 
      this.InitializeRow(row, fields); 
      row.TableSection = TableRowSection.TableHeader; 
      table.Rows.Add(row); 
      this.Controls.Add(table); 
     } 
     return numRows; 
    } 
} 

覆蓋在GridView」的CreateChildControls到一個空表添加到它的時候沒有數據顯示。

+0

此代碼爲我產生一個錯誤「沒有合適的方法來覆蓋」,第二我真的不明白這個代碼的目的,所以如果有人可以解釋。謝謝。 – ykh

0

您可以使用GridView控件的數據源和初始化集合只有1元。 如果您在Page_Load中執行此操作,然後調用DataBind(),則GridView將顯示您的行。

+0

我不要在數據源想要這個,我想在這裏實現的是一個插入行能力。 – ykh