<iframe src="http://wikimapia.org/#lat=26.0439825&lon=79.6216965&z=13&l=0&ifr=1&m=b" width="366" height="150" frameborder="0"></iframe>
Monday, March 7, 2011
Monday, February 21, 2011
Insert/Update/Delete in gridview asp.net
Insert/Update/Delete in GridView using asp.net C#
Insert/Update/Delete in GridView using asp.net C#
Step1:-
Create a employee table:
CREATE TABLE EMPLOYEE
(
EMPID INT IDENTITY(100,1),
FIRSTNAME VARCHAR(20),
LASTNAME VARCHAR(20),
ADDRESS VARCHAR(100),
MOBILE VARCHAR(20)
)
NOW INSERT SOME VALUES IN EMPLOYEE TABLE:
INSERT INTO EMPLOYEE(FIRSTNAME,LASTNAME, ADDRESS,MOBILE)VALUES('SHIVAM' ,'GUPTA','NEW DELHI','8826743157')
STEP2:- CREATE CONNECTION STRING IN WEB.CONFIG FILE.
<connectionStrings>
<add name="mycon" connectionString="data source=SHIVAMGUPTA; initial catalog=operation; integrated security=true;" providerName="System.Data. SqlClient"/>
</connectionStrings>
STEP3:- TAKE A GRIDVIEW IN YOUR .ASPX PAGE.
<asp:GridView ID="GridView1" runat="server" AutoGenerateDeleteButton=" true" AutoGenerateColumns="false"
AutoGenerateEditButton="True"
onpageindexchanging=" GridView1_PageIndexChanging"
onrowcancelingedit=" GridView1_RowCancelingEdit" DataKeyNames="EmpID"
onrowdeleting="GridView1_ RowDeleting" onrowediting="GridView1_ RowEditing"
onrowupdating="GridView1_ RowUpdating">
<Columns>
<asp:BoundField DataField="EMPID" HeaderText="EmployeeID" />
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="Address" HeaderText="Address" />
<asp:BoundField DataField="Mobile" HeaderText="Mobile" />
</Columns>
</asp:GridView>
<asp:Label ID="lblMessage" runat="server"></asp:Label>
STEP4: NOW COME IN YOUR CODE BEHIND .ASPX.CS
public partial class _Default : System.Web.UI.Page
{
SqlConnection con;
protected void Page_Load(object sender, EventArgs e)
{
string conection;
conection = System.Configuration. ConfigurationManager. ConnectionStrings["mycon"]. ConnectionString.ToString();
con = new SqlConnection(conection);
if (!IsPostBack)
{
FillGrid();
}
}
protected void FillGrid()
{
SqlCommand cmd = new SqlCommand("select * from employee", Con);
con.Open();
GridView1.DataSource = cmd.ExecuteReader();
GridView1.DataBind();
con.Close();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
FillGrid();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int index = GridView1.EditIndex;
GridViewRow row = GridView1.Rows[index];
int Eid = Convert.ToInt32(GridView1. DataKeys[e.RowIndex].Value);
string FirstName = ((TextBox)row.Cells[2]. Controls[0]).Text.ToString(). Trim();
string LastName = ((TextBox)row.Cells[3]. Controls[0]).Text.ToString(). Trim();
string Address = ((TextBox)row.Cells[4]. Controls[0]).Text.ToString(). Trim();
string Mobile = ((TextBox)row.Cells[5]. Controls[0]).Text.ToString(). Trim();
string sql = "UPDATE EMPLOYEE SET FIRSTNAME='" + FirstName + "',LastName='" + LastName + "',Address='" +Address + "',Mobile='" + Mobile + "' WHERE EMPID=" + Eid + "";
SqlCommand cmd = new SqlCommand(sql, con);
con.Open();
int temp = cmd.ExecuteNonQuery();
con.Close();
if (temp == 1)
{
lblMessage.Text = "Record updated successfully";
}
GridView1.EditIndex = -1;
FillGrid();
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int Eid = Convert.ToInt32(GridView1. DataKeys[e.RowIndex].Value);
SqlCommand cmd = new SqlCommand("DELETE FROM EMPLOYEE WHERE EMPID=" + Eid + "", con);
con.Open();
int temp = cmd.ExecuteNonQuery();
if (temp == 1)
{
lblMessage.Text = "Record deleted successfully";
}
con.Close();
FillGrid();
}
protected void GridView1_PageIndexChanging( object sender, GridViewPageEventArgs e)
{
GridView1.EditIndex = e.NewPageIndex;
FillGrid();
}
protected void GridView1_RowCancelingEdit( object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
FillGrid();
}
}
Insert/Update/Delete in GridView using asp.net C#Step1:-
Create a employee table:
CREATE TABLE EMPLOYEE
(
EMPID INT IDENTITY(100,1),
FIRSTNAME VARCHAR(20),
LASTNAME VARCHAR(20),
ADDRESS VARCHAR(100),
MOBILE VARCHAR(20)
)
NOW INSERT SOME VALUES IN EMPLOYEE TABLE:
INSERT INTO EMPLOYEE(FIRSTNAME,LASTNAME,
STEP2:- CREATE CONNECTION STRING IN WEB.CONFIG FILE.
<connectionStrings>
<add name="mycon" connectionString="data source=SHIVAMGUPTA; initial catalog=operation; integrated security=true;" providerName="System.Data.
</connectionStrings>
STEP3:- TAKE A GRIDVIEW IN YOUR .ASPX PAGE.
<asp:GridView ID="GridView1" runat="server" AutoGenerateDeleteButton="
AutoGenerateEditButton="True"
onpageindexchanging="
onrowcancelingedit="
onrowdeleting="GridView1_
onrowupdating="GridView1_
<Columns>
<asp:BoundField DataField="EMPID" HeaderText="EmployeeID" />
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="Address" HeaderText="Address" />
<asp:BoundField DataField="Mobile" HeaderText="Mobile" />
</Columns>
</asp:GridView>
<asp:Label ID="lblMessage" runat="server"></asp:Label>
STEP4: NOW COME IN YOUR CODE BEHIND .ASPX.CS
public partial class _Default : System.Web.UI.Page
{
SqlConnection con;
protected void Page_Load(object sender, EventArgs e)
{
string conection;
conection = System.Configuration.
con = new SqlConnection(conection);
if (!IsPostBack)
{
FillGrid();
}
}
protected void FillGrid()
{
SqlCommand cmd = new SqlCommand("select * from employee", Con);
con.Open();
GridView1.DataSource = cmd.ExecuteReader();
GridView1.DataBind();
con.Close();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
FillGrid();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int index = GridView1.EditIndex;
GridViewRow row = GridView1.Rows[index];
int Eid = Convert.ToInt32(GridView1.
string FirstName = ((TextBox)row.Cells[2].
string LastName = ((TextBox)row.Cells[3].
string Address = ((TextBox)row.Cells[4].
string Mobile = ((TextBox)row.Cells[5].
string sql = "UPDATE EMPLOYEE SET FIRSTNAME='" + FirstName + "',LastName='" + LastName + "',Address='" +Address + "',Mobile='" + Mobile + "' WHERE EMPID=" + Eid + "";
SqlCommand cmd = new SqlCommand(sql, con);
con.Open();
int temp = cmd.ExecuteNonQuery();
con.Close();
if (temp == 1)
{
lblMessage.Text = "Record updated successfully";
}
GridView1.EditIndex = -1;
FillGrid();
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int Eid = Convert.ToInt32(GridView1.
SqlCommand cmd = new SqlCommand("DELETE FROM EMPLOYEE WHERE EMPID=" + Eid + "", con);
con.Open();
int temp = cmd.ExecuteNonQuery();
if (temp == 1)
{
lblMessage.Text = "Record deleted successfully";
}
con.Close();
FillGrid();
}
protected void GridView1_PageIndexChanging(
{
GridView1.EditIndex = e.NewPageIndex;
FillGrid();
}
protected void GridView1_RowCancelingEdit(
{
GridView1.EditIndex = -1;
FillGrid();
}
}
Insert/Update/Delete in GridView using asp.net C#
Step1:-
Create a employee table:
CREATE TABLE EMPLOYEE
(
EMPID INT IDENTITY(100,1),
FIRSTNAME VARCHAR(20),
LASTNAME VARCHAR(20),
ADDRESS VARCHAR(100),
MOBILE VARCHAR(20)
)
NOW INSERT SOME VALUES IN EMPLOYEE TABLE:
INSERT INTO EMPLOYEE(FIRSTNAME,LASTNAME, ADDRESS,MOBILE)VALUES('SHIVAM' ,'GUPTA','NEW DELHI','8826743157')
STEP2:- CREATE CONNECTION STRING IN WEB.CONFIG FILE.
<connectionStrings>
<add name="mycon" connectionString="data source=SHIVAMGUPTA; initial catalog=operation; integrated security=true;" providerName="System.Data. SqlClient"/>
</connectionStrings>
STEP3:- TAKE A GRIDVIEW IN YOUR .ASPX PAGE.
<asp:GridView ID="GridView1" runat="server" AutoGenerateDeleteButton=" true" AutoGenerateColumns="false"
AutoGenerateEditButton="True"
onpageindexchanging=" GridView1_PageIndexChanging"
onrowcancelingedit=" GridView1_RowCancelingEdit" DataKeyNames="EmpID"
onrowdeleting="GridView1_ RowDeleting" onrowediting="GridView1_ RowEditing"
onrowupdating="GridView1_ RowUpdating">
<Columns>
<asp:BoundField DataField="EMPID" HeaderText="EmployeeID" />
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="Address" HeaderText="Address" />
<asp:BoundField DataField="Mobile" HeaderText="Mobile" />
</Columns>
</asp:GridView>
<asp:Label ID="lblMessage" runat="server"></asp:Label>
STEP4: NOW COME IN YOUR CODE BEHIND .ASPX.CS
public partial class _Default : System.Web.UI.Page
{
SqlConnection con;
protected void Page_Load(object sender, EventArgs e)
{
string conection;
conection = System.Configuration. ConfigurationManager. ConnectionStrings["mycon"]. ConnectionString.ToString();
con = new SqlConnection(conection);
if (!IsPostBack)
{
FillGrid();
}
}
protected void FillGrid()
{
SqlCommand cmd = new SqlCommand("select * from employee", Con);
con.Open();
GridView1.DataSource = cmd.ExecuteReader();
GridView1.DataBind();
con.Close();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
FillGrid();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int index = GridView1.EditIndex;
GridViewRow row = GridView1.Rows[index];
int Eid = Convert.ToInt32(GridView1. DataKeys[e.RowIndex].Value);
string FirstName = ((TextBox)row.Cells[2]. Controls[0]).Text.ToString(). Trim();
string LastName = ((TextBox)row.Cells[3]. Controls[0]).Text.ToString(). Trim();
string Address = ((TextBox)row.Cells[4]. Controls[0]).Text.ToString(). Trim();
string Mobile = ((TextBox)row.Cells[5]. Controls[0]).Text.ToString(). Trim();
string sql = "UPDATE EMPLOYEE SET FIRSTNAME='" + FirstName + "',LastName='" + LastName + "',Address='" +Address + "',Mobile='" + Mobile + "' WHERE EMPID=" + Eid + "";
SqlCommand cmd = new SqlCommand(sql, con);
con.Open();
int temp = cmd.ExecuteNonQuery();
con.Close();
if (temp == 1)
{
lblMessage.Text = "Record updated successfully";
}
GridView1.EditIndex = -1;
FillGrid();
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int Eid = Convert.ToInt32(GridView1. DataKeys[e.RowIndex].Value);
SqlCommand cmd = new SqlCommand("DELETE FROM EMPLOYEE WHERE EMPID=" + Eid + "", con);
con.Open();
int temp = cmd.ExecuteNonQuery();
if (temp == 1)
{
lblMessage.Text = "Record deleted successfully";
}
con.Close();
FillGrid();
}
protected void GridView1_PageIndexChanging( object sender, GridViewPageEventArgs e)
{
GridView1.EditIndex = e.NewPageIndex;
FillGrid();
}
protected void GridView1_RowCancelingEdit( object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
FillGrid();
}
}
Step1:-
Create a employee table:
CREATE TABLE EMPLOYEE
(
EMPID INT IDENTITY(100,1),
FIRSTNAME VARCHAR(20),
LASTNAME VARCHAR(20),
ADDRESS VARCHAR(100),
MOBILE VARCHAR(20)
)
NOW INSERT SOME VALUES IN EMPLOYEE TABLE:
INSERT INTO EMPLOYEE(FIRSTNAME,LASTNAME,
STEP2:- CREATE CONNECTION STRING IN WEB.CONFIG FILE.
<connectionStrings>
<add name="mycon" connectionString="data source=SHIVAMGUPTA; initial catalog=operation; integrated security=true;" providerName="System.Data.
</connectionStrings>
STEP3:- TAKE A GRIDVIEW IN YOUR .ASPX PAGE.
<asp:GridView ID="GridView1" runat="server" AutoGenerateDeleteButton="
AutoGenerateEditButton="True"
onpageindexchanging="
onrowcancelingedit="
onrowdeleting="GridView1_
onrowupdating="GridView1_
<Columns>
<asp:BoundField DataField="EMPID" HeaderText="EmployeeID" />
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="Address" HeaderText="Address" />
<asp:BoundField DataField="Mobile" HeaderText="Mobile" />
</Columns>
</asp:GridView>
<asp:Label ID="lblMessage" runat="server"></asp:Label>
STEP4: NOW COME IN YOUR CODE BEHIND .ASPX.CS
public partial class _Default : System.Web.UI.Page
{
SqlConnection con;
protected void Page_Load(object sender, EventArgs e)
{
string conection;
conection = System.Configuration.
con = new SqlConnection(conection);
if (!IsPostBack)
{
FillGrid();
}
}
protected void FillGrid()
{
SqlCommand cmd = new SqlCommand("select * from employee", Con);
con.Open();
GridView1.DataSource = cmd.ExecuteReader();
GridView1.DataBind();
con.Close();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
FillGrid();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int index = GridView1.EditIndex;
GridViewRow row = GridView1.Rows[index];
int Eid = Convert.ToInt32(GridView1.
string FirstName = ((TextBox)row.Cells[2].
string LastName = ((TextBox)row.Cells[3].
string Address = ((TextBox)row.Cells[4].
string Mobile = ((TextBox)row.Cells[5].
string sql = "UPDATE EMPLOYEE SET FIRSTNAME='" + FirstName + "',LastName='" + LastName + "',Address='" +Address + "',Mobile='" + Mobile + "' WHERE EMPID=" + Eid + "";
SqlCommand cmd = new SqlCommand(sql, con);
con.Open();
int temp = cmd.ExecuteNonQuery();
con.Close();
if (temp == 1)
{
lblMessage.Text = "Record updated successfully";
}
GridView1.EditIndex = -1;
FillGrid();
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int Eid = Convert.ToInt32(GridView1.
SqlCommand cmd = new SqlCommand("DELETE FROM EMPLOYEE WHERE EMPID=" + Eid + "", con);
con.Open();
int temp = cmd.ExecuteNonQuery();
if (temp == 1)
{
lblMessage.Text = "Record deleted successfully";
}
con.Close();
FillGrid();
}
protected void GridView1_PageIndexChanging(
{
GridView1.EditIndex = e.NewPageIndex;
FillGrid();
}
protected void GridView1_RowCancelingEdit(
{
GridView1.EditIndex = -1;
FillGrid();
}
}
get primary key in gridview
*********RowCommand_event of Gridview*************
Step1: Add the gridview in your .aspx page.
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
DataKeyNames="EmpID"onrowcommand="GridView1_RowCommand">
<Columns>
<asp:BoundField DataField="EMPID" HeaderText="EmployeeID" />
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="Address" HeaderText="Address" />
<asp:BoundField DataField="Mobile" HeaderText="Mobile" />
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnSelect" runat="server" Text="Select" CommandName="Select" CommandArgument='<%# Eval("Mobile") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Label ID="lblMessage" runat="server"></asp:Label>
<asp:TextBox ID="txtMobile" runat="server"></asp:TextBox>
</div>
step 2:- your .aspx.cs page.
NOTE:- this is my connection string which is using in below coding you can use your own to modify it in your web.config file.
My connectiion string is.
"
<connectionStrings>
<add name="mycon" connectionString="data source=SHIVAMGUPTA; initial catalog=operation; integrated security=true;" providerName="System.Data.SqlClient"/>
</connectionStrings>
"
**********************your code behind part.*********************
public partial class SelectGridColumn : System.Web.UI.Page
{
SqlConnection con;
protected void Page_Load(object sender, EventArgs e)
{
string conection;
conection = System.Configuration.ConfigurationManager.ConnectionStrings["mycon"].ConnectionString.ToString();
con = new SqlConnection(conection);
if (!IsPostBack)
{
FillGrid();
}
}
protected void FillGrid()
{
SqlCommand cmd = new SqlCommand("select * from employee", con);
con.Open();
GridView1.DataSource = cmd.ExecuteReader();
GridView1.DataBind();
con.Close();
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
txtMobile.Text = Convert.ToString(e.CommandArgument);
lblMessage.Text = "this the mobile no of selected row!";
}
}
}
Step1: Add the gridview in your .aspx page.
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
DataKeyNames="EmpID"onrowcommand="GridView1_RowCommand">
<Columns>
<asp:BoundField DataField="EMPID" HeaderText="EmployeeID" />
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="Address" HeaderText="Address" />
<asp:BoundField DataField="Mobile" HeaderText="Mobile" />
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnSelect" runat="server" Text="Select" CommandName="Select" CommandArgument='<%# Eval("Mobile") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Label ID="lblMessage" runat="server"></asp:Label>
<asp:TextBox ID="txtMobile" runat="server"></asp:TextBox>
</div>
step 2:- your .aspx.cs page.
NOTE:- this is my connection string which is using in below coding you can use your own to modify it in your web.config file.
My connectiion string is.
"
<connectionStrings>
<add name="mycon" connectionString="data source=SHIVAMGUPTA; initial catalog=operation; integrated security=true;" providerName="System.Data.SqlClient"/>
</connectionStrings>
"
**********************your code behind part.*********************
public partial class SelectGridColumn : System.Web.UI.Page
{
SqlConnection con;
protected void Page_Load(object sender, EventArgs e)
{
string conection;
conection = System.Configuration.ConfigurationManager.ConnectionStrings["mycon"].ConnectionString.ToString();
con = new SqlConnection(conection);
if (!IsPostBack)
{
FillGrid();
}
}
protected void FillGrid()
{
SqlCommand cmd = new SqlCommand("select * from employee", con);
con.Open();
GridView1.DataSource = cmd.ExecuteReader();
GridView1.DataBind();
con.Close();
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
txtMobile.Text = Convert.ToString(e.CommandArgument);
lblMessage.Text = "this the mobile no of selected row!";
}
}
}
row command in griedview asp.net C#
*********RowCommand_event of Gridview*************
Step1: Add the gridview in your .aspx page.
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
DataKeyNames="EmpID"onrowcommand="GridView1_RowCommand">
<Columns>
<asp:BoundField DataField="EMPID" HeaderText="EmployeeID" />
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="Address" HeaderText="Address" />
<asp:BoundField DataField="Mobile" HeaderText="Mobile" />
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnSelect" runat="server" Text="Select" CommandName="Select" CommandArgument='<%# Eval("Mobile") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Label ID="lblMessage" runat="server"></asp:Label>
<asp:TextBox ID="txtMobile" runat="server"></asp:TextBox>
</div>
step 2:- your .aspx.cs page.
NOTE:- this is my connection string which is using in below coding you can use your own to modify it in your web.config file.
My connectiion string is.
"
<connectionStrings>
<add name="mycon" connectionString="data source=SHIVAMGUPTA; initial catalog=operation; integrated security=true;" providerName="System.Data.SqlClient"/>
</connectionStrings>
"
**********************your code behind part.*********************
public partial class SelectGridColumn : System.Web.UI.Page
{
SqlConnection con;
protected void Page_Load(object sender, EventArgs e)
{
string conection;
conection = System.Configuration.ConfigurationManager.ConnectionStrings["mycon"].ConnectionString.ToString();
con = new SqlConnection(conection);
if (!IsPostBack)
{
FillGrid();
}
}
protected void FillGrid()
{
SqlCommand cmd = new SqlCommand("select * from employee", con);
con.Open();
GridView1.DataSource = cmd.ExecuteReader();
GridView1.DataBind();
con.Close();
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
txtMobile.Text = Convert.ToString(e.CommandArgument);
lblMessage.Text = "this the mobile no of selected row!";
}
}
}
Step1: Add the gridview in your .aspx page.
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
DataKeyNames="EmpID"onrowcommand="GridView1_RowCommand">
<Columns>
<asp:BoundField DataField="EMPID" HeaderText="EmployeeID" />
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="Address" HeaderText="Address" />
<asp:BoundField DataField="Mobile" HeaderText="Mobile" />
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnSelect" runat="server" Text="Select" CommandName="Select" CommandArgument='<%# Eval("Mobile") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Label ID="lblMessage" runat="server"></asp:Label>
<asp:TextBox ID="txtMobile" runat="server"></asp:TextBox>
</div>
step 2:- your .aspx.cs page.
NOTE:- this is my connection string which is using in below coding you can use your own to modify it in your web.config file.
My connectiion string is.
"
<connectionStrings>
<add name="mycon" connectionString="data source=SHIVAMGUPTA; initial catalog=operation; integrated security=true;" providerName="System.Data.SqlClient"/>
</connectionStrings>
"
**********************your code behind part.*********************
public partial class SelectGridColumn : System.Web.UI.Page
{
SqlConnection con;
protected void Page_Load(object sender, EventArgs e)
{
string conection;
conection = System.Configuration.ConfigurationManager.ConnectionStrings["mycon"].ConnectionString.ToString();
con = new SqlConnection(conection);
if (!IsPostBack)
{
FillGrid();
}
}
protected void FillGrid()
{
SqlCommand cmd = new SqlCommand("select * from employee", con);
con.Open();
GridView1.DataSource = cmd.ExecuteReader();
GridView1.DataBind();
con.Close();
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
txtMobile.Text = Convert.ToString(e.CommandArgument);
lblMessage.Text = "this the mobile no of selected row!";
}
}
}
how to insert value in identy
----------------INSERT VALUE IN IDENTITY COLUM
SET IDENTITY_INSERT EMPLOYEE ON
INSERT INTO EMPLOYEE(EID,ENAME,EADD)
VALUES(1,'SHIVAM','JHANSI/NEW DELHI')
SET IDENTITY_INSERT EMPLOYEE OFF
--------------------------------
SET IDENTITY_INSERT EMPLOYEE ON
INSERT INTO EMPLOYEE(EID,ENAME,EADD)
VALUES(1,'SHIVAM','JHANSI/NEW DELHI')
SET IDENTITY_INSERT EMPLOYEE OFF
--------------------------------
Fully Editable GridView in ASP.NET 2 using C#
This post demonstrate how to make a GridView editable all the time using C# asp.net.
step1-: Create a table with name " items" with following columns("iterm_no","name","price")
where "iterm_no" is identity column.as describe below
create table items
(
iterm_no int identity(1,1),
name varchar(20),
price numeric(10,2)
)
step2- Now create a web page with name(EditableGridView). as describe below.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="EditableGridView.aspx.cs" Inherits="EditableGridView" %>
<!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>Editable GridView</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False"
BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px"
CellPadding="3" DataKeyNames="INTERM_NO" >
<FooterStyle BackColor="White" ForeColor="#000066" />
<Columns>
<asp:BoundField DataField="INTERM_NO" HeaderText="ITEM_N0" InsertVisible="False" ReadOnly="True"
SortExpression="INTERM_NO" />
<asp:TemplateField HeaderText="NAME" SortExpression="NAME">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("NAME") %>'
OnTextChanged="TextBox_TextChanged" BorderStyle="None"></asp:TextBox>
<asp:HiddenField ID="HiddenField1" runat="server" Value='<%# Eval("INTERM_NO") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="PRICE" SortExpression="PRICE">
<ItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("PRICE") %>'
OnTextChanged="TextBox_TextChanged" BorderStyle="None"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<RowStyle ForeColor="#000066" />
<SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />
<HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
</asp:GridView>
</div>
<asp:Button ID="btnUpdate" runat="server" onclick="btnUpdate_Click"
Text="Update" />
<asp:Label ID="lblMessage" runat="server"></asp:Label>
</form>
</body>
</html>
step 3- Go to your code behind (EditableGridView.cs) as describe below.
using System;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data.SqlClient;
public partial class EditableGridView : System.Web.UI.Page
{
SqlConnection con;
bool[] rowChanged;
protected void Page_Load(object sender, EventArgs e)
{
string conString = ConfigurationSettings.AppSettings["mycon"];
con = new SqlConnection(conString);
int totalRows = GridView1.Rows.Count;
rowChanged = new bool[totalRows];
if (!Page.IsPostBack)
{
BindGrid();
}
}
public void BindGrid()
{
SqlDataAdapter adap = new SqlDataAdapter("select * from items", con);
DataTable dt = new DataTable();
adap.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void TextBox_TextChanged(object sender, EventArgs e)
{
TextBox thisTextBox = (TextBox)sender;
GridViewRow thisGridViewRow = (GridViewRow)thisTextBox.Parent.Parent;
int row = thisGridViewRow.RowIndex;
rowChanged[row] = true;
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
int totalRows = GridView1.Rows.Count;
for (int r = 0; r < totalRows; r++)
{
if (rowChanged[r])
{
GridViewRow thisGridViewRow = GridView1.Rows[r];
HiddenField hf1 = (HiddenField)thisGridViewRow.FindControl("HiddenField1");
string pk = hf1.Value;
TextBox tb1 = (TextBox)thisGridViewRow.FindControl("TextBox1");
string name = tb1.Text;
TextBox tb2 = (TextBox)thisGridViewRow.FindControl("TextBox2");
decimal price = Convert.ToDecimal(tb2.Text);
SqlCommand cmd = new SqlCommand("update items set name='" + name + "' , price='" + price + "' where INTERM_NO=' " + pk + "'", con);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
int temp = cmd.ExecuteNonQuery();
if (temp > 0)
{
lblMessage.Text = "Operation perform successfully";
con.Close();
}
}
}
GridView1.DataBind();
BindGrid();
}
}
}
Note: If you have any query or question about this post contact us:
step1-: Create a table with name " items" with following columns("iterm_no","name","price")
where "iterm_no" is identity column.as describe below
create table items
(
iterm_no int identity(1,1),
name varchar(20),
price numeric(10,2)
)
step2- Now create a web page with name(EditableGridView). as describe below.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="EditableGridView.aspx.cs" Inherits="EditableGridView" %>
<!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>Editable GridView</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False"
BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px"
CellPadding="3" DataKeyNames="INTERM_NO" >
<FooterStyle BackColor="White" ForeColor="#000066" />
<Columns>
<asp:BoundField DataField="INTERM_NO" HeaderText="ITEM_N0" InsertVisible="False" ReadOnly="True"
SortExpression="INTERM_NO" />
<asp:TemplateField HeaderText="NAME" SortExpression="NAME">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("NAME") %>'
OnTextChanged="TextBox_TextChanged" BorderStyle="None"></asp:TextBox>
<asp:HiddenField ID="HiddenField1" runat="server" Value='<%# Eval("INTERM_NO") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="PRICE" SortExpression="PRICE">
<ItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("PRICE") %>'
OnTextChanged="TextBox_TextChanged" BorderStyle="None"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<RowStyle ForeColor="#000066" />
<SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />
<HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
</asp:GridView>
</div>
<asp:Button ID="btnUpdate" runat="server" onclick="btnUpdate_Click"
Text="Update" />
<asp:Label ID="lblMessage" runat="server"></asp:Label>
</form>
</body>
</html>
using System;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data.SqlClient;
public partial class EditableGridView : System.Web.UI.Page
{
SqlConnection con;
bool[] rowChanged;
protected void Page_Load(object sender, EventArgs e)
{
string conString = ConfigurationSettings.AppSettings["mycon"];
con = new SqlConnection(conString);
int totalRows = GridView1.Rows.Count;
rowChanged = new bool[totalRows];
if (!Page.IsPostBack)
{
BindGrid();
}
}
public void BindGrid()
{
SqlDataAdapter adap = new SqlDataAdapter("select * from items", con);
DataTable dt = new DataTable();
adap.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void TextBox_TextChanged(object sender, EventArgs e)
{
TextBox thisTextBox = (TextBox)sender;
GridViewRow thisGridViewRow = (GridViewRow)thisTextBox.Parent.Parent;
int row = thisGridViewRow.RowIndex;
rowChanged[row] = true;
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
int totalRows = GridView1.Rows.Count;
for (int r = 0; r < totalRows; r++)
{
if (rowChanged[r])
{
GridViewRow thisGridViewRow = GridView1.Rows[r];
HiddenField hf1 = (HiddenField)thisGridViewRow.FindControl("HiddenField1");
string pk = hf1.Value;
TextBox tb1 = (TextBox)thisGridViewRow.FindControl("TextBox1");
string name = tb1.Text;
TextBox tb2 = (TextBox)thisGridViewRow.FindControl("TextBox2");
decimal price = Convert.ToDecimal(tb2.Text);
SqlCommand cmd = new SqlCommand("update items set name='" + name + "' , price='" + price + "' where INTERM_NO=' " + pk + "'", con);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
int temp = cmd.ExecuteNonQuery();
if (temp > 0)
{
lblMessage.Text = "Operation perform successfully";
con.Close();
}
}
}
GridView1.DataBind();
BindGrid();
}
}
}
Note: If you have any query or question about this post contact us:
How to get integer and character from input and display them in c
#include<stdio.h>
void main()
{
int r,m;
char variable;
printf("Enter the grad of student");
scanf("%c",&variable);
printf("Enter the roll no of student");
scanf("%d",&r);
printf("Enter the marks of student");
scanf("%d",&m);
// now display the student information
printf("\n");
printf("Rollno of student is %d",r);
printf("\n");
printf("Marks of student is %d",m);
printf("\n");
printf("Grade of student is%c", variable);
}
Monday, February 14, 2011
how to bind a text/csv file from html/dhtml
how to bind data with dhtml/html file
step 1:- create your html file
<html>
<head>
<body>
<object classid="clsid:333C7BC4-460F-11D0-BC04-0080C7055A83" id="myData">
<param name="DataURL" value="myfile.csv">
<param name="UseHeader" value="True">
<param name="TextQualifier" value="'">
</object>
<table id="myTable" datasrc="#myData">
<thead>
<tr style="font-weight:bold">
<td>First</td>
<td>Last</td>
</tr>
</thead>
<tbody>
<tr id="tableList">
<td><span datafld="firstname"></span></td>
<td><span datafld="lastname"></span></td>
</tr>
</tbody>
</table>
</body>
</html>
step-2- create your source file(data)
<!---
here creating our .csv file
----------------
firstname:STRING,lastname:STRING
Shivam,Gupta
Mukesh,Gupta
Simran,Gupta
--->
step 1:- create your html file
<html>
<head>
<body>
<object classid="clsid:333C7BC4-460F-11D0-BC04-0080C7055A83" id="myData">
<param name="DataURL" value="myfile.csv">
<param name="UseHeader" value="True">
<param name="TextQualifier" value="'">
</object>
<table id="myTable" datasrc="#myData">
<thead>
<tr style="font-weight:bold">
<td>First</td>
<td>Last</td>
</tr>
</thead>
<tbody>
<tr id="tableList">
<td><span datafld="firstname"></span></td>
<td><span datafld="lastname"></span></td>
</tr>
</tbody>
</table>
</body>
</html>
step-2- create your source file(data)
<!---
here creating our .csv file
----------------
firstname:STRING,lastname:STRING
Shivam,Gupta
Mukesh,Gupta
Simran,Gupta
--->
how to bind data in html/dhtml file
how to bind data with dhtml/html file
step 1:- create your html file
<html>
<head>
<body>
<object classid="clsid:333C7BC4-460F-11D0-BC04-0080C7055A83" id="myData">
<param name="DataURL" value="myfile.csv">
<param name="UseHeader" value="True">
<param name="TextQualifier" value="'">
</object>
<table id="myTable" datasrc="#myData">
<thead>
<tr style="font-weight:bold">
<td>First</td>
<td>Last</td>
</tr>
</thead>
<tbody>
<tr id="tableList">
<td><span datafld="firstname"></span></td>
<td><span datafld="lastname"></span></td>
</tr>
</tbody>
</table>
</body>
</html>
step-2- create your source file(data)
<!---
here creating our .csv file
----------------
firstname:STRING,lastname:STRING
Shivam,Gupta
Mukesh,Gupta
Simran,Gupta
--->
Saturday, February 12, 2011
How to use validation Rule in access database table
By Allen Browne. Created March 2007. Updated January 2009.
Validation Rules
Validation rules prevent bad data being saved in your table. Basically, they look like criteria in a query.
You can create a rule for a field (lower pane of table design), or for the table (in the Properties box in table design.) Use the table's rule to compare fields.
There is one trap to avoid. In some versions of Access, you will not be able to leave the field blank once you add the validation rule, i.e. you must enter something that satisfies the rule. If you need to be able to leave the field blank, add OR Is Null to your rule. (Some versions accept Nulls anyway, but we recommend you make it explicit for clarity and consistency.)
This article explains how to use validation rules, and concludes with some thought provoking on when to use them.
When you select a field in table design, you see its Validation Rule property in the lower pane.
This rule is applied when you enter data into the field. You cannot tab to the next field until you enter something that satisfies the rule, or undo your entry.
Examples:
| To do this ... | Validation Rule for Fields | Explanation |
| Accept letters (a - z) only | Is Null OR Not Like "*[!a-z]*" | Any character outside the range A to Z is rejected. (Case insensitive.) |
| Accept digits (0 - 9) only | Is Null OR Not Like "*[!0-9]*" | Any character outside the range 0 to 9 is rejected. (Decimal point and negative sign rejected.) |
| Letters and spaces only | Is Null Or Not Like "*[!a-z OR "" ""]*" | Punctuation and digits rejected. |
| Digits and letters only | Is Null OR Not Like "*[!((a-z) or (0-9))]*" | Accepts A to Z and 0 to 9, but no punctuation or other characters. |
| Exactly 8 characters | Is Null OR Like "????????" | The question mark stands for one character. |
| Exactly 4 digits | Is Null OR Between 1000 And 9999 | For Number fields. |
| Is Null OR Like "####" | For Text fields. | |
| Positive numbers only | Is Null OR >= 0 | Remove the "=" if zero is not allowed either. |
| No more than 100% | Is Null OR Between -1 And 1 | 100% is 1. Use 0 instead of -1 if negative percentages are not allowed. |
| Not a future date | Is Null OR <= Date() | |
| Email address | Is Null OR ((Like "*?@?*.?*") AND (Not Like "*[ ,;]*")) | Requires at least one character, @, at least one character, dot, at least one character. Space, comma, and semicolon are not permitted. |
| You must fill in Field1 | Not Null | Same as setting the field's Required property, but lets you create a custom message (in the Validation Text property.) |
| Limit to specific choices | Is Null OR "M" Or "F" | It is better to use a lookup table for the list, but this may be useful for simple choices such as Male/Female. |
| Is Null OR IN (1, 2, 4, 8) | The IN operator may be simpler than several ORs. | |
| Yes/No/Null field | Is Null OR 0 or -1 | The Yes/No field in Access does not support Null as other databases do. To simulate a real Yes/No/Null data type, use a Number field (size Integer) with this rule. (Access uses 0 for False, and -1 for True.) |
In table design, open the Properties box and you see another Validation Rule. This is the rule for the table.
The rule is applied after all fields have been entered, just before the record is saved. Use this rule to compare values across different fields, or to delay validation until the last moment before the record is saved.
Examples:
| To do this ... | Validation Rule for Table | Explanation |
| A booking cannot end before it starts | ([StartDate] Is Null) OR ([EndDate] Is Null) OR ([StartDate] <= [EndDate]) | The rule is satisfied if either field is left blank; otherwise StartDate must be before (or the same as) EndDate. |
| If you fill in Field1, Field2 is required also | ([Field1] Is Null) OR ([Field2] Is Not Null) | The rule is satisfied if Field1 is blank; otherwise it is satisfied only if Field2 is filled in. |
| You must enter Field1 or Field2, but not both | ([Field1] Is Null) XOR ([Field2] Is Null) | XOR is the exclusive OR. |
In designing a database, you walk a tightrope between blocking bad data and accepting anything. Ultimately, a database is only as good as the data it contains, so you want to do everything you can to limit bad data. On the other hand, truth is stranger than fiction, and your database must handle those weird real-world cases where the data exceeds the bounds of your imagination.
Field's validation rule
Take a BirthDate field, for example. Should you create a rule to ensure the user doesn't enter a future date? We would need some radically different physics to ever be entering people who are not yet born, so it sounds like a safe enough rule? But did you consider that the computer's date might be wrong? Would it be better to give a warning rather than block the entry?
The answer to that question is subjective. The question merely illustrates the need to think outside the box whenever you will block data, not merely to block things just because you cannot imagine a valid scenario for that data.
Validation Rules are absolute. You cannot bypass them, so you cannot use them for warnings. To give a warning instead, use an event of your form, such as Form_BeforeUpdate.
Table's validation rule
We suggested using this rule for comparing fields. In the ideal database design, the fields are not dependent on each other, so if you are comparing fields, you might consider whether there is another way to design the table.
Our first example above ensures that a booking does not end before it starts. There is therefore a dependency between these two fields. Could we redesign the table without that dependency? How about replacing EndDatewith a Duration field? Duration would be a number in an applicable unit (e.g. days for hotel bookings, periods for school classrooms, or minutes for doctors appointments.) We use a calculated field in a query to get theEndDate. This may not be the best design for every case, but it is worth considering when you go to use the record-level validation rule.
Limitations
You cannot use a validation rule where:
- You want to call user-defined functions, or VBA functions beyond the ones in JET such as IIf() and Date().
- The user should be able to bypass the rule.
- The expression is too complex.
- The expression involves data in other records or other tables. (Well, not easily, anyway.)
Alternatives
Use these alternatives instead of or in combination with validation rules:
- Required: Setting a field's Required property to Yes forces the user to enter something. (In addition to the obvious cases, always consider setting this to Yes for your foreign key fields. See #3 in this article for details.)
- Allow Zero Length: Setting this property to No for text, memo, and hyperlink fields prevents a zero-length string being entered. A ZLS is not the same as a Null, so if you permit this you have confusing data for the user, more work checking for both as a developer, more chance of a mistake, and slower executing queries. More information in Problem Properties.
- Indexed: To prevent duplicates in a field, set this property to Yes (No Duplicates). Using the Indexes box in table design, you can create a multi-field unique index to the values are unique across a combination of fields.
- Lookups: Rather than creating a validation rule consisting of a list of valid values, consider creating a related table. This is much more flexible and easier to maintain.
- Input Mask: Of limited use. Users must enter the entire pattern (without them you can enter some dates with just 3 keystrokes, e.g. 2/5), and they cannot easily insert a character if they missed one.
Conclusion
Validation rules are very useful for keeping bad data out of your tables, but be careful not to overdo them. You don't want to block things that might be valid, though unexpected.
Subscribe to:
Posts (Atom)