通过formview绑定和更新对象

时间:2011-03-02 08:52:15

标签: asp.net

我想将对象绑定到表单视图。

<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对象,并且让我们说,将它传递给某个方法(在更新事件中)。

1 个答案:

答案 0 :(得分: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
    }
}