AspAlliance.com LogoASPAlliance: Articles, reviews, and samples for .NET Developers
URL:
http://aspalliance.com/articleViewer.aspx?aId=1542&pId=-1
Data Manipulation using ListView Server Control with ASP.NET 3.5
page
by Jesudas Chinnathampi (Das)
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 129321/ 217

Introduction

In order to use the ListView control, we need the ASP.NET 3.5 Framework. All examples mentioned in this article were created using Visual Web Developer 2008 Express Edition. You could use SQL Server 2000/2005 or the free SQL Express to try out the examples explained in this article. C# is the primary language that is being used in this article. If you are comfortable with VB, then you could use a free tool which will convert the C# code to VB.NET. This can be found by visiting the following link.

Topics covered in this article

·         How to populate a ListView Web Server Control.

·         How to add rows to a ListView Web Server Control.

·         How to Modify / Edit rows in a ListView Web Server Control.

·         Editing a DropDownList control inside of a ListView.

·         How to delete a row from a ListView Web Server Control by showing a Delete warning message.

How to Populate a ListView Web Server Control

The following is the basic syntax to declare a ListView Web Server Control in an ASPX page.

Listing 1: ListView definition

<asp:ListView ID="ListView1" runat="server">
<LayoutTemplate>
<asp:PlaceHolder ID="itemPlaceholder" runat="server"></asp:PlaceHolder>
</LayoutTemplate> 
</asp:ListView>
<ItemTemplate>
<%#DataBinder.Eval(Container.DataItem, "ColumnName")%>
</ItemTemplate>

The layout template specifies the basic structure of a ListView control. A Placeholder control must be declared to use the ListView control. For example, if you want to display a report title then you could have a table row just above the Placeholder. And, if you want to display report footer, then you could have a table row just below the Placeholder. This has been explained later in this article, where we add rows to a ListView.

There are many ways we could bind the ListView object. In the following example, the ListView is being populated using a Stored Procedure. The DataItem "ColumnName" is one of the columns which are being returned by the Stored Procedure. During the Page_Load event, the Stored Procedure is executed and bind to the ListView.

Listing 2: Binding a ListView Web Server Control

protected void PopulateListView()
{
  SqlConnection myConn = CreateConnection();
  // CreateConnetion is a custom method which returns SQL connection.
  SqlCommand myCmd = new SqlCommand("pubs_get_authors", myConn);
  myCmd.CommandType = CommandType.StoredProcedure;
  try
  {
    myConn.Open();
    ListView1.DataSource = myCmd.ExecuteReader(CommandBehavior.CloseConnection);
  }
  catch (SqlException se)
  {
    lblMsg.Text = se.Message;
  }
  catch (Exception e)
  {
    lblMsg.Text = e.Message;
  }
  finally{}
  ListView1.DataBind();
  myConn.Close();
}

In the above code listing, the stored proc “pubs_get_authors” is invoked. Try … Catch … Finally has been used to trap any unexpected errors that might occur during the database operation. The definition of CreateConnection method is included in the code sample at the end of this article.

Figure 1: ListView control Output

How to add rows to a ListView Web Server Control

In order to allow users to add rows to the ListView, the following needs to be taken care of:

A Hyperlink or a Button needs to be created for the user to click on. Once the user clicks the link, we should add a blank row to the ListView.

In the insert mode, we should have a “Save” option and a “Cancel” option.

If the user clicks “Save” a new row should be added to the database table

If the user clicks “Cancel” the insert operation should be cancelled.

Let us see how the above can be achieved:

Providing a Hyperlink/Button to add a new row to the Listview

Listing 3

<LayoutTemplate>
<asp:PlaceHolder ID="itemPlaceholder" runat="server"></asp:PlaceHolder>
<tr>
      <td colspan="5" align="center">
      <asp:LinkButton Text="Click here to add an Author" ID="lnkNew"
          runat="server" Font-Bold="true" OnClick="NewAuthor"></asp:LinkButton>
      </td>
</tr>
</LayoutTemplate>

In the ListView control definition, you should define a method which will be invoked when the event ItemInserting occurs. For example:

Listing 4

OnItemInserting="InsertList" 

