CODEDIGEST
Home Articles CodeDigest Tutorials FAQs
Skip Navigation LinksHome » Article » ASP.Net Article » Edit,Update,Delete and Insert in ListView Control   You are not logged in.
Search
 

Technologies
 

Sponsors
 

CodeDigest Navigation
 

Technology News
 

Community News
No News Feeds available at this time.
 
Edit,Update,Delete and Insert in ListView Control

By Satheesh babu
Posted On Aug 03,,2008
Article Rating: (Login)
Average Rating: 5
No of Ratings: 1
No of Comments: 12
Print this article.
Category: ASP.Net 3.5

Subscribe to our feed!

Edit,Update,Delete and Insert in ListView Control

Introduction

We have explored the basics and adding paging feature to ListView control through my previous articles ListView Control in ASP.Net 3.5 and Paging in ListView in ASP.Net 3.5. Our next step in learning ListView Control is to add edit/update/delete/insert feature to the ListView control. Like my previous articles on ListView control, we will add this feature in 2 scenarios.

Ø       Edit/Update/Delete/Insert feature using DataSource controls.

Ø       Edit/Update/Delete/Insert feature without using DataSource controls.

In GridView, the Edit/Update/Delete feature is an inbuilt one and can be achieved without writing a line of code with the help of DataSource controls. Likewise, the ListView control also have inbuilt Edit/Update/Delete feature and additionally, insert feature is also introduced as an inbuilt one.

Edit/Update/Delete/Insert feature using DataSource controls

Configuring SqlDataSource Control

Drag a SqlDataSource control from the data tab of Visual Studio 2008. Configure it with the Database Server; I have used a database in App_Data folder. To configure the DataSource control to handle insert, update and delete click “Advanced...” button. Refer the below snapshot.

Edit/Update/Delete/Insert in ListView in ASP.Net 3.5

Check the “Generate Insert, Update and Delete statements as shown in below figure. Click OK.

F:\Articles\Dot Net 3.5\ListView EditUpdateAndDelete\ConfigDS2.png

Configuring ListView Control

Drag a ListView control from the data tab of Visual Studio 2008.  Click the Smart tag of ListView control and select the datasource control; Refer the below figure, SqlDataSource1 in our example.

F:\Articles\Dot Net 3.5\ListView with DataPager\ConfigLV.png

 

Click “Configure ListView...” option as seen in the above figure to choose the display Layout for the ListView. Choose a display layout, I have selected “Grid” in our example, as seen in the below figure. Click Ok.

F:\Articles\Dot Net 3.5\ListView EditUpdateAndDelete\ConfigLV.png

You can check “Enable Paging”, which will add a DataPager control in the LayoutTemplate of the ListView control. Read my previous article on Paging in ListView to understand more.

The insert item position can be configured as a LastItem or FirstItem using InsertItemPosition property of ListView control. Executing the page will give you an output similar to the below figure. In the below output, I have added paging feature using DataPager control.

F:\Articles\Dot Net 3.5\ListView EditUpdateAndDelete\LVWithDS.png



ASP.Net Hosting

Recent Articles

Edit/Update/Delete/Insert feature without using DataSource controls

1.      Drag a ListView control inside a webform as we did in previous section.  Specify the LayoutTemplate, ItemTemplate, EditItemTemplate, InsertItemTemplate that displays the ListView similar to the previous section.

<asp:ListView ID="lvEmployee" runat="server"    

    onitemediting="lvEmployee_ItemEditing"

    onitemupdating="lvEmployee_ItemUpdating"

    onitemcanceling="lvEmployee_ItemCanceling"

    onitemdeleting="lvEmployee_ItemDeleting"

    InsertItemPosition="LastItem"

    oniteminserting="lvEmployee_ItemInserting">

<LayoutTemplate>

<table id="Table1" runat="server">

    <tr id="Tr1" runat="server">

<td id="Td1" runat="server">

    <table ID="itemPlaceholderContainer" runat="server" border="0" style="">

<tr id="Tr2" runat="server" style="">

<th id="Th1" runat="server">

        </th>

<th id="Th2" runat="server">

     EmpID</th>

<th id="Th3" runat="server">

     EmpName</th>

<th id="Th4" runat="server">

     Department</th>

<th id="Th5" runat="server">

     Age</th>

        <th id="Th6" runat="server">

     Address</th>

</tr>

<tr ID="itemPlaceholder" runat="server">

</tr>

     </table>

</td>

    </tr>

    <tr id="Tr3" runat="server">

<td id="Td2" runat="server" style="">

</td>

    </tr>

</table>

</LayoutTemplate>

<ItemTemplate>

        <tr style="">

    <td>

<asp:Button ID="DeleteButton" runat="server" CommandName="Delete"

    Text="Delete" />

        <asp:Button ID="EditButton" runat="server" CommandName="Edit" Text="Edit" />

    </td>

    <td>

<asp:Label ID="EmpIDLabel" runat="server" Text='<%# Eval("EmpID") %>' />

            </td>

    <td>

