2014-09-03 29 views
0

我有一個GridView,其中的列動態添加。但是,在回發時,列不再存在。動態Gridview列在回發中找不到

我知道,動態創建的項目必須在回調後重新創建,即使創建列代碼成功執行,但GridView不包含任何列。

protected void gvUsers_RowCreated(object sender, GridViewRowEventArgs e) 
    { 
     if (e.Row.RowType == DataControlRowType.Header) 
     { //creating column 
      List<Module> listModule = getModules(); 
       foreach (Module m in listModule) 
       { 
        TemplateField tfield = new TemplateField(); 
        tfield.HeaderTemplate = new TickColumn(m.ModuleName);   
        gvUsers.Columns.Add(tfield); 
       } 
     } 


     if (e.Row.RowType == DataControlRowType.DataRow) 
     { //Creation of checkboxes in the dynamic columns 
      List<Module> listModule = getModules(); 
      int i = 3; // cell postioning 
      foreach (Module m in listModule) 
      { 
       CheckBox cbActive = new CheckBox(); 
       cbActive.ID = m.ModuleID.ToString(); 
       e.Row.Cells[i].Controls.Add(cbActive); //Error<- because the cell does not have the column 
       i++; 
      } 
     } 
    } 

我是否在錯誤的事件中創建了列?

+1

不應該這樣在數據綁定事件? – Mairaj 2014-09-03 04:17:10

+0

它被放置在RowCreateEvent中的原因是因爲[This](http://stackoverflow.com/questions/14517812/how-to-find-a-dynamic-controlradio-button-inside-a-placeholder-in-gridview )。檢查蒂姆的答案 – 2014-09-03 06:05:55

回答

0
if (e.Row.RowType == DataControlRowType.Header) 
    { //creating column 
     List<Module> listModule = getModules(); 
      foreach (Module m in listModule) 
      { 
       TemplateField tfield = new TemplateField(); 
       tfield.HeaderTemplate = new TickColumn(m.ModuleName);   
       tfield.Controls.Add(cbActive); 
       CheckBox cbActive = new CheckBox(); 
       cbActive.ID = m.ModuleID.ToString(); 
       gvUsers.Columns.Add(tfield); 
      } 
    } 

}

嘗試上面的代碼,我還沒有編譯的代碼,但得到的想法如何做到這一點,

+0

複選框的創建是爲數據行,而不是頭。創建代碼很好。我懷疑它的事件,由於某種原因,它刷新剛創建的列,使其在回發中再次爲空。 – 2014-09-03 07:03:04

+0

嘗試此鏈接http://www.codeproject.com/Questions/330441/How-to-get-value-of-the-dynamically-created-contro – Mudeyanse 2014-09-08 05:31:13