Published:
27 Dec 2007
|
Abstract
In this article, Das explains how the good old data manipulation operations (such as Add/Modify/Delete) can be done using the ListView Web Server control. Apart from these, you will also learn how to give a confirmation message before we delete a row from the ListView. And finally, during editing/modifying a row from the ListView, we will see how to set the proper index for a DropDownList inside the ListView Edit Row. All these operations have been explained clearly with a live demo. |
|
by Jesudas Chinnathampi (Das)
Feedback
|
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days):
76262/
69
|
|
|
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.
|
|
|
User Comments
Title:
realy helpfu;
Name:
pradeep
Date:
2012-11-12 7:13:51 AM
Comment:
this article realy help to edit a row in database
|
Title:
Dete function
Name:
Michael C
Date:
2012-10-11 3:07:17 PM
Comment:
The delete function is not working
|
Title:
saa
Name:
cxcc
Date:
2012-04-12 10:54:51 AM
Comment:
cxcxcx
|
Title:
gud article
Name:
Madhuri Sharma
Date:
2011-10-01 5:12:43 AM
Comment:
it is very help ful article to use ListView tool on .net project.
|
Title:
Programming
Name:
Gerri
Date:
2011-04-03 11:44:34 PM
Comment:
Can't populate listview.
|
Title:
Dont use lable for row.
Name:
Sachin
Date:
2010-10-30 7:36:26 PM
Comment:
".............s. 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. "
Ever Heard of DataKey??
|
Title:
ListView in window application
Name:
Harsh
Date:
2010-09-06 4:07:30 AM
Comment:
Article is good. Can i get same thing on Window application.
|
Title:
Demo doesn't work
Name:
Roger
Date:
2010-04-07 5:24:00 PM
Comment:
When I download and attempt to run the demo it doesn't work! Please try embedding an SDF file into your project rather than trying make users connect to a nonexistant database on their machine.
|
Title:
This was an answer to all my ListView questions!
Name:
Laxmi
Date:
2009-12-10 2:42:01 PM
Comment:
Its very nice article on listview
|
Title:
This was an answer to all my ListView questions!
Name:
Halvard (Norway)
Date:
2009-12-08 11:01:02 AM
Comment:
Greate help!!
|
Title:
How do I programmatically add the (conditional-not default) value to the new insert row
Name:
Thinnakone
Date:
2009-11-21 2:26:39 AM
Comment:
when click at the Insert, I want to be able to assign a value (from a conditional calculation) to the new row ?
|
Title:
Server Side DropDownList databinding
Name:
Rinoy
Date:
2009-08-02 5:36:36 AM
Comment:
Hello, thanks can you help me to make server side dropdownbox binding
|
Title:
Doesnt work demo and Downdoad File!!
Name:
Roberto
Date:
2009-07-06 9:38:05 PM
Comment:
Hello, I can not download the file and also it doesnt work the online demo. Thanks.
|
Title:
DropDownList OnSelectIndexChanged
Name:
Ajeesh
Date:
2009-01-13 2:19:18 AM
Comment:
Hi, Thanks, Nice Article. I would like to know how to handle the dropdownlist onselectindexchanged event if I have two dropdownlists in the template and their autopostback property is set to true.
|
Title:
Delete Confirmation Works Great
Name:
Lois
Date:
2008-09-22 3:22:26 PM
Comment:
I've been looking for delete confirmation for a ListView and everything I tried did not work until now. Your solution is simple, straight forward, and it works! Thanks, and keep up the good work.
|
Title:
Nice
Name:
kinng
Date:
2008-09-06 10:38:06 AM
Comment:
Thanks, Useful article.
|
Title:
YOU MUST TAKE THIS ARTICLE DOWN
Name:
HAN
Date:
2008-06-20 11:33:51 AM
Comment:
I spended quite a lot of hours and your codes are not working. I tried to make it work, but it just doesn't make sense and not working. I found it's better to put Updating, Inserting, and deleting on ItemCommand event. If you want to do all actions in code-behind, that's the best place you should embed the action codes. Your codes are too buggy and don't make sense in general. I hope anyone reading this as a beginner should avoid. Don't waste your time thinking you're doing something wrong. It's just the design of this codes are too nonsense
|
Title:
Re: Go back and try again
Name:
Das (Author)
Date:
2008-05-20 9:05:08 PM
Comment:
This is fixed.
Well, this is a design flaw. When we have zero rows, the link to add authors was disabled. This is due to fact that the link to add new authors was in the ItemTemplate. When we have zero rows, the rows inside item template will not get rendered. So, I added an EmptyDataTemplate. Inside the EmptyDataTemplate, I have included a link to add authors. By this way, when someone deletes all rows, the link inside the EmptyDataTemplate will get rendered.
|
Title:
Go back and try again
Name:
BugBuster
Date:
2008-05-20 1:19:20 PM
Comment:
Your code doesn't work, please correct it or remove from site. Tired of finding non-working examples.
|
Title:
Editnig ListView
Name:
ListView
Date:
2008-04-23 3:08:32 AM
Comment:
Unable to edit
|
Title:
Re: Live Demo is broken
Name:
Das
Date:
2008-02-19 6:13:48 PM
Comment:
It is a bug in my code. when the record count goes to zero, the link to "add new records" is not being displayed.
I need to fix this, so that the "Add new" link / button will always show up. so, when we have zero rows, we could add new row using the "Add New" functionality.
Will modify the code accordingly.
|
Title:
Live Demo is broken
Name:
Jason Schechter
Date:
2008-02-19 2:38:06 PM
Comment:
Nothing is coming up except the shell of the table with the column headings.
|
Title:
ListViewItemType
Name:
Wissam Bishouty
Date:
2008-02-19 6:33:06 AM
Comment:
Greetings, thank you for the useful article. in the DataBoundList method you say : if (ddl != null) but why you do not check if the listview in edit mode so if it is in edit mode so you get the reference to the dropdownlist??
Regards.
|
Title:
Re: Could not find stored procedure 'teacher.das_get_authors'.
Name:
Das
Date:
2008-02-17 6:39:19 PM
Comment:
The stored procedure got deleted somehow. Not sure how. But I just ran the create script again and the LIVE demo is working fine again.
Thanks for letting me know about the error
|
Title:
Broken Demo
Name:
me
Date:
2008-02-06 4:43:35 PM
Comment:
Nice.... Could not find stored procedure 'teacher.das_get_authors'.
|
|
|
|