Build Your Own ASP.NET 3.5 Website Using C# & VB (76 page)

Read Build Your Own ASP.NET 3.5 Website Using C# & VB Online

Authors: Cristian Darie,Zak Ruvalcaba,Wyatt Barnett

Tags: #C♯ (Computer program language), #Active server pages, #Programming Languages, #C#, #Web Page Design, #Computers, #Web site development, #internet programming, #General, #C? (Computer program language), #Internet, #Visual BASIC, #Microsoft Visual BASIC, #Application Development, #Microsoft .NET Framework

BOOK: Build Your Own ASP.NET 3.5 Website Using C# & VB
6.33Mb size Format: txt, pdf, ePub

its templates, and see how you can use the EditItemTemplate to edit its contents.

Our goal here is to allow users to change the name or username of any employee

using this form.

Start by adding another button to the ItemTemplate of the DataList. This button

will read
Edit employee
Employee Name
and, when clicked, it will cause the item of which it’s a part to become editable. It goes at the end of the ItemTemplate element:

Visual Basic

Dorknozzle\VB\06_EmployeeDirectory.aspx
(excerpt)





Text=<%#"Edit employee " & Eval("Name")%>

Licensed to [email protected]

Displaying Content Using Data Lists

431

CommandName="EditItem"

CommandArgument=<%#Eval("EmployeeID")%> />


If you are using C#, don’t forget to replace the & with a + in the Text property value.

When an
Edit employee
button is clicked, we will make the item enter edit mode.

When one of the DataList items is in edit mode, the EditItemTemplate template

of the DataList is used to generate the contents of that item. All the other items are

generated by the ItemTemplate, as usual.

Modify
EmployeeDirectory.aspx
by adding the EditItemTemplate to the DataList.

The EditItemTemplate contains TextBox controls into which the user can enter

the employee’s name and username, and two buttons:
Update Item
and
Cancel Editing
, whose names are self-explanatory:

Dorknozzle\VB\07_EmployeeDirectory.aspx
(excerpt)


Name:

Text=<%#Eval("Name")%> />

Username:

Text=<%#Eval("Username")%> />

Text="Update Item" CommandName="UpdateItem"

CommandArgument=<%#Eval("EmployeeID")%> />

or

Text="Cancel Editing" CommandName="CancelEditing"

CommandArgument=<%#Eval("EmployeeID")%> />


Finally, before you can see your new template, we need to handle the
Edit employee

button. Again, when that button is clicked, the DataList’s ItemCommand event is

fired. This time, the CommandName of the new button is EditItem, and when we

discover that this button was clicked, we’ll put the item into edit mode. To put a

DataList item into edit mode, we set its EditItemIndex to the index of the item,

then bind the DataList to its data source again to refresh its contents. Add this code

to the file:

Licensed to [email protected]

432

Build Your Own ASP.NET 3.5 Web Site Using C# & VB

Visual Basic

Dorknozzle\VB\08_EmployeeDirectory.aspx.vb
(excerpt)

Protected Sub employeesList_ItemCommand(ByVal source As Object,

➥ ByVal e As System.Web.UI.WebControls.DataListCommandEventArgs)

➥ Handles employeesList.ItemCommand

If e.CommandName = "MoreDetailsPlease" Then

Dim li As Literal

li = e.Item.FindControl("extraDetailsLiteral")

li.Text = "Employee ID: " & e.CommandArgument & _

"
"

ElseIf e.CommandName = "EditItem" Then

employeesList.EditItemIndex = e.Item.ItemIndex

BindList()

End If

End Sub

C#

Dorknozzle\CS\08_EmployeeDirectory.aspx.cs
(excerpt)

protected void employeesList_ItemCommand(object source,

DataListCommandEventArgs e)

{

if (e.CommandName == "MoreDetailsPlease")

{

Literal li;

li = (Literal)e.Item.FindControl("extraDetailsLiteral");

li.Text = "Employee ID: " + e.CommandArgument +

"
";

}

else if (e.CommandName == "EditItem")

{

employeesList.EditItemIndex = e.Item.ItemIndex;

BindList();

}

}

