Monday, 8 December 2014
Wednesday, 3 December 2014
Tuesday, 25 November 2014
Thursday, 13 November 2014
Monday, 20 October 2014
Friday, 17 October 2014
Thursday, 25 September 2014
Friday, 19 September 2014
Tuesday, 16 September 2014
Wednesday, 27 August 2014
uploading and generating Thumbnails asp.net webforms
HTML
<form id="form1" runat="server">
<h3>Upload image with Thumbnail</h3>
<hr />
<div>
Select Image :
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />
</div>
<div>
<br />
<br />
<div>
<asp:DataList ID="DataList1" runat="server" RepeatColumns="3"
RepeatDirection="Horizontal" BackColor="White" BorderColor="#CC9966"
BorderStyle="None" BorderWidth="1px" CellPadding="4" GridLines="Both">
<FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
<ItemStyle BackColor="White" ForeColor="#330099" />
<SelectedItemStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
<ItemTemplate>
<div style="text-align:center">
<div><a target="_blank" href='/Images/<%#Eval("FileName")%>'><img src="/Thumbnail/<%#Eval("FileName")%>" /></a></div>
<div ><%#Eval("FileSize")%> KB</div>
<div><a target="_blank" href='/Images/<%#Eval("FileName")%>'>View Full Size</a> </div>
</div>
</ItemTemplate>
</asp:DataList>
</div>
</div>
</form>
****************************Back Coding**************************
public partial class ImageTest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnUpload_Click(object sender, EventArgs e)
{
string uploadedFileName = FileUpload1.PostedFile.FileName;
Image img = Image.FromStream(FileUpload1.PostedFile.InputStream);
string ext = Path.GetExtension(uploadedFileName);
string uploadFilePath = DateTime.Now.ToString("ddMMyyyyhhmmsstt");
string imageFile = uploadFilePath + ext;
try
{
FileUpload1.PostedFile.SaveAs(Path.Combine(Server.MapPath("~/Images"), imageFile));
var ratio = (double)100 / img.Height;
int imageHeight = (int)(img.Height * ratio);
int imageWidth = (int)(img.Width * ratio);
Image.GetThumbnailImageAbort dCallback = new Image.GetThumbnailImageAbort(ThumbnailCallback);
Image thumbnailImg = img.GetThumbnailImage(imageWidth, imageHeight, dCallback, IntPtr.Zero);
thumbnailImg.Save(Path.Combine(Server.MapPath("~/Thumbnail"), imageFile), ImageFormat.Jpeg);
thumbnailImg.Dispose();
//Here Code for Get Uploaded Images
PopulateImage();
}
catch (Exception ex)
{
throw;
}
}
public bool ThumbnailCallback()
{
return true;
}
private void PopulateImage()
{
DirectoryInfo dir = new DirectoryInfo(Server.MapPath("~/Images"));
List<MyImageFiles> images = new List<MyImageFiles>();
foreach (var i in dir.GetFiles())
{
images.Add(new MyImageFiles { FileName = i.Name, FileSize = (i.Length / 1024).ToString() });
}
DataList1.DataSource = images;
DataList1.DataBind();
}
}
********************class****************
public class MyImageFiles
{
public string FileName { get; set; }
public string FileSize { get; set; }
}
Tuesday, 26 August 2014
Sunday, 10 August 2014
Wednesday, 6 August 2014
Wednesday, 16 July 2014
Monday, 14 July 2014
Wednesday, 9 July 2014
Sunday, 15 June 2014
Monday, 2 June 2014
Monday, 19 May 2014
Dynamic Menu using Repeater by Me working
----------------------------------------Page Design-------------------------------
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DynamicMenu.aspx.cs" Inherits="MyTestLearnProject.DynamicMenu" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
.menu{
width: auto;
margin: 0px auto;
font-family: Arial, Helvetica, sans-serif;
font-weight: bold;
font-size: 14px;
}
.menu ul li a:link, div ul li a:visited {
display: block;
background-color: #f1f1f1;color:#000;
text-align: center;
text-decoration: none;
padding: 4px;
border-bottom: 1px solid #fff;
width: 150px;
}
.menu ul li a:hover{
background-color: #ccc;
}
.menu ul li ul li a:link, li ul li a:visited {
display: block;
background-color: #f1f1f1;
color: #000;
text-align: center;
text-decoration: none;
padding: 4px;
border-bottom: 1px solid #fff;
width: 150px;
}
.menu ul li ul li a:hover {
background-color: #ccc;
}
.menu ul {
list-style-type: none;
margin: 0px;
padding: 0px;
}
.menu ul li {
float: left;
margin-left: 5px;
}
.menu ul li ul li {
float: none;
margin-left: 0px;
}
.menu ul li ul {
display: none;
}
.menu li:hover ul{
display: block;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<asp:repeater ID="rptCategories" runat="server" OnItemDataBound="rptCategories_ItemDataBound">
<headertemplate>
<div class="menu" id="gn" runat="server">
<ul>
</ul>
</div>
</headertemplate>
<itemtemplate>
<div class="menu" id="gn" runat="server">
<ul>
<li>
<a href='<%#Eval("MenuUrl") %>'><%#Eval("CategoryName") %></a>
<asp:literal ID="ltrlSubMenu" runat="server"></asp:literal>
</li>
</ul>
</div>
</itemtemplate>
<footertemplate>
</footertemplate>
</asp:repeater>
</form>
</body>
</html>
-----------------------------------------------------Back End Code--------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using BE;
using BLL;
using System.IO;
using System.Text;
namespace MyTestLearnProject
{
public partial class DynamicMenu : System.Web.UI.Page
{
DataTable allCategories = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadCategories();
}
}
public void LoadCategories()
{
allCategories = new menuBLL().GetAllCategories();
rptCategories.DataSource = new menuBLL().GetCategories();
rptCategories.DataBind();
}
protected void rptCategories_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
if (allCategories != null)
{
DataRowView drv = e.Item.DataItem as DataRowView;
string ID = drv["ID"].ToString();
DataRow[] rows = allCategories.Select("ParentID=" + ID, "CategoryName");
if (rows.Length > 0)
{
StringBuilder sb = new StringBuilder();
sb.Append("<ul>");
foreach (var item in rows)
{
sb.Append("<li><a href='"+item["MenuUrl"]+"'>" + item["CategoryName"] + "</a></li>");
}
sb.Append("</ul>");
(e.Item.FindControl("ltrlSubMenu") as Literal).Text = sb.ToString();
}
}
}
}
}
}
----------------------------------------Menu DAL--------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
namespace DAL
{
public class menuDAL
{
private string path = MyConnection.path;
public DataTable GetCategories()
{
SqlConnection con = new SqlConnection(path);
SqlCommand cmd = new SqlCommand("select ID,CategoryName,MenuUrl from tblMenu where ParentID=0", con);
DataTable dt = new DataTable();
try
{
con.Open();
SqlDataReader sdr = cmd.ExecuteReader();
if (sdr.HasRows)
{
dt.Load(sdr);
}
}
catch (Exception)
{
throw;
}
finally
{
con.Close();
}
return dt;
}
public DataTable GetAllCategories()
{
SqlConnection con = new SqlConnection(path);
SqlCommand cmd = new SqlCommand("select * from tblMenu", con);
DataTable dt = new DataTable();
try
{
con.Open();
SqlDataReader sdr = cmd.ExecuteReader();
if (sdr.HasRows)
{
dt.Load(sdr);
}
}
catch (Exception)
{
throw;
}
finally
{
con.Close();
}
return dt;
}
}
}
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DynamicMenu.aspx.cs" Inherits="MyTestLearnProject.DynamicMenu" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
.menu{
width: auto;
margin: 0px auto;
font-family: Arial, Helvetica, sans-serif;
font-weight: bold;
font-size: 14px;
}
.menu ul li a:link, div ul li a:visited {
display: block;
background-color: #f1f1f1;color:#000;
text-align: center;
text-decoration: none;
padding: 4px;
border-bottom: 1px solid #fff;
width: 150px;
}
.menu ul li a:hover{
background-color: #ccc;
}
.menu ul li ul li a:link, li ul li a:visited {
display: block;
background-color: #f1f1f1;
color: #000;
text-align: center;
text-decoration: none;
padding: 4px;
border-bottom: 1px solid #fff;
width: 150px;
}
.menu ul li ul li a:hover {
background-color: #ccc;
}
.menu ul {
list-style-type: none;
margin: 0px;
padding: 0px;
}
.menu ul li {
float: left;
margin-left: 5px;
}
.menu ul li ul li {
float: none;
margin-left: 0px;
}
.menu ul li ul {
display: none;
}
.menu li:hover ul{
display: block;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<asp:repeater ID="rptCategories" runat="server" OnItemDataBound="rptCategories_ItemDataBound">
<headertemplate>
<div class="menu" id="gn" runat="server">
<ul>
</ul>
</div>
</headertemplate>
<itemtemplate>
<div class="menu" id="gn" runat="server">
<ul>
<li>
<a href='<%#Eval("MenuUrl") %>'><%#Eval("CategoryName") %></a>
<asp:literal ID="ltrlSubMenu" runat="server"></asp:literal>
</li>
</ul>
</div>
</itemtemplate>
<footertemplate>
</footertemplate>
</asp:repeater>
</form>
</body>
</html>
-----------------------------------------------------Back End Code--------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using BE;
using BLL;
using System.IO;
using System.Text;
namespace MyTestLearnProject
{
public partial class DynamicMenu : System.Web.UI.Page
{
DataTable allCategories = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadCategories();
}
}
public void LoadCategories()
{
allCategories = new menuBLL().GetAllCategories();
rptCategories.DataSource = new menuBLL().GetCategories();
rptCategories.DataBind();
}
protected void rptCategories_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
if (allCategories != null)
{
DataRowView drv = e.Item.DataItem as DataRowView;
string ID = drv["ID"].ToString();
DataRow[] rows = allCategories.Select("ParentID=" + ID, "CategoryName");
if (rows.Length > 0)
{
StringBuilder sb = new StringBuilder();
sb.Append("<ul>");
foreach (var item in rows)
{
sb.Append("<li><a href='"+item["MenuUrl"]+"'>" + item["CategoryName"] + "</a></li>");
}
sb.Append("</ul>");
(e.Item.FindControl("ltrlSubMenu") as Literal).Text = sb.ToString();
}
}
}
}
}
}
----------------------------------------Menu DAL--------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
namespace DAL
{
public class menuDAL
{
private string path = MyConnection.path;
public DataTable GetCategories()
{
SqlConnection con = new SqlConnection(path);
SqlCommand cmd = new SqlCommand("select ID,CategoryName,MenuUrl from tblMenu where ParentID=0", con);
DataTable dt = new DataTable();
try
{
con.Open();
SqlDataReader sdr = cmd.ExecuteReader();
if (sdr.HasRows)
{
dt.Load(sdr);
}
}
catch (Exception)
{
throw;
}
finally
{
con.Close();
}
return dt;
}
public DataTable GetAllCategories()
{
SqlConnection con = new SqlConnection(path);
SqlCommand cmd = new SqlCommand("select * from tblMenu", con);
DataTable dt = new DataTable();
try
{
con.Open();
SqlDataReader sdr = cmd.ExecuteReader();
if (sdr.HasRows)
{
dt.Load(sdr);
}
}
catch (Exception)
{
throw;
}
finally
{
con.Close();
}
return dt;
}
}
}
Tuesday, 13 May 2014
Tuesday, 29 April 2014
Friday, 25 April 2014
Thursday, 24 April 2014
Wednesday, 23 April 2014
Wednesday, 16 April 2014
Thursday, 3 April 2014
Grid View Custom Paging..
****************SP***********
CREATE PROCEDURE sp_getAllDataPager
@PageNo int,
@NoOfRecord int,
@TotalRecord int output
AS
-- Here Get Total No of record
Select @TotalRecord = Count(*) from tblLab
Select * from
(
Select
Row_number() over( Order by ID ASC) as RowNo,
ID,
Assignment,
RollNo
From
tblLab
) as Tab
Where
Tab.RowNo between ((@PageNo - 1) * @NoOfRecord) + 1 and (@PageNo * @NoOfRecord)
Order by ID ASC
RETURN
*******************Design page***********
<body>
<form id="form1" runat="server">
<div>
<div>
<asp:GridView ID="GridView1" runat="server" CellSpacing="5" AutoGenerateColumns="true" Width="442px">
</asp:GridView>
<asp:Panel ID="Panel1" runat="server"></asp:Panel>
</div>
</div>
</form>
</body>
******************Code Behind**************
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Collections;
namespace MyTestLearnProject
{
public partial class GridViewCustomPagerTest : System.Web.UI.Page
{
private static SqlConnection GetCon()
{
SqlConnection con = new SqlConnection(@"Data Source=LHR-MH-PC79\;Initial Catalog=DBStudentTest;Integrated Security=True");
return con;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
populateGrid(1, 5);
}
AddpagingButton();
}
protected void populateGrid(int pageNo, int noOfRecord)
{
SqlConnection con = GetCon();
SqlCommand cmd = new SqlCommand("sp_getAllDataPager", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@PageNo", pageNo);
cmd.Parameters.AddWithValue("@NoOfRecord", noOfRecord);
SqlParameter TotalRecordSP = new SqlParameter("@TotalRecord", System.Data.SqlDbType.Int);
TotalRecordSP.Direction = System.Data.ParameterDirection.Output;
cmd.Parameters.Add(TotalRecordSP);
DataTable dt = new DataTable();
if (con.State != ConnectionState.Open)
{
con.Open();
}
dt.Load(cmd.ExecuteReader());
int totalRecord = 0;
if (TotalRecordSP.Value != null)
{
int.TryParse(TotalRecordSP.Value.ToString(), out totalRecord);
}
GridView1.DataSource = dt;
GridView1.DataBind();
// Store Total Record & No of record per page into view state for use in Generate Paging button method
ViewState["TotalRecord"] = totalRecord;
ViewState["NoOfRecord"] = noOfRecord;
}
private void AddpagingButton()
{
// this method for generate custom button for Custom paging in Gridview
int totalRecord = 0;
int noofRecord = 0;
totalRecord = ViewState["TotalRecord"] != null ? (int)ViewState["TotalRecord"] : 0;
noofRecord = ViewState["NoOfRecord"] != null ? (int)ViewState["NoOfRecord"] : 0;
int pages = 0;
if (totalRecord > 0 && noofRecord > 0)
{
// Count no of pages
pages = (totalRecord / noofRecord) + ((totalRecord % noofRecord) > 0 ? 1 : 0);
for (int i = 0; i < pages; i++)
{
Button b = new Button();
b.Text = (i + 1).ToString();
b.CommandArgument = (i + 1).ToString();
b.ID = "Button_" + (i + 1).ToString();
b.Click += new EventHandler(this.b_click);
Panel1.Controls.Add(b);
}
}
}
protected void b_click(object sender, EventArgs e)
{
// this is for Get data from Database on button (paging button) click
string pageNo = ((Button)sender).CommandArgument;
populateGrid(Convert.ToInt32(pageNo), 5);
}
}
}
CREATE PROCEDURE sp_getAllDataPager
@PageNo int,
@NoOfRecord int,
@TotalRecord int output
AS
-- Here Get Total No of record
Select @TotalRecord = Count(*) from tblLab
Select * from
(
Select
Row_number() over( Order by ID ASC) as RowNo,
ID,
Assignment,
RollNo
From
tblLab
) as Tab
Where
Tab.RowNo between ((@PageNo - 1) * @NoOfRecord) + 1 and (@PageNo * @NoOfRecord)
Order by ID ASC
RETURN
*******************Design page***********
<body>
<form id="form1" runat="server">
<div>
<div>
<asp:GridView ID="GridView1" runat="server" CellSpacing="5" AutoGenerateColumns="true" Width="442px">
</asp:GridView>
<asp:Panel ID="Panel1" runat="server"></asp:Panel>
</div>
</div>
</form>
</body>
******************Code Behind**************
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Collections;
namespace MyTestLearnProject
{
public partial class GridViewCustomPagerTest : System.Web.UI.Page
{
private static SqlConnection GetCon()
{
SqlConnection con = new SqlConnection(@"Data Source=LHR-MH-PC79\;Initial Catalog=DBStudentTest;Integrated Security=True");
return con;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
populateGrid(1, 5);
}
AddpagingButton();
}
protected void populateGrid(int pageNo, int noOfRecord)
{
SqlConnection con = GetCon();
SqlCommand cmd = new SqlCommand("sp_getAllDataPager", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@PageNo", pageNo);
cmd.Parameters.AddWithValue("@NoOfRecord", noOfRecord);
SqlParameter TotalRecordSP = new SqlParameter("@TotalRecord", System.Data.SqlDbType.Int);
TotalRecordSP.Direction = System.Data.ParameterDirection.Output;
cmd.Parameters.Add(TotalRecordSP);
DataTable dt = new DataTable();
if (con.State != ConnectionState.Open)
{
con.Open();
}
dt.Load(cmd.ExecuteReader());
int totalRecord = 0;
if (TotalRecordSP.Value != null)
{
int.TryParse(TotalRecordSP.Value.ToString(), out totalRecord);
}
GridView1.DataSource = dt;
GridView1.DataBind();
// Store Total Record & No of record per page into view state for use in Generate Paging button method
ViewState["TotalRecord"] = totalRecord;
ViewState["NoOfRecord"] = noOfRecord;
}
private void AddpagingButton()
{
// this method for generate custom button for Custom paging in Gridview
int totalRecord = 0;
int noofRecord = 0;
totalRecord = ViewState["TotalRecord"] != null ? (int)ViewState["TotalRecord"] : 0;
noofRecord = ViewState["NoOfRecord"] != null ? (int)ViewState["NoOfRecord"] : 0;
int pages = 0;
if (totalRecord > 0 && noofRecord > 0)
{
// Count no of pages
pages = (totalRecord / noofRecord) + ((totalRecord % noofRecord) > 0 ? 1 : 0);
for (int i = 0; i < pages; i++)
{
Button b = new Button();
b.Text = (i + 1).ToString();
b.CommandArgument = (i + 1).ToString();
b.ID = "Button_" + (i + 1).ToString();
b.Click += new EventHandler(this.b_click);
Panel1.Controls.Add(b);
}
}
}
protected void b_click(object sender, EventArgs e)
{
// this is for Get data from Database on button (paging button) click
string pageNo = ((Button)sender).CommandArgument;
populateGrid(Convert.ToInt32(pageNo), 5);
}
}
}
Tuesday, 1 April 2014
Thursday, 27 March 2014
Grid View DML using tamplate Fully Customized
*****************Design************
<form id="form1" runat="server">
<div>
</div>
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server"
DataObjectTypeName="BE.BELab" DeleteMethod="Deletelab" InsertMethod="insertlab"
SelectMethod="show" TypeName="BLL.LabBLL" UpdateMethod="Updatelab">
</asp:ObjectDataSource>
<asp:GridView ID="GridView1" runat="server"
DataSourceID="ObjectDataSource1" DataKeyNames="ID" Height="190px"
ShowFooter="True" AlternatingRowStyle-BackColor="SeaGreen"
HeaderStyle-BackColor="Aqua" AutoGenerateColumns="False"
FooterStyle-BackColor="Azure">
<AlternatingRowStyle BackColor="SeaGreen"></AlternatingRowStyle>
<Columns>
<asp:TemplateField ShowHeader="False">
<EditItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True"
CommandName="Update" Text="Update"></asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False"
CommandName="Cancel" Text="Cancel"></asp:LinkButton>
</EditItemTemplate>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False"
CommandName="Edit" Text="Edit"></asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False"
CommandName="Delete" Text="Delete"></asp:LinkButton>
</ItemTemplate>
<FooterTemplate>
<asp:Button ID="btnadd" runat="server" Text="Add" OnClick="Insert_into_Grid" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ID" SortExpression="ID">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("ID") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("ID") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtID" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Assignment" SortExpression="Assignment">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("Assignment") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("Assignment") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAssignment" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="RollNo" SortExpression="RollNo">
<EditItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server"
DataSourceID="SqlDataSource1" DataTextField="StdName"
DataValueField="StdRollNo" SelectedValue='<%# Bind("RollNo") %>'>
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:DBStudentTestConnectionString %>"
SelectCommand="SELECT [StdName], [StdRollNo] FROM [tblStudent]">
</asp:SqlDataSource>
</EditItemTemplate>
<ItemTemplate>
<asp:HiddenField ID="Hd1" runat="server" Value='<%# Bind("RollNo") %>' />
<asp:DropDownList ID="DropDownList1" runat="server"
DataSourceID="SqlDataSource1" DataTextField="StdName"
DataValueField="StdRollNo" SelectedValue='<%# Bind("RollNo") %>'>
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:DBStudentTestConnectionString %>"
SelectCommand="SELECT [StdName], [StdRollNo] FROM [tblStudent]">
</asp:SqlDataSource>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="DropDownList1" runat="server"
DataSourceID="SqlDataSource1" DataTextField="StdName"
DataValueField="StdRollNo" SelectedValue='<%# Bind("RollNo") %>'>
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:DBStudentTestConnectionString %>"
SelectCommand="SELECT [StdName], [StdRollNo] FROM [tblStudent]">
</asp:SqlDataSource>
</FooterTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="Azure"></FooterStyle>
<HeaderStyle BackColor="Aqua"></HeaderStyle>
</asp:GridView>
<div>
</div>
</form>
**************************back coding************
protected void Insert_into_Grid(object sender, EventArgs e)
{
Control control = null;
if (GridView1.FooterRow != null)
{
control = GridView1.FooterRow;
}
else
{
control = GridView1.Controls[0].Controls[0];
}
Int32 ID = Convert.ToInt32((control.FindControl("txtID") as TextBox).Text);
string txtAssignment = (control.FindControl("txtAssignment") as TextBox).Text;
string Rollno = (control.FindControl("DropDownList1") as DropDownList).SelectedValue;
BELab be = new BELab();
be.ID = ID;
be.RollNo = Rollno;
be.Assignment = txtAssignment;
new LabBLL().insertlab(be);
GridView1.DataBind();
}
<form id="form1" runat="server">
<div>
</div>
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server"
DataObjectTypeName="BE.BELab" DeleteMethod="Deletelab" InsertMethod="insertlab"
SelectMethod="show" TypeName="BLL.LabBLL" UpdateMethod="Updatelab">
</asp:ObjectDataSource>
<asp:GridView ID="GridView1" runat="server"
DataSourceID="ObjectDataSource1" DataKeyNames="ID" Height="190px"
ShowFooter="True" AlternatingRowStyle-BackColor="SeaGreen"
HeaderStyle-BackColor="Aqua" AutoGenerateColumns="False"
FooterStyle-BackColor="Azure">
<AlternatingRowStyle BackColor="SeaGreen"></AlternatingRowStyle>
<Columns>
<asp:TemplateField ShowHeader="False">
<EditItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True"
CommandName="Update" Text="Update"></asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False"
CommandName="Cancel" Text="Cancel"></asp:LinkButton>
</EditItemTemplate>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False"
CommandName="Edit" Text="Edit"></asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False"
CommandName="Delete" Text="Delete"></asp:LinkButton>
</ItemTemplate>
<FooterTemplate>
<asp:Button ID="btnadd" runat="server" Text="Add" OnClick="Insert_into_Grid" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ID" SortExpression="ID">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("ID") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("ID") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtID" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Assignment" SortExpression="Assignment">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("Assignment") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("Assignment") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAssignment" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="RollNo" SortExpression="RollNo">
<EditItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server"
DataSourceID="SqlDataSource1" DataTextField="StdName"
DataValueField="StdRollNo" SelectedValue='<%# Bind("RollNo") %>'>
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:DBStudentTestConnectionString %>"
SelectCommand="SELECT [StdName], [StdRollNo] FROM [tblStudent]">
</asp:SqlDataSource>
</EditItemTemplate>
<ItemTemplate>
<asp:HiddenField ID="Hd1" runat="server" Value='<%# Bind("RollNo") %>' />
<asp:DropDownList ID="DropDownList1" runat="server"
DataSourceID="SqlDataSource1" DataTextField="StdName"
DataValueField="StdRollNo" SelectedValue='<%# Bind("RollNo") %>'>
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:DBStudentTestConnectionString %>"
SelectCommand="SELECT [StdName], [StdRollNo] FROM [tblStudent]">
</asp:SqlDataSource>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="DropDownList1" runat="server"
DataSourceID="SqlDataSource1" DataTextField="StdName"
DataValueField="StdRollNo" SelectedValue='<%# Bind("RollNo") %>'>
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:DBStudentTestConnectionString %>"
SelectCommand="SELECT [StdName], [StdRollNo] FROM [tblStudent]">
</asp:SqlDataSource>
</FooterTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="Azure"></FooterStyle>
<HeaderStyle BackColor="Aqua"></HeaderStyle>
</asp:GridView>
<div>
</div>
</form>
**************************back coding************
protected void Insert_into_Grid(object sender, EventArgs e)
{
Control control = null;
if (GridView1.FooterRow != null)
{
control = GridView1.FooterRow;
}
else
{
control = GridView1.Controls[0].Controls[0];
}
Int32 ID = Convert.ToInt32((control.FindControl("txtID") as TextBox).Text);
string txtAssignment = (control.FindControl("txtAssignment") as TextBox).Text;
string Rollno = (control.FindControl("DropDownList1") as DropDownList).SelectedValue;
BELab be = new BELab();
be.ID = ID;
be.RollNo = Rollno;
be.Assignment = txtAssignment;
new LabBLL().insertlab(be);
GridView1.DataBind();
}
Tuesday, 25 March 2014
How to add edit delete update records in Grid view ASP.NET
by: Saravanan Arumugam
Date: 21/04/2013
16916
Hide demo
|
In
this article I’m going to explain how to insert delete edit and update records
in ASP.NET GridView using C#.
If we want to insert delete edit and
update records in gridview we should use following gridview events,
1.
onrowcommand
2.
onrowdeleting
3. onrowupdating
4.
onrowcancelingedit
5. onrowediting
Also we should use following template field in
GridView.
1.ItemTemplate :
ItemTemplate is used to
display records in grid view
2.EditItemTemplate
EditItemTemplate is used to
Edit/Update records in grid view
3.FooterTemplate
FooterTemplate is used to
insert new records in grid view
Table Design:
Column Name
|
Data Type
|
empid
|
varchar(50)
|
name
|
varchar(100)
|
designation
|
varchar(50)
|
city
|
varchar(50)
|
country
|
varchar(50)
|
Create table script:
CREATE TABLE
[dbo].[EmployeeDetails](
[empid] [varchar](50)
NULL,
[name]
[varchar](100) NULL,
[designation] [varchar](100) NULL,
[city]
[varchar](50) NULL,
[country] [varchar](50)
NULL
) ON [PRIMARY]
Designer
Source Code:
<html
xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<br />
<br />
<table width="800px"
align="center">
<tr>
<td colspan="2" align="center"><b>Employee
Details</b></td>
</tr>
<tr>
<td colspan="2">
<asp:GridView ID="gvEmployeeDetails"
runat="server"
Width="100%"
AutoGenerateColumns="false"
ShowFooter="true"
onrowcommand="gvEmployeeDetails_RowCommand"
onrowdeleting="gvEmployeeDetails_RowDeleting"
onrowupdating="gvEmployeeDetails_RowUpdating"
onrowcancelingedit="gvEmployeeDetails_RowCancelingEdit"
onrowediting="gvEmployeeDetails_RowEditing">
<Columns>
<asp:TemplateField HeaderText="Employee
ID">
<ItemTemplate>
<asp:Label ID="lblEmpID"
runat="server"
Text='<%#DataBinder.Eval(Container.DataItem,
"empid") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblEditEmpID"
runat="server"
Text='<%#DataBinder.Eval(Container.DataItem,
"empid") %>'></asp:Label>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddEmpID"
runat="server"
></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lblName"
runat="server"
Text='<%#DataBinder.Eval(Container.DataItem,
"name") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEditName"
runat="server"
Text='<%#DataBinder.Eval(Container.DataItem,
"name") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddName"
runat="server"
></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Designation">
<ItemTemplate>
<asp:Label ID="lblDesignation"
runat="server"
Text='<%#DataBinder.Eval(Container.DataItem,
"designation") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEditDesignation"
runat="server"
Text='<%#DataBinder.Eval(Container.DataItem,
"designation") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddDesignation"
runat="server"
></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="City">
<ItemTemplate>
<asp:Label ID="lblCity"
runat="server"
Text='<%#DataBinder.Eval(Container.DataItem,
"city") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEditCity"
runat="server"
Text='<%#DataBinder.Eval(Container.DataItem,
"city") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddCity"
runat="server"
></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Country">
<ItemTemplate>
<asp:Label ID="lblCountry"
runat="server"
Text='<%#DataBinder.Eval(Container.DataItem,
"country") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEditCountry"
runat="server"
Text='<%#DataBinder.Eval(Container.DataItem,
"country") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddCountry"
runat="server"
></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:ImageButton ID="imgbtnEdit"
runat="server"
CommandName="Edit"
ImageUrl="~/Images/icon-edit.png"
Height="32px"
Width="32px"/>
<asp:ImageButton ID="imgbtnDelete"
runat="server"
CommandName="Delete"
ImageUrl="~/Images/Delete.png"/>
</ItemTemplate>
<EditItemTemplate>
<asp:ImageButton ID="imgbtnUpdate"
runat="server"
CommandName="Update"
ImageUrl="~/Images/icon-update.png"/>
<asp:ImageButton ID="imgbtnCancel"
runat="server"
CommandName="Cancel"
ImageUrl="~/Images/icon-Cancel.png"/>
</EditItemTemplate>
<FooterTemplate>
<asp:LinkButton ID="lbtnAdd"
runat="server"
CommandName="ADD"
Text="Add"
Width="100px"></asp:LinkButton>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
Code
Behind:
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Web;
using
System.Web.UI;
using
System.Web.UI.WebControls;
using
System.Xml;
using
System.Data;
using
System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
SqlConnection conn = new SqlConnection("Data Source=SPIDER;Initial Catalog=Demo;Integrated
Security=True");
protected void
Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
protected void
BindData()
{
DataSet ds = new
DataSet();
DataTable FromTable = new DataTable();
conn.Open();
string cmdstr = "Select
* from EmployeeDetails";
SqlCommand cmd = new
SqlCommand(cmdstr, conn);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(ds);
cmd.ExecuteNonQuery();
FromTable = ds.Tables[0];
if (FromTable.Rows.Count > 0)
{
gvEmployeeDetails.DataSource = FromTable;
gvEmployeeDetails.DataBind();
}
else
{
FromTable.Rows.Add(FromTable.NewRow());
gvEmployeeDetails.DataSource = FromTable;
gvEmployeeDetails.DataBind();
int TotalColumns =
gvEmployeeDetails.Rows[0].Cells.Count;
gvEmployeeDetails.Rows[0].Cells.Clear();
gvEmployeeDetails.Rows[0].Cells.Add(new TableCell());
gvEmployeeDetails.Rows[0].Cells[0].ColumnSpan = TotalColumns;
gvEmployeeDetails.Rows[0].Cells[0].Text = "No
records Found";
}
ds.Dispose();
conn.Close();
}
protected void
gvEmployeeDetails_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
Label lblEmpID = (Label)gvEmployeeDetails.Rows[e.RowIndex].FindControl("lblEmpID");
conn.Open();
string cmdstr = "delete
from EmployeeDetails where empid=@empid";
SqlCommand cmd = new
SqlCommand(cmdstr, conn);
cmd.Parameters.AddWithValue("@empid",
lblEmpID.Text);
cmd.ExecuteNonQuery();
conn.Close();
BindData();
}
protected void
gvEmployeeDetails_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("ADD"))
{
TextBox txtAddEmpID = (TextBox)gvEmployeeDetails.FooterRow.FindControl("txtAddEmpID");
TextBox txtAddName =
(TextBox)gvEmployeeDetails.FooterRow.FindControl("txtAddName");
TextBox txtAddDesignation = (TextBox)gvEmployeeDetails.FooterRow.FindControl("txtAddDesignation");
TextBox txtAddCity = (TextBox)gvEmployeeDetails.FooterRow.FindControl("txtAddCity");
TextBox txtAddCountry = (TextBox)gvEmployeeDetails.FooterRow.FindControl("txtAddCountry");
conn.Open();
string cmdstr = "insert
into EmployeeDetails(empid,name,designation,city,country)
values(@empid,@name,@designation,@city,@country)";
SqlCommand cmd = new
SqlCommand(cmdstr, conn);
cmd.Parameters.AddWithValue("@empid",
txtAddEmpID.Text);
cmd.Parameters.AddWithValue("@name",
txtAddName.Text);
cmd.Parameters.AddWithValue("@designation",
txtAddDesignation.Text);
cmd.Parameters.AddWithValue("@city",
txtAddCity.Text);
cmd.Parameters.AddWithValue("@country",
txtAddCountry.Text);
cmd.ExecuteNonQuery();
conn.Close();
BindData();
}
}
protected void
gvEmployeeDetails_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
Label lblEditEmpID = (Label)gvEmployeeDetails.Rows[e.RowIndex].FindControl("lblEditEmpID");
TextBox txtEditName = (TextBox)gvEmployeeDetails.Rows[e.RowIndex].FindControl("txtEditName");
TextBox txtEditDesignation = (TextBox)gvEmployeeDetails.Rows[e.RowIndex].FindControl("txtEditDesignation");
TextBox txtEditCity = (TextBox)gvEmployeeDetails.Rows[e.RowIndex].FindControl("txtEditCity");
TextBox txtEditCountry = (TextBox)gvEmployeeDetails.Rows[e.RowIndex].FindControl("txtEditCountry");
conn.Open();
string cmdstr = "update
EmployeeDetails set
name=@name,designation=@designation,city=@city,country=@country where
empid=@empid";
SqlCommand cmd = new
SqlCommand(cmdstr, conn);
cmd.Parameters.AddWithValue("@empid",
lblEditEmpID.Text);
cmd.Parameters.AddWithValue("@name",
txtEditName.Text);
cmd.Parameters.AddWithValue("@designation",
txtEditDesignation.Text);
cmd.Parameters.AddWithValue("@city",
txtEditCity.Text);
cmd.Parameters.AddWithValue("@country",
txtEditCountry.Text);
cmd.ExecuteNonQuery();
conn.Close();
gvEmployeeDetails.EditIndex = -1;
BindData();
}
protected void
gvEmployeeDetails_RowCancelingEdit(object
sender, GridViewCancelEditEventArgs e)
{
gvEmployeeDetails.EditIndex = -1;
BindData();
}
protected void
gvEmployeeDetails_RowEditing(object sender, GridViewEditEventArgs e)
{
gvEmployeeDetails.EditIndex = e.NewEditIndex;
BindData();
}
}
- See more at:
http://www.dotnetfox.com/articles/how-to-add-edit-delete-update-records-in-grid-view-Asp-Net-1003.aspx#sthash.ZxuZWlOl.dpuf
by:
Saravanan Arumugam
Date:
21/04/2013
Page views:
16916
Hide demo | Download |
In this article I’m going to explain how to insert
delete edit and update records in ASP.NET GridView using C#.
If we want to insert delete edit and update records in gridview we
should use following gridview events,
1.
onrowcommand
2.
onrowdeleting
3.
onrowupdating
4.
onrowcancelingedit
5. onrowediting
Also we should use following
template field in GridView.
1.ItemTemplate :
ItemTemplate is used
to display records in grid view
2.EditItemTemplate
EditItemTemplate is used to
Edit/Update records in grid view
3.FooterTemplate
FooterTemplate is used
to insert new records in grid view
Table Design:
Column Name
|
Data Type
|
empid
|
varchar(50)
|
name
|
varchar(100)
|
designation
|
varchar(50)
|
city
|
varchar(50)
|
country
|
varchar(50)
|
Create table script:
CREATE TABLE [dbo].[EmployeeDetails](
[empid]
[varchar](50) NULL,
[name]
[varchar](100) NULL,
[designation]
[varchar](100) NULL,
[city]
[varchar](50) NULL,
[country]
[varchar](50) NULL
) ON [PRIMARY]
Designer
Source Code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<br />
<br />
<table width="800px" align="center">
<tr>
<td colspan="2" align="center"><b>Employee Details</b></td>
</tr>
<tr>
<td colspan="2">
<asp:GridView ID="gvEmployeeDetails" runat="server"
Width="100%"
AutoGenerateColumns="false" ShowFooter="true"
onrowcommand="gvEmployeeDetails_RowCommand"
onrowdeleting="gvEmployeeDetails_RowDeleting"
onrowupdating="gvEmployeeDetails_RowUpdating"
onrowcancelingedit="gvEmployeeDetails_RowCancelingEdit"
onrowediting="gvEmployeeDetails_RowEditing">
<Columns>
<asp:TemplateField HeaderText="Employee ID">
<ItemTemplate>
<asp:Label ID="lblEmpID"
runat="server"
Text='<%#DataBinder.Eval(Container.DataItem,
"empid") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblEditEmpID"
runat="server"
Text='<%#DataBinder.Eval(Container.DataItem,
"empid") %>'></asp:Label>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddEmpID"
runat="server"
></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lblName"
runat="server"
Text='<%#DataBinder.Eval(Container.DataItem,
"name") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEditName"
runat="server"
Text='<%#DataBinder.Eval(Container.DataItem,
"name") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddName"
runat="server"
></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Designation">
<ItemTemplate>
<asp:Label ID="lblDesignation"
runat="server"
Text='<%#DataBinder.Eval(Container.DataItem,
"designation") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEditDesignation"
runat="server"
Text='<%#DataBinder.Eval(Container.DataItem,
"designation") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddDesignation"
runat="server"
></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="City">
<ItemTemplate>
<asp:Label ID="lblCity"
runat="server"
Text='<%#DataBinder.Eval(Container.DataItem,
"city") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEditCity"
runat="server"
Text='<%#DataBinder.Eval(Container.DataItem,
"city") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddCity"
runat="server"
></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Country">
<ItemTemplate>
<asp:Label ID="lblCountry"
runat="server"
Text='<%#DataBinder.Eval(Container.DataItem,
"country") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEditCountry"
runat="server"
Text='<%#DataBinder.Eval(Container.DataItem,
"country") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddCountry"
runat="server"
></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:ImageButton ID="imgbtnEdit"
runat="server"
CommandName="Edit"
ImageUrl="~/Images/icon-edit.png"
Height="32px"
Width="32px"/>
<asp:ImageButton ID="imgbtnDelete" runat="server" CommandName="Delete" ImageUrl="~/Images/Delete.png"/>
</ItemTemplate>
<EditItemTemplate>
<asp:ImageButton ID="imgbtnUpdate"
runat="server"
CommandName="Update"
ImageUrl="~/Images/icon-update.png"/>
<asp:ImageButton ID="imgbtnCancel"
runat="server"
CommandName="Cancel"
ImageUrl="~/Images/icon-Cancel.png"/>
</EditItemTemplate>
<FooterTemplate>
<asp:LinkButton ID="lbtnAdd"
runat="server"
CommandName="ADD"
Text="Add"
Width="100px"></asp:LinkButton>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
Code
Behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.Data;
using System.Data.SqlClient;
public partial class _Default :
System.Web.UI.Page
{
SqlConnection
conn = new SqlConnection("Data Source=SPIDER;Initial Catalog=Demo;Integrated
Security=True");
protected void Page_Load(object
sender, EventArgs e)
{
if
(!IsPostBack)
{
BindData();
}
}
protected void BindData()
{
DataSet
ds = new DataSet();
DataTable
FromTable = new DataTable();
conn.Open();
string
cmdstr = "Select * from EmployeeDetails";
SqlCommand
cmd = new SqlCommand(cmdstr,
conn);
SqlDataAdapter
adp = new SqlDataAdapter(cmd);
adp.Fill(ds);
cmd.ExecuteNonQuery();
FromTable = ds.Tables[0];
if
(FromTable.Rows.Count > 0)
{
gvEmployeeDetails.DataSource =
FromTable;
gvEmployeeDetails.DataBind();
}
else
{
FromTable.Rows.Add(FromTable.NewRow());
gvEmployeeDetails.DataSource =
FromTable;
gvEmployeeDetails.DataBind();
int
TotalColumns = gvEmployeeDetails.Rows[0].Cells.Count;
gvEmployeeDetails.Rows[0].Cells.Clear();
gvEmployeeDetails.Rows[0].Cells.Add(new TableCell());
gvEmployeeDetails.Rows[0].Cells[0].ColumnSpan = TotalColumns;
gvEmployeeDetails.Rows[0].Cells[0].Text = "No
records Found";
}
ds.Dispose();
conn.Close();
}
protected void gvEmployeeDetails_RowDeleting(object sender, GridViewDeleteEventArgs
e)
{
Label
lblEmpID = (Label)gvEmployeeDetails.Rows[e.RowIndex].FindControl("lblEmpID");
conn.Open();
string
cmdstr = "delete from EmployeeDetails where
empid=@empid";
SqlCommand
cmd = new SqlCommand(cmdstr,
conn);
cmd.Parameters.AddWithValue("@empid", lblEmpID.Text);
cmd.ExecuteNonQuery();
conn.Close();
BindData();
}
protected void gvEmployeeDetails_RowCommand(object sender, GridViewCommandEventArgs
e)
{
if
(e.CommandName.Equals("ADD"))
{
TextBox
txtAddEmpID = (TextBox)gvEmployeeDetails.FooterRow.FindControl("txtAddEmpID");
TextBox
txtAddName = (TextBox)gvEmployeeDetails.FooterRow.FindControl("txtAddName");
TextBox
txtAddDesignation = (TextBox)gvEmployeeDetails.FooterRow.FindControl("txtAddDesignation");
TextBox
txtAddCity = (TextBox)gvEmployeeDetails.FooterRow.FindControl("txtAddCity");
TextBox
txtAddCountry = (TextBox)gvEmployeeDetails.FooterRow.FindControl("txtAddCountry");
conn.Open();
string
cmdstr = "insert into
EmployeeDetails(empid,name,designation,city,country)
values(@empid,@name,@designation,@city,@country)";
SqlCommand
cmd = new SqlCommand(cmdstr,
conn);
cmd.Parameters.AddWithValue("@empid", txtAddEmpID.Text);
cmd.Parameters.AddWithValue("@name", txtAddName.Text);
cmd.Parameters.AddWithValue("@designation", txtAddDesignation.Text);
cmd.Parameters.AddWithValue("@city", txtAddCity.Text);
cmd.Parameters.AddWithValue("@country", txtAddCountry.Text);
cmd.ExecuteNonQuery();
conn.Close();
BindData();
}
}
protected void gvEmployeeDetails_RowUpdating(object sender, GridViewUpdateEventArgs
e)
{
Label
lblEditEmpID = (Label)gvEmployeeDetails.Rows[e.RowIndex].FindControl("lblEditEmpID");
TextBox
txtEditName = (TextBox)gvEmployeeDetails.Rows[e.RowIndex].FindControl("txtEditName");
TextBox
txtEditDesignation = (TextBox)gvEmployeeDetails.Rows[e.RowIndex].FindControl("txtEditDesignation");
TextBox
txtEditCity = (TextBox)gvEmployeeDetails.Rows[e.RowIndex].FindControl("txtEditCity");
TextBox
txtEditCountry = (TextBox)gvEmployeeDetails.Rows[e.RowIndex].FindControl("txtEditCountry");
conn.Open();
string
cmdstr = "update EmployeeDetails set
name=@name,designation=@designation,city=@city,country=@country where
empid=@empid";
SqlCommand
cmd = new SqlCommand(cmdstr,
conn);
cmd.Parameters.AddWithValue("@empid", lblEditEmpID.Text);
cmd.Parameters.AddWithValue("@name", txtEditName.Text);
cmd.Parameters.AddWithValue("@designation",
txtEditDesignation.Text);
cmd.Parameters.AddWithValue("@city", txtEditCity.Text);
cmd.Parameters.AddWithValue("@country", txtEditCountry.Text);
cmd.ExecuteNonQuery();
conn.Close();
gvEmployeeDetails.EditIndex = -1;
BindData();
}
protected void gvEmployeeDetails_RowCancelingEdit(object sender, GridViewCancelEditEventArgs
e)
{
gvEmployeeDetails.EditIndex = -1;
BindData();
}
protected void gvEmployeeDetails_RowEditing(object sender, GridViewEditEventArgs
e)
{
gvEmployeeDetails.EditIndex =
e.NewEditIndex;
BindData();
}
}
Subscribe to:
Posts (Atom)