2011-03-02 89 views
2

我想將對象綁定到表單視圖。通過formview綁定和更新對象

<asp:FormView ID="formview" runat="server" DefaultMode="Edit" OnItemUpdating="formview_ItemUpdating"> 
    <EditItemTemplate> 
     <ol> 
     <li> 
      <label class="leftCo">First</label> 
      <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("First")%>'></asp:TextBox> 
     </li> 
     <li> 
      <label class="leftCo">Second</label> 
      <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("Second")%>'></asp:TextBox> 
     </li> 
    </ol> 
    <asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True" CommandName="Update" Text="Update"></asp:LinkButton>   
    </EditItemTemplate> 
</asp:FormView> 

    var objects = new List<OB> { new OB { First = "1111", Second = "2222" } }; 
    formview.DataSource = objects; 
    formview.DataBind(); 

現在,是否有可能在更新時生成一個新對象,而無需使用findcontrol讀取每個文本框?

當我點擊更新按鈕時,我想用更新後的值創建OB對象,並且可以說將它傳遞給某個方法(在更新事件中)。

+0

能否請你對你的問題的更詳細? – Nirmal 2011-03-02 09:02:43

+0

看到我的更新,如果你想要的東西只是問。 – markizik 2011-03-02 09:08:16

回答

2

儘量綁定到ObjectDataSource,如:

<asp:FormView ID="formview" runat="server" DefaultMode="Edit" OnItemUpdating="formview_ItemUpdating" DataSourceID="dsrcOB"> 
    <EditItemTemplate> 
     <ol> 
      <li> 
      <label class="leftCo">First</label> 
      <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("First")%>'></asp:TextBox> 
      </li> 
      <li> 
      <label class="leftCo">Second</label> 
      <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("Second")%>'></asp:TextBox> 
      </li> 
     </ol> 
     <asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True" CommandName="Update" Text="Update"></asp:LinkButton>   
    </EditItemTemplate> 
</asp:FormView> 

<asp:ObjectDataSource ID="dsrcOB" runat="server" 
    SelectMethod="GetOB" UpdateMethod="UpdateOB" 
    DataObjectTypeName="TestWeb.OB" TypeName="TestWeb.OBDal"> 
</asp:ObjectDataSource> 

然後,創建一個由引用類型匹配類的ObjectDataSource

public class OBDal 
{ 
    public OB GetOB() 
    { 
     return new OB() { First = "1111", Second = "2222" }; 
    } 

    public void UpdateOB(OB ob) 
    { 
     // do something here 
    } 
} 
+0

+1。我花了數小時試圖找出如何使用來自代碼背後的綁定數據源從FormView進行更新。每次我點擊更新時,綁定的項目都會丟失!這工作魅力(只有5年後!) – iandavidson1982 2017-07-17 09:21:41