<asp:Label ID="EmpNameLabel" runat="server" Text='<%# Eval("EmpName") %>' />

    </td>

    <td>

<asp:Label ID="DepartmentLabel" runat="server"

    Text='<%# Eval("Department") %>' />

    </td>

    <td>

<asp:Label ID="AgeLabel" runat="server" Text='<%# Eval("Age") %>' />

    </td>

    <td>

<asp:Label ID="AddressLabel" runat="server" Text='<%# Eval("Address") %>' />

    </td>

</tr>

</ItemTemplate>

<EditItemTemplate>

<tr style="">

    <td>

        <asp:Button ID="UpdateButton" runat="server" CommandName="Update"

    Text="Update" />

<asp:Button ID="CancelButton" runat="server" CommandName="Cancel"

    Text="Cancel" />

    </td>

    <td>

<asp:Label ID="EmpIDLabel1" runat="server" Text='<%# Eval("EmpID") %>' />

    </td>

    <td>

<asp:TextBox ID="EmpNameTextBox" runat="server" Text='<%# Bind("EmpName") %>' />

    </td>

    <td>

<asp:TextBox ID="DepartmentTextBox" runat="server"

    Text='<%# Bind("Department") %>' />

            </td>

    <td>

<asp:TextBox ID="AgeTextBox" runat="server" Text='<%# Bind("Age") %>' />

    </td>

    <td>

<asp:TextBox ID="AddressTextBox" runat="server" Text='<%# Bind("Address") %>' />

    </td>

</tr>

</EditItemTemplate>

<InsertItemTemplate>

<tr style="">

    <td>

<asp:Button ID="InsertButton" runat="server" CommandName="Insert"

    Text="Insert" />

<asp:Button ID="CancelButton" runat="server" CommandName="Cancel"

    Text="Clear" />

    </td>

    <td>

        &nbsp;</td>

    <td>

<asp:TextBox ID="EmpNameTextBox" runat="server" Text='<%# Bind("EmpName") %>' />

    </td>

    <td>

<asp:TextBox ID="DepartmentTextBox" runat="server"

    Text='<%# Bind("Department") %>' />

    </td>

    <td>

<asp:TextBox ID="AgeTextBox" runat="server" Text='<%# Bind("Age") %>' />

            </td>

    <td>

<asp:TextBox ID="AddressTextBox" runat="server" Text='<%# Bind("Address") %>' />

    </td>

</tr>

</InsertItemTemplate>

</asp:ListView>

2.      In the codebehind file, assign the DataTable or DataSet to the DataSource Property of the ListView control, like we do for a GridView control.

    protected void Page_Load(object sender, EventArgs e)

    {

        if (!IsPostBack)

        {

    lvEmployee.DataSource = GetEmployee("Select * from Employee");

    lvEmployee.DataBind();

        }

    }

    public DataTable GetEmployee(string query)

    {

        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString);

        SqlDataAdapter ada = new SqlDataAdapter(query, con);

        DataTable dtEmp = new DataTable();

        ada.Fill(dtEmp);

        return dtEmp;

    }

3.      We can write our own code to edit, update, delete and insert in the corresponding events of the ListView control. Refer the below code.

protected void lvEmployee_ItemEditing(object sender, ListViewEditEventArgs e)

    {

        lvEmployee.EditIndex = e.NewEditIndex;

    lvEmployee.DataSource = GetEmployee("Select * from Employee");

    lvEmployee.DataBind();

    }

  protected void lvEmployee_ItemUpdating(object sender, ListViewUpdateEventArgs e)

    {

    string empid = "", name = "", dept = "", age = "", address = "";

    Label lbl = (lvEmployee.Items[e.ItemIndex].FindControl("EmpIDLabel1")) as Label;

    if (lbl != null)

empid = lbl.Text;

    TextBox txt = (lvEmployee.Items[e.ItemIndex].FindControl("EmpNameTextBox")) as TextBox;

    if (txt != null)

name = txt.Text;

    txt = (lvEmployee.Items[e.ItemIndex].FindControl("DepartmentTextBox")) as TextBox;

    if (txt != null)

dept = txt.Text;

    txt = (lvEmployee.Items[e.ItemIndex].FindControl("AgeTextBox")) as TextBox;

    if (txt != null)

age = txt.Text;

    txt = (lvEmployee.Items[e.ItemIndex].FindControl("AddressTextBox")) as TextBox;

    if (txt != null)

address = txt.Text;

    string UpdateQuery = "UPDATE [Employee] SET [EmpName] = '" + name + "', [Department] = '" + dept + "', [Age] = '" + age + "', [Address] = '" + address + "' WHERE [EmpID] = '" + empid + "'";

    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString);

    con.Open();

    SqlCommand com = new SqlCommand(UpdateQuery, con);

    com.ExecuteNonQuery();

    con.Close();

    lvEmployee.EditIndex = -1;       

    lvEmployee.DataSource = GetEmployee("Select * from Employee");

    lvEmployee.DataBind();

    }

    protected void lvEmployee_ItemCanceling(object sender, ListViewCancelEventArgs e)

    {

        lvEmployee.EditIndex = -1;

    lvEmployee.DataSource = GetEmployee("Select * from Employee");

    lvEmployee.DataBind();

    }

    protected void lvEmployee_ItemDeleting(object sender, ListViewDeleteEventArgs e)

    {

        string empid = "";

        Label lbl = (lvEmployee.Items[e.ItemIndex].FindControl("EmpIDLabel")) as Label;

        if (lbl != null)

    empid = lbl.Text;

        string DeleteQuery = "Delete from Employee WHERE [EmpID] = '" + empid + "'";

        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString);

        con.Open();

        SqlCommand com = new SqlCommand(DeleteQuery, con);

        com.ExecuteNonQuery();

        con.Close();

        lvEmployee.EditIndex = -1;

        lvEmployee.DataSource = GetEmployee("Select * from Employee");

        lvEmployee.DataBind();

    }

