How to use Asp.net
  • Home
  • About us
  • Disclaimer
  • joy of helping
KEEP IN TOUCH

How to use GridView with Databound fields Ado.net way C#

Mar27
2011
Leave a Comment Written by vikram

Hello there, here i m explaining how to use Databound fields using gridview before this article i have written an article on ItemTemplate fields using gridview.

*you can refer below link to get to know about how to create  Events for gridview.

http://howtouseasp.net/?p=61

 

now first of all we will create a database.  Here the following script, copy it and run it.

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N‘[dbo].[tbEmp]‘) AND type in (N‘U’))

BEGIN

CREATE TABLE [dbo].[tbEmp](

[id] [int] IDENTITY(1,1) NOT NULL,

[name] [varchar](50) NULL,

[age] [int] NULL,

[address] [varchar](50) NULL

) ON [PRIMARY]

END

Place the GridView control on a form and set the following property.

AutoGenerateColumns=”False”

And set the Gridview Events name is

onrowcancelingedit=”GridView1_RowCancelingEdit”

onrowdeleting=”GridView1_RowDeleting” onrowediting=”GridView1_RowEditing”

onrowupdating=”GridView1_RowUpdating”

*and one more thing set the readonly property true for Id field.

*set the Datafields of all databound

Or add the default.aspx page and paste the following source code in it.

<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Default.aspx.cs” Inherits=”_Default” %>

<!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>Untitled Page</title>

<style type=”text/css”>

.style1

{

width: 100%;

}

</style>

</head>

<body>

<form id=”form1″ runat=”server”>

<div>

</div>

<table class=”style1″>

<tr>

<td>

Name</td>

<td>

<asp:TextBox ID=”txt_name” runat=”server”></asp:TextBox></td>

</tr>

<tr>

<td>

Age</td>

<td>

<asp:TextBox ID=”txt_age” runat=”server”></asp:TextBox></td>

</tr>

<tr>

<td>

Address</td>

<td>

<asp:TextBox ID=”txt_address” runat=”server”></asp:TextBox></td>

</tr>

<tr>

<td>

&nbsp;</td>

<td>

<asp:Button ID=”Button1″ runat=”server” onclick=”Button1_Click” Text=”Button” />

</td>

</tr>

<tr>

<td colspan=”2″>

<asp:Label ID=”lbl_msg” runat=”server” ForeColor=”Red”></asp:Label>

</td>

</tr>

<tr>

<td colspan=”2″>

<asp:GridView ID=”GridView1″ runat=”server” AutoGenerateColumns=”False”

AutoGenerateDeleteButton=”True” AutoGenerateEditButton=”True”

onrowdeleting=”GridView1_RowDeleting” onrowediting=”GridView1_RowEditing”

onrowcancelingedit=”GridView1_RowCancelingEdit”

onrowupdating=”GridView1_RowUpdating” CellPadding=”4″ ForeColor=”#333333″

GridLines=”None”>

<RowStyle BackColor=”#EFF3FB” />

<Columns>

<asp:BoundField DataField=”id” HeaderText=”Id” ReadOnly=”True” />

<asp:BoundField DataField=”Name” HeaderText=”Name” />

<asp:BoundField DataField=”Age” HeaderText=”Age” />

<asp:BoundField DataField=”address” HeaderText=”address” />

</Columns>

<FooterStyle BackColor=”#507CD1″ Font-Bold=”True” ForeColor=”White” />

<PagerStyle BackColor=”#2461BF” ForeColor=”White” HorizontalAlign=”Center” />

<SelectedRowStyle BackColor=”#D1DDF1″ Font-Bold=”True” ForeColor=”#333333″ />

<HeaderStyle BackColor=”#507CD1″ Font-Bold=”True” ForeColor=”White” />

<EditRowStyle BackColor=”#2461BF” />

<AlternatingRowStyle BackColor=”White” />

</asp:GridView>

</td>

</tr>

</table>

</form>

</body>

</html>

 

In Coding

using System;

using System.Configuration;

using System.Data;

using System.Linq;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.HtmlControls;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Xml.Linq;

using System.Data.SqlClient;

 

public partial class _Default : System.Web.UI.Page