Licensed to [email protected]

Displaying Content Using Data Lists

433

Figure 10.5. Editing the DataList

Execute the project now, load the employee directory, and enter one of your items

into edit mode, as shown in Figure 10.5
.

We need to implement functionality for two more buttons:
Update Item
, and
Cancel

Editing
. We’ll take them one at a time, starting with
Cancel Editing
, which is easier to handle. Modify employeesList_ItemCommand like this:

Visual Basic

Dorknozzle\VB\09_EmployeeDirectory.aspx.vb
(excerpt)

Protected Sub employeesList_ItemCommand(ByVal source As Object,

➥ ByVal e As System.Web.UI.WebControls.DataListCommandEventArgs)

➥ Handles employeesList.ItemCommand

If e.CommandName = "MoreDetailsPlease" Then


ElseIf e.CommandName = "EditItem" Then


ElseIf e.CommandName = "CancelEditing" Then

employeesList.EditItemIndex = -1

BindList()

End If

End Sub

Licensed to [email protected]

434

Build Your Own ASP.NET 3.5 Web Site Using C# & VB

C#

Dorknozzle\CS\09_EmployeeDirectory.aspx.cs
(excerpt)

protected void employeesList_ItemCommand(object source,

DataListCommandEventArgs e)

{

if (e.CommandName == "MoreDetailsPlease")

{


}

else if (e.CommandName == "EditItem")

{


}

else if (e.CommandName == "CancelEditing")

{

employeesList.EditItemIndex = -1;

BindList();

}

}

Execute your project again and check that your new button works. As you can see,

exiting edit mode is really simple. You merely need to set the EditItemIndex

property of the DataList to -1, then refresh the DataList’s contents.

Let’s deal with the task of updating the record now. We read the ID of the employee

whose details are being edited from the button’s CommandArgument property, and

we read that person’s new name and username from the TextBox control:

Visual Basic

Dorknozzle\VB\10_EmployeeDirectory.aspx.vb
(excerpt)

Protected Sub employeesList_ItemCommand(ByVal source As Object,

➥ ByVal e As System.Web.UI.WebControls.DataListCommandEventArgs)

➥ Handles employeesList.ItemCommand

If e.CommandName = "MoreDetailsPlease" Then


ElseIf e.CommandName = "EditItem" Then


ElseIf e.CommandName = "CancelEditing" Then


ElseIf e.CommandName = "UpdateItem" Then

Dim employeeId As Integer = e.CommandArgument

Dim nameTextBox As TextBox = _

e.Item.FindControl("nameTextBox")

Licensed to [email protected]

Displaying Content Using Data Lists

435

Dim newName As String = nameTextBox.Text

Dim usernameTextBox As TextBox = _

e.Item.FindControl("usernameTextBox")

Dim newUsername As String = usernameTextBox.Text

UpdateItem(employeeId, newName, newUsername)

employeesList.EditItemIndex = -1

BindList()

End If

End Sub

C#

Dorknozzle\CS\10_EmployeeDirectory.aspx.cs
(excerpt)

protected void employeesList_ItemCommand(object source,

DataListCommandEventArgs e)

{

if (e.CommandName == "MoreDetailsPlease")

{


}

else if (e.CommandName == "EditItem")

{


}

else if (e.CommandName == "CancelEditing")

{


}

else if (e.CommandName == "UpdateItem")

{

int employeeId = Convert.ToInt32(e.CommandArgument);

TextBox nameTextBox =

(TextBox)e.Item.FindControl("nameTextBox");

string newName = nameTextBox.Text;

TextBox usernameTextBox =

(TextBox)e.Item.FindControl("usernameTextBox");

string newUsername = usernameTextBox.Text;

UpdateItem(employeeId, newName, newUsername);

employeesList.EditItemIndex = -1;

BindList();

}

}