protected void lvEmployee_ItemInserting(object sender, ListViewInsertEventArgs e)

    {

        string name = "", dept = "", age = "", address = "";

        TextBox txt = (e.Item.FindControl("EmpNameTextBox")) as TextBox;

        if (txt != null)

    name = txt.Text;

        txt = (e.Item.FindControl("DepartmentTextBox")) as TextBox;

        if (txt != null)

    dept = txt.Text;

        txt = (e.Item.FindControl("AgeTextBox")) as TextBox;

        if (txt != null)

    age = txt.Text;

        txt = (e.Item.FindControl("AddressTextBox")) as TextBox;

        if (txt != null)

    address = txt.Text;

        string INSERTQuery = "INSERT INTO [Employee] (EmpName,Department,Age,Address) VALUES ('" + name + "','" + dept + "','" + age + "','" + address + "')";

        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString);

        con.Open();

        SqlCommand com = new SqlCommand(INSERTQuery, con);

        com.ExecuteNonQuery();

        con.Close();

        lvEmployee.EditIndex = -1;  

        lvEmployee.DataSource = GetEmployee("Select * from Employee");

        lvEmployee.DataBind();

    }

 

Downloads

Download Source

 

Conclusion

Thus, we have learnt how to provide edit/update/delete and insert feature for ListView Control.  We can also handle these edit, update, delete and insert events in ItemCommand of ListView control. Since, ListView is capable of displaying the data in user defined formats these features will be very useful to do these operations in those layouts itself. Download the code attached with this article to see it in action.

Happy Coding!!!

Similar Articles
  • You can contribute to CodeDigest.Com:
    Article Feedback
    Title  
    Submitted By  
    Comment  
    Enter the verification number
     
    Comments
    Help!
    When I configure the data source of my listview and I clicked the advance the Generate Insert, Update, Delete Statments checkbox is disabled. It's greyed out.. How do I enable the checkbox in order to use the add edit delete for my listview? I'm totally new in asp.net. Please help!
    ListView
    It's good. But some events missing.
    listview
    its nice but more complicated
    so make easy
    <a href="http://www.careersoft-technology.com">tarun</a>
    Really good
    Congratulation.
    Not Good
    ya i have Read this article but i find its not good
    THANK YOU!!!
    The line:
    lvEmployee.EditIndex = e.NewEditIndex;
    Takes me a lot of internet navigation time, because in every website the examples are with sqldatasource.

    Thanks a lot!!!
    DataBind
    If you are using

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

    then your ItemEditing handler should look like this

    protected void lvEmployee_ItemEditing(object sender, ListViewEditEventArgs e)
    {
    lvEmployee.EditIndex = e.NewEditIndex;
    SetDataSource
    DataBind
    }

    or you are never get EditTemplate activated
    Nice post
    I was having some trouble getting my edit template to work. I had to go through about 20 other posts before I found yours. Thanks for making it simple.

    Also, Satheesh is right. That SQL you have is a disaster waiting to happen. If you have anything like that on a site you control I'd fix it ASAP before you get hacked.
    abc
    gud
    EditTemplate
    Hi,

    Nice post. I 've just made my own listview, everyting seems to work.
    Except the edittemplate, when I click the edit button, he never shows the editTemplate. I used "lvMine.EditIndex = e.NewEditIndex;" in the lvMine_itemediting method.
    Any ideas?
    RE:Edit,Update,Delete and Insert in ListView Control
    Hi Satheesh,
    Thanks for the comment!
    You are correct! inline sql query is prone to Sql injection attack.To make the implementation simple, i have made it as inline query and it is a good practise to have it as SP's.
    Edit,Update,Delete and Insert in ListView Control
    You should be careful with your sql statements. Pretty vulnerable to sql injection.

    Also, this is a great resource for people coming into the list view. One thing I'd add is a
    if (!IsPostBack)
    {databind()}

    in the datapaging prerender or you may get this error The control collection cannot be modified during DataBind, Init, Load, PreRender or Unload phases.