【问题标题】:Inserting into ObjectDataSource with an object使用对象插入 ObjectDataSource
【发布时间】:2013-02-01 05:46:52
【问题描述】:

我正在尝试学习 ASP.NET,并希望使用 ObjectDataSource 来选择并插入数据库。我正在使用一个业务类,该类具有一个以对象作为参数的插入方法。我看过的几个消息来源说这是一种正确的方法,但我一直无法找出如何在文件后面的代码中使用 c# 插入数据库。我有一个表单,它使用正常工作的 ObjectDataSources 从其他两个表中提取,但我需要使用一个按钮将我正在创建的记录插入到表中。我似乎无法将我创建的对象添加到 ObjectDataSource 的 InsertParameters 中,所以我想知道是否有这样做的方法。

插入方法的签名如下所示:

public static void InsertIncident(Incident incident)

Visual Studio 生成的 ASP 代码如下所示:

<asp:ObjectDataSource ID="ObjectDataSource1" runat="server"
  DataObjectTypeName="Incident" InsertMethod="InsertIncident"
  OldValuesParameterFormatString="original_{0}"  SelectMethod="GetIncidents" 
  TypeName="IncidentDB"></asp:ObjectDataSource>

【问题讨论】:

标签: c# asp.net objectdatasource


【解决方案1】:

我现在觉得有点傻,但我发现我做错了什么。我根本不需要使用 ObjectDataSource 来插入对象。我应该直接调用 insert 方法。

if (IsValid)
{
  Incident i = new Incident();
  i.CustomerID = Convert.ToInt32(ddlCustomer.SelectedValue);
  i.ProductCode = ddlProduct.SelectedValue;
  i.DateOpened = DateTime.Today;
  i.Title = txtTitle.Text;
  i.Description = txtDescription.Text;

  try
  {
    IncidentDB.InsertIncident(i);
  }
  catch (Exception ex)
  {
  }
}

【讨论】:

  • 谢谢 - 我遇到了同样的问题,这帮助我找到了答案!
【解决方案2】:

尝试将您的 ObjectDataSource 更改为如下内容:

<asp:ObjectDataSource ID="ObjectDataSource1" runat="server" DataObjectTypeName="Incident" InsertMethod="InsertIncident" SelectMethod="GetIncidents" TypeName="IncidentDB"></asp:ObjectDataSource>

然后,尝试添加 DetailsView 以在数据库中插入记录:

<asp:DetailsView ID="insertData_DetailsView" runat="server" Height="50px" Width="400px" AutoGenerateRows="False" DataSourceID="ObjectDataSource1" DefaultMode="Insert" GridLines="None">

只需确保您的 DV 中有正确的 DataSourceID。

对我来说很好用。

谢谢。

【讨论】:

  • 问题是我不想使用详细视图,而是使用一组不能很好地工作的控件。因此,我想使用一个按钮。原因是我希望表格中的一项不显示在表单中,而是自动设置(当前日期),另外两项留空。 DetailsView 并不真正适用于这项任务。
  • 嗨 Steven,你检查过这个 [Configure ObjectDataSource from Code Behind] (stackoverflow.com/questions/3900398/…) 吗?
猜你喜欢
  • 1970-01-01
  • 2011-12-15
  • 1970-01-01
  • 1970-01-01
  • 2010-11-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多