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.
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: