ListView Edit,Update,Delete in Asp .net using Ado .net

In this article we will see how to insert data, Display data in ListView control, create edit and delete functionality in ListView control using ado .net. ListView is very similar to Repeater control excepts it has paging option by using DataPager. By default it does not have its own default view which gives us great flexibility to design and apply custom CSS.

Lets begin:

Step1: First of all we need database to insert, update, delete and display records in ListView control.Create Database "EmployeeTest"(You can choose your prefered database name).

Step2: Create a table named "Employee" (You can also change table name as per your needs).

 

CREATE TABLE Employee(
[Id] [int] PRIMARY KEY IDENTITY(1,1),
[Name] [nvarchar](50) NULL,
[Email] [nvarchar](50) NULL,
[Age] [int] NULL,
[Salary] [float] NULL)
Step3: Make connection string and pass database information.

 
Step4: Make HTML form to input data. 
Note: I have not used any validations for this demo.You can use your validations accordingly.
 
 ListView-add-edit-update-delete-asp-net-codingfusion
 
Name
Email
Age
Salary
  <%--//======= By default we have made update button visible false. So that when ever page loads first time only save and cancel buttons are visible.--%>
 
Step5: Coding for Save buttion Click.
 
 //=-=-=-=-= Save Button
    protected void btnSave_Click(object sender, EventArgs e)
    {

        //====== Getting connection string defined in the web.config file. Pointed to the database we want to use.
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["EmployeeConnection"].ConnectionString);

        //======= Insert Query.
        string cmdText = "INSERT INTO employee (Name,Email,Age,Salary) VALUES (@Name,@Email,@Age,@Salary)";

        //====== Providning information to SQL command object about which query to 
        //====== execute and from where to get database connection information.
        SqlCommand cmd = new SqlCommand(cmdText, con);

        //===== Adding parameters/Values.
        cmd.Parameters.AddWithValue("@Name", txtName.Text);
        cmd.Parameters.AddWithValue("@Email", txtEmail.Text);
        cmd.Parameters.AddWithValue("@Age", Convert.ToInt32(txtAge.Text));
        cmd.Parameters.AddWithValue("@Salary", Convert.ToDouble(txtSalary.Text));

        //===== To check current state of the connection object. If it is closed open the connection
        //===== to execute the insert query.
        if (con.State == ConnectionState.Closed)
        {
            con.Open();
        }

        //===== Execute Query.
        cmd.ExecuteNonQuery();

        //===== close the connection.
        con.Close();

        //===== Clear text from textboxes
        clearInputControls();

        //===== Bind data to ListView.
        bindEmployeeDetailsToListView();

    }

 

Step6: We have successfully saved our data to database. Now lets create ListView control.

 

 
        
                
                    ">
                        
Sno Name Email Age Salary Action
<%#Container.DataItemIndex+1%> <%#Eval("Name") %> <%#Eval("Email") %> <%#Eval("Age") %> <%#Eval("Salary") %> <%--//==== Here we have used CommandName property to distinguish which button is clicked and we have passed our primary key to CommandArgument property. ====//--%>

 

 

Step7: Create some required methods which we have used in save functionality i.e. "bindEmployeeDetailsToListView()" and "clearInputControls()" Methods. bindEmployeeDetailsToListView() method is used to bind records into ListView and "clearInputControls" is used to empty textboxes data after save operation.

 

BindEmployeeDetailsToListView() Method

//===== Method to bind employee records to ListView control.
    void bindEmployeeDetailsToListView()
    {
        //====== Getting connection string defined in the web.config file. Pointed to the database we want to use.
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["EmployeeConnection"].ConnectionString);

        //======= Select Query.
        string cmdText = "SELECT * FROM employee";

        //====== Providning information to SQL command object about which query to 
        //====== execute and from where to get database connection information.
        SqlCommand cmd = new SqlCommand(cmdText, con);

        //===== To check current state of the connection object. If it is closed open the connection
        //===== to execute the insert query.
        if (con.State == ConnectionState.Closed)
        {
            con.Open();
        }

        //===== Execute Query and bind data to ListView.
        lstViewEmployeeDetails.DataSource = cmd.ExecuteReader();
        lstViewEmployeeDetails.DataBind();
    }

clearInputControls() Method

 //===== Clear Inut control's data.
    void clearInputControls()
    {
        txtAge.Text = string.Empty;
        txtEmail.Text = string.Empty;
        txtName.Text = string.Empty;
        txtSalary.Text = string.Empty;
    }

Step8: Call "bindEmployeeDetailsToListView()" in the pageload so that data get binds to ListView when page loads first time.

 

 protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            //===== To bind employee's records from database.
            bindEmployeeDetailsToListView();
        }
    }

Step9: Now we will create edit and delte functionality so that whenever edit button is clicked corresponding data will inserted into related textboxes.For this we will use ListView's "OnItemCommand" Event.

 

 //========= Edit,Delete buttons inside ListView.
    protected void lstViewEmployeeDetails_ItemCommand(object sender, ListViewCommandEventArgs e)
    {

        //====== Here we use switch state to distinguish which link button is clicked based 
        //====== on command name supplied to the link button.
        switch (e.CommandName)
        {
            //==== This case will fire when link button placed
            //==== inside Listview having command name "Delte" is clicked.

            case ("Del"):
                //==== Getting id of the selelected record(We have passed on link button's command argument property).
                int id = Convert.ToInt32(e.CommandArgument);

                //==== Call delete method and pass id as argument.
                deleteEmployee(id);

                break;

            //==== This case will fire when link button placed
            //==== inside ListView having command name "Edt" is clicked.
            case ("Edt"):

                //==== Getting id of the selelected record(We have passed on link button's command argument property).
                id = Convert.ToInt32(e.CommandArgument);

                //==== Call delete method and pass id as argument.
                bindEmployeeDetailToEdit(id);

                break;


        }
    }

 

deleteEmployee() Method

 

//===== Method to delete employee from database.
    void deleteEmployee(int id)
    {
        //====== Getting connection string defined in the web.config file. Pointed to the database we want to use.
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["EmployeeConnection"].ConnectionString);

        //======= Delete Query.
        string cmdText = "DELETE FROM employee WHERE Id=@Id";

        //====== Providning information to SQL command object about which query to 
        //====== execute and from where to get database connection information.
        SqlCommand cmd = new SqlCommand(cmdText, con);

        //===== Adding parameters/Values.
        cmd.Parameters.AddWithValue("@Id", id);

        //===== To check current state of the connection object. If it is closed open the connection
        //===== to execute the insert query.
        if (con.State == ConnectionState.Closed)
        {
            con.Open();
        }

        //===== Execute Query.
        cmd.ExecuteNonQuery();

        //===== close the connection.
        con.Close();

        //===== Bind data to listview.
        bindEmployeeDetailsToListView();
    }

 

 

bindEmployeeDetailToEdit() Method

 

 //==== Method to bind data to textboxes for update.
    public void bindEmployeeDetailToEdit(int id)
    {
        //====== Getting connection string defined in the web.config file. Pointed to the database we want to use.
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["EmployeeConnection"].ConnectionString);

        //======= Query.
        string cmdText = "SELECT * FROM employee WHERE Id=@Id";

        //====== Providning information to SQL command object about which query to 
        //====== execute and from where to get database connection information.
        SqlCommand cmd = new SqlCommand(cmdText, con);

        //===== Adding parameters/Values.
        cmd.Parameters.AddWithValue("@Id", id);

        //===== To check current state of the connection object. If it is closed open the connection
        //===== to execute the insert query.
        if (con.State == ConnectionState.Closed)
        {
            con.Open();
        }

        //===== Execute Query.
        SqlDataReader dr = cmd.ExecuteReader();

        //=== Read Data.
        if (dr.HasRows)
        {
            dr.Read();
            txtEmail.Text = dr["Email"].ToString();
            txtAge.Text = dr["Age"].ToString();
            txtName.Text = dr["Name"].ToString();
            txtSalary.Text = dr["Salary"].ToString();

            //=== Make update button visible and save button invisible
            btnUpdate.Visible = true;
            btnSave.Visible = false;
        }

        //===== close the connection.
        con.Close();
    }

 