Licensed to [email protected]

436

Build Your Own ASP.NET 3.5 Web Site Using C# & VB

The techniques used in the above code are ones we have used earlier, but be sure

to read the code carefully to ensure that you understand how it works. If you are

using C#, you may have noticed that once again we need an explicit case for the

TextBox objects, whereas VB automatically converts the control to the proper type.

This is also true of the employeeId variable; in VB this is automatically converted

to an integer, but in C# we have to perform the conversion explicitly using the

Convert.ToInt32 method.

As you can see, we make a call to a mysterious method named UpdateItem. This

method is used to perform the actual update. We’ve created it as a separate method

to make the code easier to manage. Add this code to your code-behind file:

Visual Basic

Dorknozzle\VB\11_EmployeeDirectory.aspx.vb
(excerpt)

Protected Sub UpdateItem(ByVal employeeId As Integer,

➥ ByVal newName As String, ByVal newUsername As String)

Dim conn As SqlConnection

Dim comm As SqlCommand

Dim connectionString As String = _

ConfigurationManager.ConnectionStrings( _

"Dorknozzle").ConnectionString

conn = New SqlConnection(connectionString)

comm = New SqlCommand("UpdateEmployee", conn)

comm.CommandType = System.Data.CommandType.StoredProcedure

comm.Parameters.Add("@EmployeeID", Data.SqlDbType.Int)

comm.Parameters("@EmployeeID").Value = employeeId

comm.Parameters.Add("@NewName", Data.SqlDbType.NVarChar, 50)

comm.Parameters("@NewName").Value = newName

comm.Parameters.Add("@NewUsername", Data.SqlDbType.NVarChar, 50)

comm.Parameters("@NewUsername").Value = newUsername

Try

conn.Open()

comm.ExecuteNonQuery()

Finally

conn.Close()

End Try

End Sub

Licensed to [email protected]

Displaying Content Using Data Lists

437

C#

Dorknozzle\CS\11_EmployeeDirectory.aspx.cs
(excerpt)

protected void UpdateItem(int employeeId, string newName,

string newUsername)

{

SqlConnection conn;

SqlCommand comm;

string connectionString =

ConfigurationManager.ConnectionStrings[

"Dorknozzle"].ConnectionString;

conn = new SqlConnection(connectionString);

comm = new SqlCommand("UpdateEmployee", conn);

comm.CommandType = System.Data.CommandType.StoredProcedure;

comm.Parameters.Add("@EmployeeID", SqlDbType.Int);

comm.Parameters["@EmployeeID"].Value = employeeId;

comm.Parameters.Add("@NewName", SqlDbType.NVarChar, 50);

comm.Parameters["@NewName"].Value = newName;

comm.Parameters.Add("@NewUsername", SqlDbType.NVarChar, 50);

comm.Parameters["@NewUsername"].Value = newUsername;

try

{

conn.Open();

comm.ExecuteNonQuery();

}

finally

{

conn.Close();

}

}

Once the parameters are all prepared, the UpdateItem method calls the UpdateEmployee stored procedure, which performs the database operation. Next, let’s add the UpdateEmployee stored procedure to our database by executing

the following script using SQL Server Management Studio:

Dorknozzle\VB\12_UpdateEmployee.sql
(excerpt)

CREATE PROCEDURE UpdateEmployee

(

@EmployeeID Int,

@NewName nvarchar(50),

@NewUsername nvarchar(50)

)

Licensed to [email protected]

Other books

If I Say Yes by Jellum, Brandy
Fever Season by Barbara Hambly
The Memory of Blood by Christopher Fowler
Mystery of the Glowing Eye by Carolyn G. Keene
Wild Desert Princess by Deering, Debbie
Return of the Bad Boy by Paige North
A Girl Named Mister by Nikki Grimes
The Good Lord Bird by James McBride
The One That Got Away by Kerrianne Coombes