2011-06-27 71 views
0

我有一個代碼:e.Row.Cell增加控制不起作用

protected void gvContacts_RowDatabound(object sender, GridViewRowEventArgs e) 
    {  

    Label label = new Label(); 
    label.Text = "test";   

    if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowIndex == 0) 
    { 
     for (int i = 0; i < e.Row.Cells.Count; i++) 
     { 
      e.Row.Cells[i].Controls.Add(label); //doesnt work 
      e.Row.Cells[i].Text = "this works"; 

     } 
    } 
} 

其中標籤不顯示我的細胞。怎麼了?

+0

你在哪裏試圖調用這段代碼?具體來說,它是在RowDataBind中調用的嗎? –

+0

你在哪寫這段代碼?你無法在任何地方添加控件。 [ASP.NET頁面生命週期](http://msdn.microsoft.com/en-us/library/ms178472.aspx)可能非常複雜。 –

+0

更新我的代碼 –

回答

1

您需要在每個循環中創建一個新的標籤實例

for (int i = 0; i < e.Row.Cells.Count; i++) 
{ 
    label = new Label(); 
    label.Text = "test"; 
    e.Row.Cells[i].Controls.Add(label); 
    e.Row.Cells[i].Text = "this works"; 
} 
+0

我想通了。任何解釋爲什麼有一個實例不起作用? –

+0

因爲您正在爲每個單元格添加相同的控件。當您將其添加到另一個單元格時,您將從最後一個單元格中刪除它,因爲只存在一個對象。 –

+0

請記住,這種類型的對象(控件)是ByReference,而不是ByValue:) –

0

首先第一件事情:

  • 確保RowType實際上DataControlRowType.DataRow
  • 是確保e.Row.RowIndex == 0

在代碼中設置一個斷點,這樣你就可以確保這些值的。

之後,它看起來像你的代碼應該工作。

+0

更新了我的代碼 –

0

假設你已經有了一個標題行:

if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowIndex == 0) 

你行0將DataControlRowType.HeaderRow

你想要= 0,我覺得

+0

不,那一行是正確的。我有一個標題,但索引0是一個波紋管,我需要。 –

+0

然後我參考Adrian的迴應 - 調試測試它並檢查值。請確保您的GridView正在觸發事件。 –

+0

他們做的,e.Row.Cells [i] .Text =「這個作品」;作品 –

0

嘗試之前添加的TableCell添加控件:

TableCell cell = new TableCell();  
e.Row.Cells.Add(cell); 
e.Row.Cells[i].Controls.Add(label); 
+0

沒有工作..... –