Step10: Create update functionality.

 

  //========= Update Button
    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        //====== Getting connection string defined in the web.config file. Pointed to the database we want to use.
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["EmployeeConnection"].ConnectionString);

        //======= Insert Query.
        string cmdText = "UPDATE employee SET Name=@Name,Email=@Email,Age=@Age,Salary=@Salary WHERE Id=@Id";

        //====== Providning information to SQL command object about which query to 
        //====== execute and from where to get database connection information.
        SqlCommand cmd = new SqlCommand(cmdText, con);

        //===== Adding parameters/Values.
        cmd.Parameters.AddWithValue("@Name", txtName.Text);
        cmd.Parameters.AddWithValue("@Email", txtEmail.Text);
        cmd.Parameters.AddWithValue("@Age", Convert.ToInt32(txtAge.Text));
        cmd.Parameters.AddWithValue("@Salary", Convert.ToDouble(txtSalary.Text));

        //====== Remember we have stored primary key in hiddenfield during 
        //====== binding values into textboxes method:(bindEmployeeDetailToEdit).
        //====== We will use same id to pass id parameter.
        cmd.Parameters.AddWithValue("@Id", Convert.ToInt32(hfSelectedRecord.Value));


        //===== To check current state of the connection object. If it is closed open the connection
        //===== to execute the insert query.
        if (con.State == ConnectionState.Closed)
        {
            con.Open();
        }

        //===== Execute Query.
        cmd.ExecuteNonQuery();

        //===== close the connection.
        con.Close();

        //===== Clear text from textboxes
        clearInputControls();

        //===== Bind data to listview.
        bindEmployeeDetailsToListView();

        //===== Show Save button and hide update button.
        btnSave.Visible = true;
        btnUpdate.Visible = false;

        //===== Clear Hiddenfield
        hfSelectedRecord.Value = string.Empty;
    }

 

Step11: Create CSS to give ListView some good looks.

 

 

 

 Final Output:

ListView-Edit-update-delete-Codingfusion-Anuj-koundal
ListView-Edit-update-delete-CodingFusion-Anuj-Koundal
We are nothing without our users ! You can help us offer even more high quality content. Please share our page !
Best quality Asp .Net Ajax Control Toolkit tutorials.
when I look this site for somthing learn.I find this is to much and i like the site very much....thank to ur team...
17-Dec-2013 From  prakash kumar
Thanks prakash for your beautiful and valuable comment. Stay tuned for more articles.
21-Dec-2013 From  Anuj
sir its good..but i need more...
30-Dec-2013 From  sanjeev
Thanks sanjeev... what do you need more articles?
15-Jan-2014 From  Anuj
Thanks for the code, but i found one error on step 6 # at "<%#(Container.DataItemIndex+1)%2==0?" altrow":"normalrow"%="">" Can you please tell me why? Thanks
17-Jan-2014 From  Tashi
Thanks for pointing the issue you can do like this class="<%#(Container.DataItemIndex+1)%2==0?" altrow":"normalrow"%>"> or simply use tr tag. I will provide download link soon Thanks
17-Jan-2014 From  Anuj
Thank you for your post. Good article. Where did you defined the method bindEmployeeDetailToEdit(id);
25-Jan-2014 From  venkat
Thanks venkat for pointing the issue... Code is updated kindly check
28-Jan-2014 From  Anuj
bindEmployeeDetailToEdit(); method is not working for me.
9-Mar-2014 From  rico
It's super artical it help me alot... One request i want wcf with n-tier same sample can u send me...
26-Mar-2014 From  Nagesh
C# codeing in update
1-Apr-2014 From  ankit khandivar
Hi Nagesh. Thanks for your lovely words. I'll try to send you soon.
6-Apr-2014 From  Anuj
Hi It's nice artical help me but One request i want wcf with n-tier same sample can u send me too..
21-May-2014 From  Piyush
Hi piyush I'll try to send you soon.
25-May-2014 From  Anuj

Give your valuable comments.

Name
Email
Comment
7 + 8 =
 
About Us | Terms of Use | Privacy Policy | Disclaimer | Contact Us Copyright © 2012-2017 CodingFusion