2009-11-05 51 views
0

下面是我希望控件工作的方式。點擊gridview中的一行編輯。在其中一列中有一個文本框,我希望它是空白的,即使該列的數據庫中有數據,但是當我單擊更新時,我想要用戶輸入的任何新文本來更新該列的數據庫。這將是單向數據綁定,但反過來呢?ASP .Net Gridview僅在點擊更新時綁定到數據

回答

0

下面是我如何在生成的select,update和delete方法中使用sql數據源。

首先,你需要做的是要與一個項目模板,並編輯項目模板編輯這樣的一個模板場任意列:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
     DataKeyNames="ID" DataSourceID="SqlDataSource1" 
     onrowupdating="GridView1_RowUpdating"> 
    <Columns> 
    <asp:TemplateField HeaderText="City" SortExpression="City"> 
     <ItemTemplate> 
      <asp:Label runat="server" Text='<%# Eval("City") %>'></asp:Label> 
     </ItemTemplate> 
     <EditItemTemplate> 
      <asp:TextBox runat="server" ID="txtCityEdit" Text=""></asp:TextBox> 
     </EditItemTemplate> 
    </asp:TemplateField> 
    </Columns> 
</asp:GridView> 

下一頁處理GridView控件的更新事件的:

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) 
    { 
     //find the value control who's value you want 
     TextBox tb = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtCityEdit"); 

     //since we are not using a bound column for city we need to explicitly insert the value 
     //into the update parameter. 
     SqlDataSource1.UpdateParameters["City"].DefaultValue = tb.Text; 
    } 

即使您使用的不是SQL數據源,也應該是基本的解決方案。

+0

這並不適合我,但絕對讓我走上正軌!我最大的問題是將文本框的值從模板字段中取出,因爲intellisense不會給我。 我嘗試使用UpdateParameters喜歡你的例子,但得到一個空引用錯誤,然後我試圖添加我的新集合,並沒有工作。 我結束了我的新值添加到「NewValues」集合,它的工作。 – user204019

0
// Find notes textbox 
TextBox tb = (TextBox)MyActiveReferrals.Rows[e.RowIndex].FindControl("NotesTextBox"); 
e.NewValues.Add("Notes", tb.Text); 

我用了一個linq數據源。