2013-03-29 77 views
2

內設置一個文本框的值在我的網頁我的負荷方法我想設置文本框在一個TemplateField的值。一個GridView模板字段

這裏是我當前的源代碼顯示我的模板字段文本框項「txtQuan」:

<asp:TemplateField> 
       <ItemTemplate> 
       <asp:Label ID="lblTotalRate" Text="Qty:" runat="server" /> 
       <asp:TextBox ID="txtQuan" Height="15" Width="30" runat="server" /> 

       <asp:Button ID="addButton" CommandName="cmdUpdate" Text="Update Qty" OnClick="addItemsToCart_Click" runat="server" /> 
      </ItemTemplate> 
      </asp:TemplateField> 

這是IM如何試圖設置文本框的值:

string cartQty = Qty.ToString(); 

((TextBox)(FindControl("txtQuan"))).Text = cartQty; 

即時通訊目前接收'nullRefernceException錯誤'。

+0

在此情況下你要爲這個值?你需要找到其中的文本框所屬的行,然後調用'row.FindControl(...)' – codingbiz

+0

@codingbiz你的答案感謝。我想設置一個文本框爲我的GridView的每一行,因爲它會被用來允許用戶調整的item.I的控管數量,然後要填充基礎上,cartQty值的每個文本框。我已嘗試通過使用GridViewRow行= GridView1.SelectedRow設置行對象;但很顯然我沒有選擇一排。 – user1352057

回答

5

使用RowDataBound事件來做到這一點。你可以在互聯網上查看。該事件處理程序的參數可讓您輕鬆訪問每一行。您還可以遍歷行使用var rows = myGridView.Rows

var rows = myGridView.Rows; 
foreach(GridViewRow row in rows) 
{ 
    TextBox t = (TextBox) row.FindControl("txtQuan"); 
    t.Text = "Some Value"; 
} 

對於事件:GridView RowDataBound

protected void myGridView_RowDataBound(object sender, GridViewRowEventArgs e) 
    { 

    if(e.Row.RowType == DataControlRowType.DataRow) 
    { 
     TextBox t = (TextBox) e.Row.FindControl("txtQuan"); 
     t.Text = "Some Value";  
    } 
    } 
+0

非常感謝偉大的答案。 – user1352057

2
((TextBox)grdviewId.Row.FindControl("txtQuan")).Text=cartQty; 
相關問題