In this article I will explain how to work with controls on GridView Footer. Here i perform insert operation first using GridView footer. We did not read controls directly which are in Template fields of GridView.
Description
I am using same table as i used earlier in my previous update related to GridView.
Create Database Employee
Use Employee
Create table EmpDetail( Id int Identity(1,1), Name varchar(50),Designation varchar(50))
If you are aware from the Stored Procedures then the following SP code you can understand easily. Here i am using a single Stored Procedure fo to Insert, Update ,Delete,Update opeations.
CREATE PROCEDURE CrudOperations
@id int = 0,
@name varchar(50)=null,
@designation varchar(50)=null,
@status varchar(50)
AS
BEGIN
SET NOCOUNT ON;
--- Insert New Records
IF @status='INSERT'
BEGIN
INSERT INTO EmpDetail(Name,Designation) VALUES(@name,@designation)
END
--- Select Records in Table
IF @status='SELECT'
BEGIN
SELECT Id,Name,Designation FROM EmpDetail
END
--- Update Records in Table
IF @status='UPDATE'
BEGIN
UPDATE EmpDetail SET Name=@name,Designation=@designation WHERE Id=@id
END
--- Delete Records from Table
IF @status='DELETE'
BEGIN
DELETE FROM EmpDetailwhere Id=@id
END
SET NOCOUNT OFF
END
Now on Web-Form take a grid view control and give some style to it for making its interactive.
Aspx Code-- -- -- -- -- -- --
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
<style type="text/css">
.GridviewDiv {font-size: 100%; font-family: 'Lucida Grande', 'Lucida Sans Unicode', Verdana, Arial,Helevetica, sans-serif; color: #303933;}
.headerstyle
{
color:#FFFFFF;border-right-color:#abb079;border-bottom-color:#abb079;background-color:#df5015;padding:0.5em 0.5em 0.5em 0.5em;text-align:center;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div class="GridviewDiv">
<asp:GridView runat="server" ID="gvDetails" ShowFooter="true" AllowPaging="true" PageSize="10"AutoGenerateColumns="false" DataKeyNames="Id,Name" OnPageIndexChanging="gvDetails_PageIndexChanging"OnRowCancelingEdit="gvDetails_RowCancelingEdit"
OnRowEditing="gvDetails_RowEditing" OnRowUpdating="gvDetails_RowUpdating"OnRowDeleting="gvDetails_RowDeleting" OnRowCommand ="gvDetails_RowCommand" >
<HeaderStyle CssClass="headerstyle" />
<Columns>
<asp:BoundField DataField="Id" HeaderText="Employee Id" ReadOnly="true" />
<asp:TemplateField HeaderText="Employee
Name">
<ItemTemplate>
<asp:Label ID="lblname" runat="server" Text='<%#
Eval("Name")%>'/>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtname" runat="server" Text='<%#
Eval("Name")%>'/>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddname" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText = "Designation">
<ItemTemplate>
<asp:Label ID="lblDesignation" runat="server" Text='<%#
Eval("Designation")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtDesignation" runat="server" Text='<%#
Eval("Designation")%>'/>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddDesignation" runat="server" />
<asp:Button ID="btnAdd" CommandName="AddNew" runat="server" Text="Add" />
</FooterTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" ShowDeleteButton="true" />
</Columns>
</asp:GridView>
<asp:Label ID="lblresult" runat="server"></asp:Label>
</div>
</form>
</body>
</html>
After doing the complete code on aspx page now write code on .CS page. For to open a code Window you can just right click on aspx page and click on View Code.
.CS Code-- -- -- -- -- -- --
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridview();
}
}
protected void BindGridview()
{
DataSet ds = new DataSet();
using (SqlConnection con = new SqlConnection("Data
Source=JP;Initial Catalog=Employee ;Integrated Security=True"))
{
con.Open();
SqlCommand cmd = new SqlCommand("crudoperations", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@status", "SELECT");
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
con.Close();
if (ds.Tables[0].Rows.Count > 0)
{
gvDetails.DataSource = ds;
gvDetails.DataBind();
}
else
{
ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
gvDetails.DataSource = ds;
gvDetails.DataBind();
int columncount = gvDetails.Rows[0].Cells.Count;
gvDetails.Rows[0].Cells.Clear();
gvDetails.Rows[0].Cells.Add(new TableCell());
gvDetails.Rows[0].Cells[0].ColumnSpan = columncount;
gvDetails.Rows[0].Cells[0].Text
= "No Records Found";
}
}
}
protected void gvDetails_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("AddNew"))
{
TextBox txtnm = (TextBox)gvDetails.FooterRow.FindControl("txtAddname");
TextBox txtdes = (TextBox)gvDetails.FooterRow.FindControl("txtAddDesignation");
crudoperations("INSERT",
txtnm.Text, txtdes.Text, 0);
}
}
protected void gvDetails_RowEditing(object sender, GridViewEditEventArgs e)
{
gvDetails.EditIndex = e.NewEditIndex;
BindGridview();
}
protected void gvDetails_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gvDetails.EditIndex = -1;
BindGridview();
}
protected void gvDetails_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvDetails.PageIndex = e.NewPageIndex;
BindGridview();
}
protected void gvDetails_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int empid = Convert.ToInt32(gvDetails.DataKeys[e.RowIndex].Values["Id"].ToString());
TextBox txtnm = (TextBox)gvDetails.Rows[e.RowIndex].FindControl("txtName");
TextBox txtdes = (TextBox)gvDetails.Rows[e.RowIndex].FindControl("txtDesignation");
crudoperations("UPDATE",
txtnm.Text, txtdes.Text, empid);
}
protected void gvDetails_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int id = Convert.ToInt32(gvDetails.DataKeys[e.RowIndex].Values["Id"].ToString());
string name = gvDetails.DataKeys[e.RowIndex].Values["Name"].ToString();
crudoperations("DELETE", name, "", id);
}
protected void crudoperations(string status, string Name, string Designation, int Id)
{
using (SqlConnection con = new SqlConnection("Data
Source=JP;Initial Catalog=Employee ;Integrated Security=True"))
{
con.Open();
SqlCommand cmd = new SqlCommand("crudoperations", con);
cmd.CommandType = CommandType.StoredProcedure;
if (status == "INSERT")
{
cmd.Parameters.AddWithValue("@status",
status);
cmd.Parameters.AddWithValue("@name", Name);
cmd.Parameters.AddWithValue("@designation",
Designation);
}
else if (status == "UPDATE")
{
cmd.Parameters.AddWithValue("@status",
status);
cmd.Parameters.AddWithValue("@name", Name);
cmd.Parameters.AddWithValue("@designation",
Designation);
cmd.Parameters.AddWithValue("@id", Id);
}
else if (status == "DELETE")
{
cmd.Parameters.AddWithValue("@status",
status);
cmd.Parameters.AddWithValue("@id", Id);
}
cmd.ExecuteNonQuery();
lblresult.ForeColor = Color.Red;
lblresult.Text = Name + " details " +
status.ToLower() + "d successfully";
gvDetails.EditIndex = -1;
BindGridview();
}
}
In the above code i use the CrudOperation method for to make code easy to understand and more clear. The main concept to understand is gvDetails_RowCommand Event. In this event i read the footer Template controls value.
TextBox txtnm = (TextBox)gvDetails.FooterRow.FindControl("txtAddname");
In this line of code first we find the control and then TypeCast it to its Control type.
I hope this article helps you to perform CRUD in Grid using FooterTemplate.
It really helpful. Thanks from Philippines
ReplyDeleteGreat blog yyou have here
ReplyDelete