{

SqlConnection con = new SqlConnection();

SqlDataAdapter adp;

SqlCommand cmd;

DataTable dt;

 

protected void Page_Load(object sender, EventArgs e)

{

con.ConnectionString = ConfigurationManager.ConnectionStrings["cnn"].ConnectionString;

con.Open();

if (con.State == ConnectionState.Closed)

{ con.Open(); }

con.Close();

 

if (IsPostBack == false)

{ grdview(); }

}

 

private void grdview()

{

if (con.State == ConnectionState.Closed)

{ con.Open(); }

adp = new SqlDataAdapter(“select * from tbemp order by id desc”, con);

dt = new DataTable();

adp.Fill(dt);

adp.Dispose();

if(dt.Rows.Count == 0)

{

lbl_msg.Text = “No Record”;

}

else

{

lbl_msg.Text = String.Empty;

GridView1.DataSource = dt;

GridView1.DataBind();

}

dt.Dispose();

con.Close();

}

protected void Button1_Click(object sender, EventArgs e)

{

if (con.State == ConnectionState.Closed)

{ con.Open(); }

 

cmd = new SqlCommand(“insert into tbEmp values(@name,@age,@address)”, con);

cmd.Parameters.AddWithValue(“@name”, txt_name.Text);

cmd.Parameters.AddWithValue(“@age”, txt_age.Text);

cmd.Parameters.AddWithValue(“@address”, txt_address.Text);

cmd.ExecuteNonQuery();

cmd.Dispose();

con.Close();

grdview();

txt_name.Text = String.Empty;

txt_age.Text = String.Empty;

txt_address.Text = String.Empty;

}

// Deleting the Record

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)

{

if (con.State == ConnectionState.Closed)

{ con.Open(); }

 

Int32 idd = Convert.ToInt32(GridView1.Rows[e.RowIndex].Cells[1].Text);

cmd = new SqlCommand(“delete from tbemp where id=@id”, con);

cmd.Parameters.AddWithValue(“@id”, idd);

cmd.ExecuteNonQuery();

cmd.Dispose();

con.Close();

grdview();

}

protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)

{

GridView1.EditIndex = -1;

grdview();

}

protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)

{

GridView1.EditIndex = e.NewEditIndex;

grdview();

}

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)

{

if (con.State == ConnectionState.Closed)

{ con.Open(); }

Int32 idd = Convert.ToInt32(GridView1.Rows[e.RowIndex].Cells[1].Text);

cmd = new SqlCommand(“update tbemp set name=@name,age=@age,address=@address where id=@id”, con);

cmd.Parameters.AddWithValue(“@name”, ((TextBox)(GridView1.Rows[e.RowIndex].Cells[2].Controls[0])).Text);

cmd.Parameters.AddWithValue(“@age”, ((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text);

cmd.Parameters.AddWithValue(“@address”, ((TextBox)(GridView1.Rows[e.RowIndex].Cells[4].Controls[0])).Text);

cmd.Parameters.AddWithValue(“@id”, idd);

cmd.ExecuteNonQuery();

cmd.Dispose();

con.Close();

GridView1.EditIndex = -1;

grdview();

}

}

EDITING THE RECORDS

 

AFTER UPDATING THE RECORDS

 

DELETING THE RECORD

 

 

Hope you will like this post…

Posted in Asp.net
SHARE THIS Twitter Facebook Delicious StumbleUpon E-mail
« How to use GridView with Insert, Edit, Update, Delete the Ado.net way C#
» How to do paging in Datalist with images Ado.net way C#

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

*

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Joy of Helping

Any sort of help to the children who are fatherless, poor & are from far-off areas.
Joy of Helping

Facebook Link

Asp dot Net ,Ajax,Xml.

Recent Posts

  • ROW_NUMBER(), NTILE(), partition by, Duplicate Records, CTE sql server 2008
  • How to get second highest Salary sql server 2008
  • Insert values, insert into, insert default value, insert execute and select into sql server 2008
  • How to Bind GridView with SqlDataReader in Asp.net
  • how to attach files to email without storing on disk using Asp.net FileUpload control

Recent Comments

  • Anonymous on ROW_NUMBER(), NTILE(), partition by, Duplicate Records, CTE sql server 2008
  • dhananjay on How to use GridView with Insert, Edit, Update, Delete the Ado.net way C#
  • dev on How can we limit the characters in multiline textbox asp.net using JavaScript
  • navneet on How to display image in Image control after upload on the server asp.net C#
  • AnhVu on How to do Shopping Cart in Asp.net C#

Archives

  • February 2013
  • September 2012
  • April 2012
  • January 2012
  • October 2011
  • August 2011
  • May 2011
  • April 2011
  • March 2011

Categories

  • Asp.net
  • jQuery
  • Sql Server

Meta

  • Log in
  • Entries RSS
  • Comments RSS
  • WordPress.org

EvoLve theme by Theme4Press  •  Powered by WordPress How to use Asp.net