I am attempting to learn ASP.NET and want to use an ObjectDataSource to select and insert into a database. I am using a business class that has an insert method that has an object as its parameter. Several sources I've looked at say that this is a correct way of doing this but I have been unable to find out how to insert into the database using c# in the code behind file. I have a form that pulls from two other tables using ObjectDataSources that work correctly but I need to use a button to insert the record that I am creating into the table. I do not seem to be able to add the object I have created into the InsertParameters of the ObjectDataSource so I want to know if there is a method of doing this.
The insert method's signature looks like this:
public static void InsertIncident(Incident incident)
The ASP code that Visual Studio generated looks like this:
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server"
DataObjectTypeName="Incident" InsertMethod="InsertIncident"
OldValuesParameterFormatString="original_{0}" SelectMethod="GetIncidents"
TypeName="IncidentDB"></asp:ObjectDataSource>
I feel a little bit silly now, but I found out what I was doing wrong. I didn't need to use the ObjectDataSource for inserting the object at all. I should have just called the insert method directly.
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)
{
}
}