Grid-view-Example.aspx : Code
---------------------------------
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridviewEx.aspx.cs" Inherits="GridviewEx" %>
<!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>Complete Grid Operation</title>
<script type="text/javascript" >
function Check_UnCheck(Val)
{
var ValChecked = Val.checked;
var ValId =Val.id;
var frm = document.forms[0];
// Loop through all elements
for (i=0; i<frm.length; i++)
{
// Look for Header Template's Checkbox
if (this!=null)
{ if (ValId.indexOf ('CheckAll') != -1)
{
// Check if main checkbox is checked, then select or deselect datagrid checkboxes
if(ValChecked) frm.elements[i].checked = true;
else frm.elements[i].checked = false;
}
else if (ValId.indexOf ('deleteRec') != -1)
{
// Check if any of the checkboxes are not checked, and then uncheck top select all checkbox
if(frm.elements[i].checked == false) document.getElementById('GridView1_ctl01_CheckAll').checked=false; /*frm.elements[1].checked = false;*/ }
} // if
} // for
}// function
function ConfirmMessage(frm)
{
// loop through all elements
for (i=0; i<frm.length; i++)
{
// Look for our checkboxes only
if (frm.elements[i].name.indexOf("deleteRec") !=-1)
{
// If any are checked then confirm alert, otherwise nothing happens
if(frm.elements[i].checked) return confirm ('Are you sure you want to delete your selection(s)?')
}
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ID, Type"
OnRowCancelingEdit="GridView1_RowCancelingEdit"
OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" OnRowCommand="GridView1_RowCommand"
ShowFooter="True" OnRowDeleting="GridView1_RowDeleting" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="CheckAll" onclick="return Check_UnCheck (this );" runat="server" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="deleteRec" onclick="return Check_UnCheck (this );" runat="server" />
<asp:TextBox ID="txtCID" runat="server" Text='<%# Eval("ID")%>' Visible="False"
Width="0px"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name" SortExpression="Name">
<EditItemTemplate>
<asp:TextBox ID="txtName" runat="server" Text='<%# Eval("Name") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtNewName" runat="server"></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("Name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Gender">
<EditItemTemplate>
<asp:DropDownList ID="cmbGender" runat="server" SelectedValue='<%# Eval("Gender") %>'>
<asp:ListItem Value="Male" Text="Male"></asp:ListItem>
<asp:ListItem Value="Female" Text="Female"></asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="LblGender" runat="server" Text='<%# Eval("Gender") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="cmbNewGender" runat="server">
<asp:ListItem Selected="True" Text="Male" Value="Male"></asp:ListItem>
<asp:ListItem Text="Female" Value="Female"></asp:ListItem>
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="City">
<EditItemTemplate>
<asp:TextBox ID="txtCity" runat="server" Text='<%# Bind("City") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtNewCity" runat="server"></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("City") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="State" SortExpression="State">
<EditItemTemplate>
<asp:Label ID="lblState" runat="server" Text='<%# Bind("State") %>'></asp:Label>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtNewState" runat="server"></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# Bind("State") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Type">
<EditItemTemplate>
<asp:DropDownList ID="cmbType" runat="server" DataTextField="Type" DataValueField="ID">
<asp:ListItem Value="Developer" Text="Developer"></asp:ListItem>
<asp:ListItem Value="Tester" Text="Tester"></asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label5" runat="server" Text='<%# Eval("Type") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="cmbNewType" runat="server" DataTextField="Type" DataValueField="Type">
<asp:ListItem Value="Developer" Text="Developer"></asp:ListItem>
<asp:ListItem Value="Tester" Text="Tester"></asp:ListItem>
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit" 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>
<FooterTemplate>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="AddNew"
Text="Add New"></asp:LinkButton>
</FooterTemplate>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Edit"
Text="Edit"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField HeaderText="Delete" ShowDeleteButton="True" ShowHeader="True" />
</Columns>
</asp:GridView>
<asp:Button ID="btnDelete" runat="server" OnClientClick="return ConfirmMessage(this.form)"
Text="Delete Selected" OnClick="btnDelete_Click" />
</div>
</form>
</body>
</html>
Grid-view-Example.aspx.cs : Code
------------------------------------
using System;
using System.Data;
using System.Data.OleDb;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class GridviewEx : System.Web.UI.Page
{
CustomersCls customer = new CustomersCls();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FillCustomerInGrid();
}
}
// This procedure will call when grid will be bind
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList cmbType = (DropDownList)e.Row.FindControl("cmbType");
if (cmbType != null)
{
cmbType.DataSource = customer.FetchCustomerType();
cmbType.DataBind();
cmbType.SelectedValue = GridView1.DataKeys[e.Row.RowIndex].Values[1].ToString();
}
}
if (e.Row.RowType == DataControlRowType.Footer)
{
DropDownList cmbNewType = (DropDownList)e.Row.FindControl("cmbNewType");
cmbNewType.DataSource = customer.FetchCustomerType();
cmbNewType.DataBind();
}
}
// This procedure will call when any command will be fire when user will click to addnew button this
// event will be execute.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("AddNew"))
{
TextBox txtNewName = (TextBox)GridView1.FooterRow.FindControl("txtNewName");
DropDownList cmbNewGender = (DropDownList)GridView1.FooterRow.FindControl("cmbNewGender");
TextBox txtNewCity = (TextBox)GridView1.FooterRow.FindControl("txtNewCity");
TextBox txtNewState = (TextBox)GridView1.FooterRow.FindControl("txtNewState");
DropDownList cmbNewType = (DropDownList)GridView1.FooterRow.FindControl("cmbNewType");
customer.Insert(txtNewName.Text, cmbNewGender.SelectedValue, txtNewCity.Text, txtNewState.Text, cmbNewType.SelectedValue);
FillCustomerInGrid();
}
}
// This procedure will call when user will click to edit button
// it will open that row in update mode
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
FillCustomerInGrid();
}
// This procedure will call when user will click to Cancel button
// it will again bind the data in add new mode
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
FillCustomerInGrid();
}
// This Procedure will call when any user click to update any existing records
// it will update the records
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
TextBox txtName = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtName");
DropDownList cmbGender = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("cmbGender");
TextBox txtCity = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtCity");
DropDownList cmbType = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("cmbType");
customer.Update(Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]), txtName.Text, cmbGender.SelectedValue, txtCity.Text, cmbType.SelectedValue);
GridView1.EditIndex = -1;
FillCustomerInGrid();
}
// This procedure will call when any user will click to Delete Button.
// it will delete the records
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
customer.Delete(Convert.ToInt32( GridView1.DataKeys[e.RowIndex].Values[0]));
FillCustomerInGrid();
}
// This procedure will bind the grid it will fetch the records from Fetch function wich is in
// Customer class
private void FillCustomerInGrid()
{
DataTable dtCustomer = customer.Fetch();
if (dtCustomer.Rows.Count > 0)
{
GridView1.DataSource = dtCustomer;
GridView1.DataBind();
}
else
{
dtCustomer.Rows.Add(dtCustomer.NewRow());
GridView1.DataSource = dtCustomer;
GridView1.DataBind();
int TotalColumns = GridView1.Rows[0].Cells.Count;
GridView1.Rows[0].Cells.Clear();
GridView1.Rows[0].Cells.Add(new TableCell());
GridView1.Rows[0].Cells[0].ColumnSpan = TotalColumns;
GridView1.Rows[0].Cells[0].Text = "No Record Found";
}
}
// This procedure will call when user will select any checkbox and click to Delete button it will be
// fire and it will delete selected records
protected void btnDelete_Click(object sender, EventArgs e)
{
string gvIDs = "";
bool chkBox = false;
foreach (GridViewRow gv in GridView1.Rows)
{
CheckBox deleteChkBxItem = (CheckBox)gv.FindControl("deleteRec");
if (deleteChkBxItem.Checked)
{
chkBox = true;
// Concatenate GridView items with comma for SQL Delete
gvIDs += ((TextBox)gv.FindControl("txtCID")).Text.ToString() + ",";
}
}
OleDbConnection cn = new OleDbConnection(ConfigurationManager.ConnectionStrings["AccessConnection"].ConnectionString);
if (chkBox)
{
// Execute SQL Query only if checkboxes are checked to avoid any error with initial null string
try
{
string deleteSQL = "DELETE from CustomerTable WHERE ID IN (" + gvIDs.Substring(0, gvIDs.LastIndexOf(",")) + ")";
OleDbCommand cmd = new OleDbCommand(deleteSQL, cn);
cn.Open();
cmd.ExecuteNonQuery();
OleDbDataAdapter da = new OleDbDataAdapter("Select * From CustomerTable;", cn);
DataSet dset = new DataSet();
da.Fill(dset);
GridView1.DataSource = dset;
GridView1.DataBind();
}
catch (OleDbException err)
{
Response.Write(err.Message.ToString());
}
finally
{
cn.Close();
cn.Dispose();
}
}
}
}
CustomerCLs. Cs : Code
-----------------------------
using System;
using System.Data;
using System.Data.OleDb;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
///
/// Summary description for CustomersCls
///
public class CustomersCls
{
public CustomersCls()
{
//
// TODO: Add constructor logic here
//
}
OleDbConnection con = new OleDbConnection(ConfigurationManager.ConnectionStrings["AccessConnection"].ConnectionString);
DataSet ds = new DataSet();
string strQry = "";
public void Insert(string CustomerName, string Gender, string City, string State, string CustomerType)
{
// Write your own Insert statement blocks
strQry = "Insert into CustomerTable (Name, Gender, City, State, Type) values('" + CustomerName + "', '" + Gender + "', '" + City + "', '" + State + "', '" + CustomerType + "' )";
OleDbCommand com = new OleDbCommand(strQry,con);
con.Open();
com = new OleDbCommand(strQry, con);
com.ExecuteNonQuery();
com.Dispose();
con.Close();
}
public DataTable Fetch()
{
// Write your own Fetch statement blocks, this method should return a DataTable
con.Open();
OleDbDataAdapter da = new OleDbDataAdapter("Select * From CustomerTable;", con);
da.Fill(ds);
da.Dispose();
con.Close();
return ds.Tables[0];
}
public DataTable FetchCustomerType()
{
// Write your own Fetch statement blocks to fetch Customer Type from its master table and this method should return a DataTable
con.Open();
OleDbDataAdapter da = new OleDbDataAdapter("Select ID, Type From CustomerTable;", con);
da.Fill(ds);
da.Dispose();
con.Close();
return ds.Tables[0];
}
public void Update(int CustomerCode, string CustomerName, string Gender, string City, string CustomerType)
{
// Write your own Update statement blocks.
strQry = "Update CustomerTable Set Name='" + CustomerName + "', Gender= '" + Gender + "', City= '" + City + "', type= '" + CustomerType + "' where ID="+ CustomerCode +"; ";
OleDbCommand com = new OleDbCommand(strQry, con);
con.Open();
com = new OleDbCommand(strQry, con);
com.ExecuteNonQuery();
com.Dispose();
con.Close();
}
public void Delete(int CustomerCode)
{
// Write your own Delete statement blocks.
strQry = "Delete * from CustomerTable where ID=" + CustomerCode + "; ";
OleDbCommand com = new OleDbCommand(strQry, con);
con.Open();
com = new OleDbCommand(strQry, con);
com.ExecuteNonQuery();
com.Dispose();
con.Close();
}
}
----------------------------------------------------------------------------------------------------
Regards any query please mail me
vikrant.sahoo@gmail.com
+91-9821207039
www.endya.com/vikrant
No comments:
Post a Comment