Tutorial RSS
 
Navigator: Home - Advanced - Updating Custom Object in SQL Database with C#

Updating Custom Object in SQL Database with C#

This tutorial follows on from the Inserting Custom Object and will show you how to build on that class to add the functionality of Updating Objects in C#

Following on from the Updating Custom Object tutorial, we will look into how we can add the Update functionality, allowing us to edit an object and then commit changes to the database. By using objects, we could first make the changes and then decide whether or not to save these changes to the database.
However, in this example, we will use the class of the previous tutorial to add a method to update the object. If you have not followed that tutorial yet, it is recommended. You can find it here.

Once you have the project opened up, open up the Car.cs from App_Code. There are two things we are going to add: A constructor that takes an int parameter; and an UpdateMethod that takes a Car object parameter.

Let's go ahead and add the constructor first. This will be different from the constructor we already have; it will be more like a method, without returning anything. The constructor will look something like this:

/// <summary>
/// Contructor for Car object, set the Car object from ID passed to it.
/// </summary>
/// <param name="theCarID">Int32 value of the ID of the Car to get.</param>
public Car(int theCarID)
{
SqlConnection connection = new SqlConnection(WebConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
try
{
SqlCommand cmd;
cmd = new SqlCommand("sp_GetCarByID", connection);
cmd.CommandType = CommandType.StoredProcedure;

cmd.Parameters.AddWithValue("@CarID", theCarID);

connection.Open();
SqlDataReader objReader = cmd.ExecuteReader();

while (objReader.Read())
{
SetObjectData(objReader);
}

objReader.Close();
connection.Close();
}
catch
{
connection.Close();
}
}


Notice here we are referencing a new Stored Procedure, one that will retrieve the record from the database that matches the ID parameter we pass to it. The Stored Procedure will look something like this:

CREATE PROCEDURE dbo.sp_GetCarByID

@CarID int

AS

SELECT * FROM Cars WHERE ID = @CarID


Need help with Windows Dedicated Hosting? Try Server Intellect. I'm a happy customer!

We also need another Stored Procedure - one to Update the Car object we pass. It should look something like this:

CREATE PROCEDURE dbo.sp_UpdateCar

@ID int,
@Make varchar(50),
@Model varchar(50)

AS

UPDATE Cars
SET Make = @Make, Model = @Model
WHERE ID = @ID


Now we have our Stored Procedures, we can finish up with the class by adding the Update method:

/// <summary>
/// Updates a Car in the database.
/// </summary>
/// <returns>Returns Boolean value indicating if the method finished without errors.</returns>
public static bool UpdateCar(Car theCar)
{
SqlConnection connection = new SqlConnection(WebConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
try
{
SqlCommand cmd = new SqlCommand("sp_UpdateCar", connection);
cmd.CommandType = CommandType.StoredProcedure;

cmd.Parameters.AddWithValue("@ID", theCar.ID);
cmd.Parameters.AddWithValue("@Make", theCar.Make);
cmd.Parameters.AddWithValue("@Model", theCar.Model);

connection.Open();
cmd.ExecuteNonQuery();
connection.Close();
return true;
}
catch
{
connection.Close();
return false;
}
}


Server Intellect offers Windows Hosting Dedicated Servers at affordable prices. I'm very pleased!

Notice we are passing in a Car object, and then using its Properties to pass to the Stored Procedure. We return true if the Update was successful.
We are now done with modifying the class. We can move back to our ASPX page and make changes to the Repeater. What we are going to do is to display all the records in a Repeater, and provide a LinkButton for record to be edited. We will also provide two textboxes to edit the Make and Model, and then a button to commit the changes. The Repeater will look something like this:

<asp:Repeater ID="repeater_Cars" runat="server" OnItemCommand="repeater_Cars_ItemCommand">
<HeaderTemplate>
<table width="350"><tr>
<td><strong>ID</strong></td>
<td><strong>Make</strong></td>
<td><strong>Model</strong></td>
<td><strong>Action</strong></td>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><%# Eval("ID") %></td>
<td><%# Eval("Make") %></td>
<td><%# Eval("Model") %></td>
<td><asp:LinkButton ID="lnk_Edit" runat="server" CommandArgument='<%# Eval("ID") %>'
CommandName="EditCar" Text="Edit" /></td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>


Notice we are using the ItemCommand event of the Repeater to handle the edits. By doing this, we are able to set a CommandName and CommandArgument for each LinkButton that is rendered, for each object in the collection. We will use the ID for the CommandArgument, because the ID is the unique identifier. Notice also, that we have a handler for the Repeater's ItemCommand, which we will show you shortly. But first, let's finis the form and add our textboxes and button:

ID: <asp:Literal ID="lit_ID" runat="server" /><br />
Make: <asp:TextBox ID="fld_Make" runat="server" /><br />
Model: <asp:TextBox ID="fld_Model" runat="server" /><br />
<asp:Button ID="btn_Update" runat="server" Text="Update" OnClick="btn_Update_OnClick" Enabled="false" />


We also include a Literal control to display the ID, as this is not editable. We disable the button on load, and will enable when an edit is clicked.
Moving to the code-behind, we will first need to make sure we are referencing our custom class:

using DBTutorials.Car;


Next, we bind the Repeater on Page_Load:

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindRepeater();
}
}

protected void BindRepeater()
{
repeater_Cars.DataSource = Car.GetAllCars();
repeater_Cars.DataBind();
}


I just signed up at Server Intellect and couldn't be more pleased with my Windows Server! Check it out and see for yourself.

Next, we create the OnItemCommand handler. This can be added manually, or by clicking on the Repeater in Design view, going to Properties and double-click on the ItemCommand Event field.
This first checks to see if the correct command is being called, and then it converts the CommandArgument to the ID of the Car object, which it then retrieves from the database using our new constructor, and then fills in the literal and textboxes as well as enabling the button.

Finally, we add the handler for the button click event:

protected void btn_Update_OnClick(object sender, EventArgs e)
{
if (!String.IsNullOrEmpty(fld_Make.Text) && !String.IsNullOrEmpty(fld_Model.Text))
{
Car carToEdit = new Car(Convert.ToInt16(lit_ID.Text));
carToEdit.Make = fld_Make.Text;
carToEdit.Model = fld_Model.Text;

if (Car.UpdateCar(carToEdit))
{
lit_ID.Text += " [Updated]";
fld_Make.Text = "";
fld_Model.Text = "";

BindRepeater();
btn_Update.Enabled = false;
}
}
}


Now if this application is run, you will see that all Cars are displayed from the collection straight away. We are then able to click on the Edit link of each object, and edit them right on the page. We can even improve the functionality of this by including a ScriptManager and UpdatePanel. The editing will then seem instantaneous.
Download Project Source - Enter your Email to be emailed a link to download the Full Source Project used in this Tutorial!



100% SPAM FREE! We will never sell or rent your email address!

411asp.net123aspxDotNetFreaksServer Intellect