And the InsertList method definition will look like as follows:

Listing 5

protected void InsertList(Object sender, ListViewInsertEventArgs e)
{
    ListView1.InsertItemPosition = InsertItemPosition.None; 
}

ListView has an InsertItemTemplate Template in which we can specify the controls that we need to show during the insert mode. For example:

Listing 6

<InsertItemTemplate>
<tr>
      <td><asp:TextBox id="txtLName" runat="server"></asp:TextBox></td>
      <td>
      <asp:LinkButton ID="lnkSave" CommandName="Save" runat="server" 
      Text="Save"></asp:LinkButton>
 
      <asp:LinkButton ID="lnkCancel" CommandName="Cancel" runat="server" 
      Text="Cancel"></asp:LinkButton>
      </td>
</tr>                
</InsertItemTemplate>

I the above code listing, we have one textbox and two links. The textbox is used to get the data from the user and will eventually be saved to the database. The action link, Save is used to save the data. We should write a custom function which will retrieve the textbox content and inserts the value to the database.  The command name for the Save link should be "Save". The action link, Cancel is used to cancel the insert operation. The command name for the Cancel link should be "Cancel". The code for the ItemCanceling event will look like as follows:

Listing 7

ListView1.InsertItemPosition = InsertItemPosition.None;
((LinkButton)ListView1.FindControl("lnkNew")).Visible = true;

In the above code, the first line removes the newly added row. The second line changes the visible property for "Click here to add an Author" hyperlink which is displayed in the ListView footer.

For saving data to the database, we should write custom code according to our business logic. The main purpose of the Save method should be to get the values for all controls. This can be achieved using the FindControl method. The following code snippet retrieves the value of a textbox control. Once the value is retrieved all we have to do is create a database connection and insert the data to the database.

Listing 8

TextBox txtLname = (TextBox)e.FindControl("txtLName");

Figure 2: ListView Insert mode

 

How to add Modify/Edit rows in a ListView Web Server Control

In order for the user to edit a row in the ListView, they should be able to change the corresponding row in the ListView to an editable one. This can be done by adding the following to the ItemTemplate template to the ListView control.

Listing 9

<asp:LinkButton ID="lnkEdit" CommandName="Edit" runat="server" Text="Edit" />

The command name should be set to “Edit”. That is the most important aspect for the edit.

The second step for editing a ListView is to put the ListView in the edit mode. When the user clicks on any of the Edit Link, the corresponding row in the ListView should be changed to an editable row. This can be achieved using the following code snippet:

Listing 10

ListView1.EditIndex = e.NewEditIndex;

e is an instance of ListViewEditEventArgs.

Once the ListView is in the edit mode, we have two possibilities. The first being: Saving the edited data back to the database and the second is to cancel the edit operation. Canceling the edit operation can be done using the following code snippet:

Listing 11

ListView1.EditIndex = -1;

When the user clicks the Update link after editing the needed data, the event ItemUpdating will be fired. We could invoke a method for this event and within the method the modified data can be retrieved and update the database using a stored procedure or an inline SQL statement. Just like the insert operation, we could use the FindControl method to retrieve the modified values. Another key aspect for any edit operation is that we should know which row in the database should be updated. For this purpose, we could store the primary key for each row in the ListView inside a hidden label control or even a hidden server control.

Editing a DropDownList control within the edit mode of ListView

Editing a textbox control is very simple. But if you have a dropdown listbox, then pre-setting the old value for the dropdown might need some extra coding. There could be many ways you can pre-set the old value for the DropDownList control within the edit mode. One of the ways is as follows:

When the user clicks the Edit link for any row, get the value for the DropDownList control and store it in a global variable.

The event, ItemEditing will be fired when the edit link is clicked. In the ItemTemplate template for the ListView, the value for the DropDownList control is displayed as a label.

All we have to do is get the value of the label server control.

Using this label, we could change the index for the DropDownList control. The following code retrieves the old value for the DropDownList control (which is stored in a Label control)

Listing 12

ListView1.EditIndex = e.NewEditIndex;
// Get the Value for State
Label lblTemp = (Label)ListView1.Items[e.NewEditIndex].FindControl("lblState");
strCurrentState = lblTemp.Text;

