2013-01-10 185 views
1

我在頁面aspx中有gridview控件和textbox +按鈕控件。將文本框值傳遞給gridview

我想通過單擊按鈕將文本框的值傳遞給gridview。

<asp:GridView ID="gvName" runat="server" ViewStateMode="Enabled"> 
<Columns> 
<asp:TemplateField> 
<ItemTemplate> 
<asp:Label ID="lblName" runat="server"></asp:Label> 
</ItemTemplate> 
</asp:TemplateField> 
</Columns> 
</asp:GridView> 

,並使用此代碼:

protected void btnAddName_Click(object sender, ImageClickEventArgs e) 
    { 
     foreach (GridViewRow row in gvName.Rows) 
     { 
      if ((Label)row.FindControl("lblName") is Label) 
      { 
       ((Label)row.FindControl("lblName")).Text = txtName.Text; 
      } 
     } 
    } 

但它沒有確定。 :-(請幫我

+0

你是什麼目的呢? –

+0

什麼是你所面臨的問題你可以解釋一下嗎? – MahaSwetha

+0

只是你想分配的texbox值在gridview標籤?你需要什麼? – Nag

回答

1

如果網格行已與id lblName標籤,那麼你將排得到它,你不必再檢查一遍

foreach (GridViewRow row in gvName.Rows) 
{ 
    Label lblName = (Label)row.FindControl("lblName");   
    lblName.Text = txtName.Text;    
} 

注意:如果你這樣做沒有行已經在THR GridView控件,那麼你將無法,您需要確保在電網其ARE行(S)獲得標籤的值。

+0

我在點擊按鈕事件中使用此代碼,但不起作用。不向gridview插入值。 –

+0

你綁定了你的網格視圖嗎?網格中有多少行? – Adil

+0

我插入文本框中的值,然後單擊但不插入值textboxt到gridview –

3
Create a rowdatabound command and place the below code. 

protected void gvName_RowDataBound(object sender, GridViewRowEventArgs e) 
{ 
     if (e.Row.RowType == DataControlRowType.DataRow) 
     { 
      Label lblName = (Label)row.FindControl("lblName");   
      lblName.Text = txtName.Text; 
     } 
} 
+0

我使用這個代碼但是沒有在gridview中插入值(gridview爲空) –

+0

首先,綁定gridview和數據源並嘗試這個。 – MahaSwetha

相關問題