2016-07-05 5 views
0

私は4つのテンプレートフィールド、それぞれがテキストボックスを含むグリッドビューを持っています。 これらのテンプレートフィールドをデータソースにバインドしました。私は、テキストボックス内のいくつかのデータを入力して保存ボタン(グリッドビューの一部ではなく、Webフォームの個々のボタン)をクリックすると、クリックイベントハンドラで値を取得できませんコードビハインドファイル私を助けてください。Asp.netグリッドビューのテンプレートフィールドのデータを保持

のaspxファイルファイルの背後にある

<asp:TemplateField HeaderText="col1"> 
 
    <ControlStyle Height="25px" Width="60px" /> 
 
     <ItemTemplate> 
 
      <asp:TextBox ID="txt1" runat="server" Text='<%# Bind("[col1]") %>'> 
 
      </asp:TextBox>     
 
     </ItemTemplate> 
 
    </asp:TemplateField> 
 
    
 
<asp:TemplateField HeaderText="col2"> 
 
    <ControlStyle Height="25px" Width="60px" /> 
 
    <ItemTemplate> 
 
     <asp:TextBox ID="txt2" runat="server" Text='<%# Bind("[col2]") %>'> 
 
     </asp:TextBox> 
 
    </ItemTemplate> 
 
</asp:TemplateField> 
 
    
 
<asp:TemplateField HeaderText="col3"> 
 
    <ControlStyle Height="25px" Width="60px" /> 
 
    <ItemTemplate> 
 
     <asp:TextBox ID="txt3" runat="server" Text='<%# Bind("[col3]") %>'> 
 
     </asp:TextBox> 
 
    </ItemTemplate> 
 
</asp:TemplateField> 
 
    
 
<asp:TemplateField HeaderText="col4"> 
 
    <ControlStyle Height="25px" Width="60px" /> 
 
    <ItemTemplate> 
 
     <asp:TextBox ID="txt4" runat="server" Text='<%# Bind("[col4]") %>'> 
 
     </asp:TextBox> 
 
    </ItemTemplate>  
 
</asp:TemplateField>

コードを

protected void ButtonAdd_Click(object sender, EventArgs e) 
{ 

    foreach (GridViewRow row in gvEdit.Rows) 
    { 



      string a = ((TextBox)row.FindControl("col1")).Text; 
       //above line gives a null value 


    } 
} 
+2

あなたのHTMLも追加する必要があります。 – techspider

答えて

0

あなたはGridViewRowCollectionをループする必要があり、その後、行ごとに、Idあなたによる制御を見つけますマークアップでそれを与えた。たとえば、次のように

protected void ButtonAdd_Click(object sender, EventArgs e) 
{ 
    foreach (GridViewRow row in gvEdit.Rows) 
    { 
     var txt1 = row.FindControl("txt1") as TextBox; 
     var txt2 = row.FindControl("txt2") as TextBox; 
     var txt3 = row.FindControl("txt3") as TextBox; 
     var txt4 = row.FindControl("txt4") as TextBox; 

     // access the Text property of each, e.g. txt1.Text 
    } 
} 

更新:あなたはデータバインディングのソースを行う際に、それが唯一の初期ロードとその後のではないのポストバックで発生することを確認してください、そうでない場合は、あなたの変更は毎回リセットされます。

protected void Page_Load(object sender, EventArgs e) 
{ 
    if (!IsPostBack) 
    { 
     GridView1.DataSource = // data source 
     GridView1.DataBind(); 
    } 
} 
+0

Nop。それは動作しません。私はデータソースから値を提供する場合、同じ値が返されますが、私は(ユーザーとして)テキストボックス内のdatを変更すると、データソース内のデータを返します – user3107338

+0

@ user3107338私はデータバインディングのロジックを見ていないが、それが最初の負荷でのみ発生することを確認してください。更新された回答をご覧ください。 –

+0

うわー。そのポストバック条件を忘れた。提案していただきありがとうございます。 – user3107338

関連する問題