Now using the string, strCurrentState we could change the index of the DropDownList control within the ItemDataBound event. The following method will be invoked during an ItemDataBound event occurs.

Listing 13

protected void DataBoundList(Object sender, ListViewItemEventArgs e)
{
  if (e.Item.ItemType == ListViewItemType.DataItem)
  {
    // Get a handle to the ddlState DropDownList control
    DropDownList ddl = (DropDownList)e.Item.FindControl("ddlState");
     // Make sure we have the handle !
    if (ddl != null)
    {
      ddl.SelectedIndex = ddl.Items.IndexOf(ddl.Items.FindByText
        (strCurrentState));
    }
  }
}

Figure 3: ListView Edit Mode

How to delete a row from a ListView Web Server Control

The first step to allow users to delete a row from the ListView is to provide them with a Delete Link / Delete button for every row in the ListView. This can be done by adding the following to the ItemTemplate collections for the ListView

Listing 14

<asp:LinkButton ID="lnkDelete" CommandName="Delete" runat="server" Text="Delete" />

The command name should be set to “Delete”. That is the key here. Now, we have something for the user to click so that the user can delete the row. When the Delete link is clicked, the ItemDeleting event will be fired. We could invoke a method for this event. Within the method we could get the value for the primary key and invoke a stored procedure or use an inline SQL Delete statement.

Display a warning message when the user clicks Delete in a ListView Control?

It will be always helpful to ask user before they actually delete the row from the ListView and eventually from the database. We could display a warning message whether they really intend to delete the row. If the reply is either yes or OK, then we could carry out with the actual removal of the rows from the database.

This can be done using the following technique:

During the ItemDataBound event, we can attach a client side event for each Delete Link in the ListView control.

Listing 15

protected void DataBoundList(Object sender, ListViewItemEventArgs e)
{
  if (e.Item.ItemType == ListViewItemType.DataItem)
  {
    LinkButton lnkDelete = (LinkButton)e.Item.FindControl("lnkDelete");
    if (lnkDelete != null)
    {
      lnkDelete.Attributes.Add("onclick",
        "return confirm('Are you sure you want to delete this author?');");
    }
  }
}

Clicking on the delete link will result in the following alert box. If the user clicks cancel, then the delete operation will not be carried out.

Figure 4: ListView Delete Confirmation message

Through out this article, we saw many methods which were invoked for many events. The following EventHandlers will be helpful. Basically these event handlers raise the corresponding events. It is through these methods we were able to customize the ListView output.

Listing 16

<asp:ListView ID="ListView1" runat="server"
OnItemCommand="CommandList" 
OnItemDataBound="DataBoundList"
OnItemEditing="EditList"
OnItemUpdating="UpdateList"
OnItemCanceling="CancelList"
OnItemDeleting="DeleteList"
OnItemInserting="InsertList">
Demo
Downloads

[Download Sample]

In order to try the sample code in your machine you will need to run Five SQL scripts. One of the scripts creates a table named, authors_backup. The table structure is very similar to the table "authors" which can be found in the pubs database of SQL Server. Remaining Four SQL scripts are stored procedures which are used to insert, modify, delete and retrieve rows from the table, authors_backup.

References
Summary

The ListView Server control combines the power of DataList and Repeater control. However, unlike those controls, with the ListView control you can enable users to edit, insert, delete data, paging and even sort the data. Using the <asp:DataPager> Web Server Control we could bring the paging functionality the ListView control. The main advantage of the ListView control is that we can display data according to our design using templates and styles.

As I mentioned earlier, there are many ways to code to achieve the data manipulation that we just saw. We could use a SQLDatasource control within the ASPX page and bind the ListView with no additional coding. Using the Visual Studio 2008 designer, we can easily configure the SQLDataSource so that it will automatically generate the SELECT, INSERT, UPDATE and DELETE statement. But in most cases we will have to write stored procedures to perform the above operations. I hope that this article will help you out to work with the ListView control with ease.



©Copyright 1998-2019 ASPAlliance.com  |  Page Processed at 2019-07-16 2:34:12 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search