EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
A supportive language is that which gives
the optimal output. Asp.net provides
that
optimization
by
providing
alternatives controls and one of the best
is Grid ie .
Easy
Gridview
with
Gridview
Tutorials
Page 1
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
Acknowledgement
I would like to express my deep gratitude to my parents and my faculty members who helped
me and guided me in writing this book. I would also like to thank my friends and collegues for
their esteem advice and assistance in keeping my progress on schedule. My valuable thanks are
also enlongated to my brother who keep pushing me into the field, so that I work hard. I would
also thankful to my office team members who directly and indirectly helped me in writing these
tutorials. Esteem thanks you Miss Bejji Purnima who helped me a lot while writing this book.
Most valuable thanks to C# Corner who helped a lot in achieving minor and major success by
keep encouraging new commers just like me. Happy to help and publish new book in my next
term.
Page 2
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
How this book is organized
1. Introduction of Asp.Net
Introduction of Grid View
Adding Grid view to Visual Studio 10
Some important Grid View Properties
Some important Grid View Methods
Some important Grid View Events
2. Introduction of Grid View using SQL Server Database
3. Tutorial of Grid View using LINQ
4. Tutorial of Grid View using 3 Tier
5. Get Data from Database using Selected ID
6. Gridview Sorting Example in asp.net using C#
7. Bind Datagrid in WPF using C#
8. Bind Grid View Control using XML in Asp.net C#
9. Bind Grid View without Database in MVC 3 C#
10. Bind Grid View with Database in MVC 5 C#
11. CRUD operation of Dropdownlist inside Gridview in asp.net
12. Export grid view to Excel using ItextSharp library
13. Export selected data from Gridview in Excel in asp.net using C#
14. Bind Gridview with MS Access Database in Asp.Net C#
15. Insert Images into DataGridView in Windows Application
16. Bound Control Demo using Gridview in Asp.Net
Page 3
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
Introduction of Asp.Net
Asp.Net is Acronym of Active Server Page and it is a web development model, which is used to
develop interactive and data- driven web application over the internet. It is having large number
of controls like – textbox, button, labels, hyperlinks, dropdowns and many more from which you
can easily develop any application. With the help of CLR you can use your Asp.Net application
using any language [c#, vb, F#, J#, Visual C++].
Asp.Net also have Rich Control from where you can develop interactive and better UI application
to the user, controls like – Ad Rotator and Calendar Control are one of them. Asp.Net supports
Ado.Net [ActiveX Data Objects] that help you to connect and work with data stored in a database.
Do you know the basic difference between Asp.Net and Asp?
Code Behind File
Inheritance
Language
Configuration Files
Custom Controls
Ado.Net
ASP.NET
Provides code-Behind File
which contains all events
handling code.
Supports Inheritance
Supports Programming
Language.
Provides Configuration Files,
such as web.config and
machine.config.
Supports Custom Controls
Supports Ado.Net with XML
integration of data from two
or more data source
Page 4
ASP
Does not have such facility to
separate programming logic
from design.
Does not support Inheritance
Supports Scripting
Languages.
Does not support any
configuration files.
Does not support custom
controls.
Supports ADO which is a
simple COM object with
limited Facilities.
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
I think now you all are about asp.net welly, we will proceed to our next topic from where we can
start our real focus of this book. In this book we will talk about one of the control of Ado.Net i.e.
– Grid View.
INTRODUCTION OF GRID VIEW
Grid View is a kind of tabular representation where we can store or represent our data in tabular
form, where there are columns and rows just similar to that of HTML table, we can do many
operation on grid view like edit, delete, update, cancel, paging and many more. We will explore
and study all these things in our upcoming chapters.
In visual studio you can see our grid view in the toolbox [Ctrl + Shift + X]. It o es u der Data
“e tio .
Figure 1: Grid View
Page 5
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
To use Grid View you just have to Drag and Drop the Grid View to your .aspx page. See the below
image to get a better idea.
Figure 1.2: Grid View in .aspx page
There are lots of properties and events are there in grid view that we will see one by one. You
can open the Properties by going to - - > Grid View - - > Press F4 or Right Click and select
Properties. In Properties they having various fields about Grid View you can change it from their
directly rather than to go the code part.
For Example if you want to change the background color of your grid view you can change it
directly from the property window, no need to go the code part and change it, as you change
something in the property window VS10 will directly makes the code for that change in your .aspx
page.
Page 6
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
Figure 1.3: Grid View Properties Window
GENERAL PROPERTIES OF GRID VIEW
1) Allow Paging: By which you can set the paging style in your Gridview for better
navigation, by just going to the property of Gridview you can enable and disable the
paging.
2) Allow Sorting: This feature is related to sorting, where you can sort the data, according
to the need.
3) Auto Generate Columns: This property lets you to generate bound fields automatically,
by just clicking on checkbox you can enable it.
4) Auto Generate Delete Button: This property lets you to generate a common field with a
Delete Butto for ea h ro i our Grid ie . B hi h ou a easil delete a data
from your Gridview.
Page 7
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
5) Auto Generate Edit Button: This propert lets ou to ge erate a o
o field ith Edit
butto for ea h ro i our Grid ie . Data is e er to e o sta t, it ha ges ith the
time, so in future you might have difficulty in editing those data, but by this property you
can easily edit and update any data. Later in this book we will see each control with the
help of tutorial.
6) BackImageUrl: This property lets you to set the background image in your Gridview with
the help of imageUrl.
7) DataKeysNames: This feature takes your primary key field from the database, by which
you can display the data in your Gridview.
8) Datakey: This feature get automatically fired for each row when you specify the
DataKe sNa es - It creates the Datakey object for each row where it contains the value
of the field.
9) DataSource: This property lets you to retrieves the list of the data from the database to
your Gridview.
10) DataSourceID: This property sets the ID of the control from which you want to retrieves
the list of the data to your Gridview.
11) PageSize: This property lets you to set the page size according to your records that you
want to display in Gridview.
12) Selected Index: This property lets you to set the index of the selected row in Gridview
control.
13) Selected Row: This property lets you give to give the reference to the Gridview objects
that represents the selected row.
GridView1.SelectedRow.Cells[1].Text;
14) BoundField: Shows the value of a field in a data source.
15)Button Field: Shows the command button for each item in the Gridview control. It lets
you to create a column for custom button controls [Add or remove button].
16) HyperLink Field: It lets you to bind a second field to the hyperlink URL which shows the
value of a field in a data source as hyperlink.
Page 8
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
17) SortDirection: It obtains the sort direction of the column (in which direction you want
to sort) being sorted.
18) Show Header: It sets a value showing whether the header row is displayed in a Gridview
control or not.
19) Pager Template: It lets you to set the custom content for the pager row in a Gridview
control.
20) Show Footer: It lets you to sets a value of footer row (whether it is showing or not) in
Gridview control.
SOME IMPORTANT METHODS OF GRIDVIEW CLASS
1) DataBind (): It binds the data from the database with the Gridview control.
2) Delete Row (): Deletes the record from the specified location from the Data source.
3) IsBindableType (): It checks whether the particular data type can be bind to a bound
control in a Gridview or not?
4) Sort (): This generally used for the purpose of sorting in a Gridview.
5) Update Row (): It lets you to update the record that is specified by index of its field value.
SOME IMPORTANT EVENTS OF GRIDVIEW CLASS:
1) PageIndexChanged: It will invoke when pager button is clicked, but before you have to
handle the code for paging operation in Gridview.
2) RowCommand: It will invoke when a button is clicked in Gridview control.
3) RowCreated: It will invoke when a row is created in Gridview control.
Page 9
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
4) RowDataBound: It will invoke when a data row is bound to the data in Gridview control.
5) RowUpdating: It will invoke when a row update button is clicked, but before you have to
handle the code for that in Gridview control.
Page
10
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
Grid View using SQL
Server Database
To enter into the code scenario of Gridview, it is very necessary to understand the connectivity
of SQL Server Database and Gridview, generally Gridview work with databases only so its prior
necessity to understand – how to connect and work with SQL server and Gridview.
We all know that VS10 has one inbuilt SQL Server Database, which is your local database, we
a ’t use lo al data ase a
here, I ea lo al data ase ill ot gi e ou the e tra utilities a d
free tools, besides this you can lose your safety check too, it might be worse if it hit by SQL
injection. For these and many other reason it is better if we use SQL Server 2008 instead of VS10
SQL Server.
First of all you have download the SQL Server 2008 from the Internet Source, once you got
completed with the process of downloading, you have to install that there are many tutorials
on WWW from where you can make that out.
Here is the link for Downloading: SQL Server Management Studio Express 2008
Here is the Link of Installation Process: Step by Step guide to install SQL Server
Step1) Open SQL Server Management Studio, if you are using Window Authentication than your
Server Name is - -> local, if you had used SQL Server Authentication then at the time of installation
whatever the server name you had given that comes. Moreover if you are using SQL Server
Authentication than they will ask you by Username and Password, that also comes from the
installation process, so you take care about these things at the time of installation.
Page
11
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
Here my username is taken from the PC or admin name, if you will use the SQL Server
authentication than you have to write the username and the password, remember that.
Step2) Click on Connect. If things get right - It will open up the SQL Server Studio for you.
Page
12
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
This is the Object Explorer same as Server Explorer in VS10, Here you can make New Database,
table, Store Procedures and many more things.
Step3) let’s start
reati g Ne Data ase. Cli k o Data ase i O je t E plorer a d -- > New
Database. New Database window will open. Give you database name and Click on Ok. See below
Image.
You can see you database under Database, See below Image.
Page
13
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
Step4) Here make a new table, by going to- -> mynewdb - -> Table - -> New Table.
Page
14
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
Step5) Open you Visual Studio 2010, Open Server Explorer. Click on Connect to database.
Page
15
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
It will open an Add Connection window like below image; there you have to give the username
that comes automatically if you click on refresh, if not come than write on the place of server
name.
Once you got your Database it means you work is done just check out by test Connection, if you
the message Test connection successfully. Then everything is right and you can proceed by
Pressing OK.
Page
16
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
After pressing OK, Check out in Server Explorer, you got your Database and table under your
servername.databasename.dbo file, See below image.
Once you got with your table – Right click on the table -> Show Table Data - > Enter some data
into it, see below image:
Page
17
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
GridView using SQL Server Database
A Simple Binding Program in Gridview
We will display this data into the Gridview using the data ase this is all e a t do ’t e? We
will understand the whole process with the help of a simple binding program of Gridview.
Now just add one Gridview to your .aspx page, by navigate to tools-> Data-> Gridview -> Drag
and Drop.
Once you done with it, go to the Gridview Task (on the top right there is an arrow click on it) ->
Edit Column -> from the available fields (left hand side) -> double click or Add to select bound
fields ( take 3 bound fields as ID, Name and City) You will see those filed o es i Selected
Area .
Now input the proper heading by going to - > Header Text gi e headi g as ID, Na e a d Cit
(Template Field Properties – Right Hand side) you have to find another property too named as –
Data Field i put the sa e data field as ou had take i the data ase. After all these o ert
all the field to template fields (link below the template filed properties – just click it). Press OK.
The last step of the configuration is the Gridview properties where you have to give the
DatakeyNames – provide your primary key here (I had taken ID as primary so I had taken the
same).
Page
18
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
This last part is where we code to display the data from database to Gridview and eventually
the connection between the SQL Server and Gridview.
Add the namespaces: it will help you to use the essential methods and properties of SQL server
that is pre-installed in the SQL library.
using System.Data.SqlClient;
using System.Data;
.aspx.cs file –
using
using
using
using
using
using
using
using
System;
System.Collections.Generic;
System.Linq;
System.Web;
System.Web.UI;
System.Web.UI.WebControls;
System.Data.SqlClient;
System.Data;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
This is the Refreshdata
method that we had
refreshdata();
made below.
}
public void refreshdata()
{
SqlConnection con = new SqlConnection("Data
Source=Nilesh;Initial Catalog=nil_db;Integrated Security=True");
SqlCommand cmd = new SqlCommand("select * from tbl_data",con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
Page
19
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
Just run the program you will get the data from the database, in this way you can bind Gridview
with any database and can play with many events and properties of Gridview.
This is my Output- same data from the database.
Page
20
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
Tutorial of Gridview
Using LINQ
Step1
Open Visual Studio 10 then create an empty website then provide a name such as
insert_data_gridview (or whatever you like).
Step2
Go to your website that will be in your right hand pane, right-click on the project and select "Add
New Item". In that you need to select We Form". By default the name is "Default.aspx"; change
it to "linqgridviewdemo.aspx". Naming is very important in every project, try to keep in the habit,
it'll become very helpful in large projects.
Step3
Agai ou eed to add “QL “er er Data ase" a d "LINQ to SQL classes" from Add New Item and
provide a suitable name for both files. They will ask you by prompting whether or not to add a
SQL file into the "App_data" folder, make it "Yes". It is good to keep our database inside a secure
folder provided by Microsoft, otherwise it can be hacked by SQL Injection or similar attacks.
Step4
we have to first design our linqgridviewdemo.aspx page. Open it up and get into the Design
section that is showing in the bottom part. Modify the design as below image shows.
Page
21
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
Step5
In the left pane of your Visual Studio 10 there is a Server Explorer. Since you added a SQL Server
Database, VS 10 automatically made a Database.mdf file for you. Right-click on the table and Add
a new table, provide the name as "tbl_data".
Page
22
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
Step6
In that pane you only need to make 2 Stored Procedures named "sp_getdata" and
"sp_insertdata".
The following is the code for sp_getdata-
The following is the code for sp_insertdata-
Page
23
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
Step7
We need to add this Stored Procedure to the LINQ file that we added from add new item. Open
your LINQ file "DataClasses.dbml". When you open it you see two sections, one is for a relational
database and the other is for a simple database, we need to drag all our Stored Procedures into
the section of the simple database.
Step8
Open the "linqgridviewdemo.cs" file. We need to code now for inserting data into textboxes and
when you press the button, the data will be set into the GridView. So go ahead, let's do the code,
it's really simple.
Page
24
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
public partial class _Default: System.Web.UI.Page
{
DataClassesDataContext ddc = new DataClassesDataContext();
protected void Page_Load(object sender, EventArgs e)
{
refreshdata();
}
public void refreshdata()
{
GridView1.DataSource = ddc.sp_getdata();
GridView1.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
ddc.sp_insertdata(TextBox1.Text, TextBox2.Text,
TextBox3.Text);
refreshdata();
}
}
This is it! You can see by pressing Ctrl+Shift+W then filling in all the text boxes and submitting it.
You will see all the data will enter into the grid view.
Download Tutorial: Bind Gridview using LINQ
Page
25
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
Tutorial of GridView
Using 3 Tier
To process this tutorial, first we should understand the brief introduction of 3 tier architecture in
software development. 3 tier architecture generally separate out the code layers so that we can
easily understand and on the purpose we can change the needed one, I mean if you want to
change the UI part than it is not necessary to change the whole code, just by going to the
presentation layer makes your work.
In a similar way, if you needed any database related query, then you can switch off to the data
layer, and can check out the whole thing. With the help of 3 tier the transparency of code
becomes lighter, now we can mess with any code.
3 Tier Architecture is very well development in every aspects of Software development and
Application Development. Mainly it have 3 layers –
1. Presentation Layer
2. Business Logic Layer(BLL)/Business Access layer (BAL)
3. Data Access Layer (DAL)
Page
26
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
Now we will understand this layers step by step:
1) Presentation Layer/ Application layer-- > Presentation Layer is used for designing your
application. It contain you .aspx page where you embed your design code. It having you
all interfaces related to the application that you are building - (Window, Web, and
Mobile). It usually only communicates with Business Layer.
2) Business Logic Layer/Business Access Layer - -> Business layer contains all your business
login where we can insert, delete, retrieve and validate the data. It usually act as an
interface between our Presentation Layer and Data Access layer.
Page
27
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
3) Data Access Layer - -> Data Access Layer having the methods that connect with our SQL
Server [Database] and to perform various operation of SQL like -- > insert, update, get,
delete data from Database.
NOW TO THE PART GRIDVIEW TUTORIAL IN 3 TIER ARCHITECTURE
INITIAL CHAMBER:
Step1) Open Your Visual Studio 2010 and Create an Empty Website, Give a suitable name
[GridView_demo].
Step2) In Solution Explorer you get your empty website, Add a web form, SQL Database and 3
Class file. By going like this –
For Web Form:
GridView_demo (Your Empty Website) -> Right Click -> Add New Item -> Web Form. Name it as
-> gridview_demo.aspx.
For SQL Server Database:
GridView_demo (Your Empty Website) -> Right Click -> Add New Item -> SQL Server Database.
[Add Database inside the App_Data_folder].
For 3 Class Files:
GridView_demo (Your Empty Website) -> Right Click -> Add New Item -> Class [Add 3 Class files
- -> Add your class file in App_code Folder] - -> Give name as:1) Commonfunctions.cs
2) BAL_user_operation.cs
3) DAL_user_operation.cs
Page
28
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
DATABASE CHAMBER:
Step3) In Server Explorer, Click on your Database [Database.mdf] - -> Tables - -> Add New Table
-:- Make table like this:
Table - -> t l_data [Do ’t Forget to
ake ID as IS Identity -- True]
Add some Store procedure for Update, Insert and Delete Data by going to Database
[Database.mdf] - -> Store Procedures - -> Right Click - -> Add New store Procedures.
1) sp_getdata()
2) sp_insert()
Page
29
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
3) sp_update()
4) sp_delete()
These all are the Store Procedures that we will use for updating deleting and editing our data in
Grid View.
Page
30
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
DESIGN CODE
Step 5) We will create our desig i Grid Vie . Let’s egi
page and fry the code like this:
ope i g our grid ie _de o.asp
<body>
<form id="form1" runat="server">
<table style="width:100%;">
<caption class="style3">
<strong>Bind Grid View Using 3Tier</strong></caption>
<tr>
<td
align="center">
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False"
BackColor="LightGoldenrodYellow" BorderColor="Tan"
BorderWidth="1px"
CellPadding="2" DataKeyNames="id" ForeColor="Black"
GridLines="None"
AutoGenerateDeleteButton="True"
AutoGenerateEditButton="True"
onrowcancelingedit="GridView1_RowCancelingEdit"
onrowdeleting="GridView1_RowDeleting"
onrowediting="GridView1_RowEditing"
onrowupdating="GridView1_RowUpdating">
<AlternatingRowStyle BackColor="PaleGoldenrod" />
<Columns>
<asp:TemplateField HeaderText="Name"
SortExpression="name">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"
Text='<%# Bind("name") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%#
Bind("name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
Page
31
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
<asp:TemplateField HeaderText="Email" SortExpression="email">
<EditItemTemplate>
<asp:TextBox ID="TextBox3" runat="server"
Text='<%# Bind("email") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%#
Bind("email") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="City"
SortExpression="city">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server"
Text='<%# Bind("city") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%#
Bind("city") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="Tan" />
<HeaderStyle BackColor="Tan" Font-Bold="True" />
<PagerStyle BackColor="PaleGoldenrod"
ForeColor="DarkSlateBlue"
HorizontalAlign="Center" />
<SelectedRowStyle BackColor="DarkSlateBlue"
ForeColor="GhostWhite" />
<SortedAscendingCellStyle BackColor="#FAFAE7" />
<SortedAscendingHeaderStyle BackColor="#DAC09E" />
<SortedDescendingCellStyle BackColor="#E1DB9C" />
<SortedDescendingHeaderStyle BackColor="#C2A47B" />
</asp:GridView>
</td>
</tr>
</table>
</form>
</body>
Page
32
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
Or you also can manually do this design by dragging the Grid view into your .aspx page. Then click
the arrow sign on grid view - -> Grid view tasks will open - -> Edit Columns - -> A Field i do
will open (Belo I age . Here ou ha e to add three BoundField Butto fro - -> Available
Fields. - -> Change the header text - -> Name, Email, City. Unlick the Auto Generated Button at
the bottom.
Page
33
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
Get into Bound Field Properties - -> Data Fields - -> Cha ge e er Bou d field’s Data field to - ->
Bound Fields Header Text
Name - -> name
Email - -> email
City - -> city
Data Fields
Go to Grid view [In design mode] - -> press F4 to open Property window of grid view and find - > Data Keys Name - -> and write – id.
Page
34
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
In Property Window find - -> Auto Generate Edit and Auto Generate Delete Button and make it
- -> True.
This is your Actual Design:
CODE CHAMBER:
1) Open Commonfunction.cs file and add this code :- ->
using
using
using
using
using
System;
System.Collections.Generic;
System.Linq;
System.Web;
System.Configuration;
/// <summary>
/// Summary description for Commonfunctions
/// </summary>
public class Commonfunctions
Page
35
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
{
public Commonfunctions()
{
//
// TODO: Add constructor logic here
//
}
public static string getconstring()
{
return
ConfigurationManager.ConnectionStrings["dbcon"].ToString();
}
}
This code is written for SQL Connection String that we have to call again and again by going to
data ase propert that ust e the le gth pro ess, that’s h e had ade this lass a d o
we just call its method - -> getconstring() that make our process shorter and comfortable.
2) Open DAL_user_operation.cs file and code it like this
using
using
using
using
using
using
System;
System.Collections.Generic;
System.Linq;
System.Web;
System.Data;
System.Data.SqlClient;
/// <summary>
/// Summary description for DAL_user_operation
/// </summary>
public class DAL_user_operation
{
public DAL_user_operation()
{
//
Page
36
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
// TODO: Add constructor logic here
//
}
public bool user_insert(string name, string email,string city)
{
SqlConnection con = new
SqlConnection(Commonfunctions.getconstring());
SqlCommand cmd = new SqlCommand("sp_insert", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("name", name);
cmd.Parameters.AddWithValue("email",email);
cmd.Parameters.AddWithValue("city", city);
con.Open();
int i = cmd.ExecuteNonQuery();
con.Close();
if (i != 0)
{
return true;
}
else
{
return false;
}
}
public void
{
user_delete(int id)
SqlConnection con = new
SqlConnection(Commonfunctions.getconstring());
SqlCommand cmd = new SqlCommand("sp_delete", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("id", id);
con.Open();
int i = cmd.ExecuteNonQuery();
con.Close();
}
public void user_update(string name, string email,string city, int
id)
Page
37
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
{
SqlConnection con = new
SqlConnection(Commonfunctions.getconstring());
SqlCommand cmd = new SqlCommand("sp_update", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("name", name);
cmd.Parameters.AddWithValue("email",email);
cmd.Parameters.AddWithValue("city", city);
cmd.Parameters.AddWithValue("id", id);
con.Open();
int i = cmd.ExecuteNonQuery();
con.Close();
}
public DataTable getdata()
{
SqlConnection con = new SqlConnection(@"Data
Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Inte
grated Security=True;User Instance=True");
SqlCommand cmd = new SqlCommand("sp_getdata", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
return dt;
}
}
Page
38
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
3) Open your BAL_user_operation.cs File and code it like this
using
using
using
using
using
using
System;
System.Collections.Generic;
System.Linq;
System.Web;
System.Data;
System.Data.SqlClient;
/// <summary>
/// Summary description for BAL_user_operation
/// </summary>
public class BAL_user_operation
{
DAL_user_operation du = new DAL_user_operation();
public BAL_user_operation()
{
//
// TODO: Add constructor logic here
//
}
public bool user_insert(string name, string email,string city)
{
return du.user_insert(name, email,city);
}
public void user_delete(int id)
{
du.user_delete(id);
}
public void user_update(string name, string email,string city, int
id)
{
du.user_update(name, email, city, id);
}
Page
39
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
public DataTable getdata()
{
return du.getdata();
}
}
4) At last Open Your gridview_demo.aspx.cs file and code it like this
using
using
using
using
using
using
System;
System.Collections.Generic;
System.Linq;
System.Web;
System.Web.UI;
System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
BAL_user_operation bu = new BAL_user_operation();
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
refreshdata();
}
}
public void refreshdata()
{
GridView1.DataSource = bu.getdata();
GridView1.DataBind();
}
protected void GridView1_RowDeleting(object sender,
GridViewDeleteEventArgs e)
{
int id =
Convert.ToInt16(GridView1.DataKeys[e.RowIndex].Values["id"].ToString()
);
bu.user_delete(id);
refreshdata();
Page
40
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
}
protected void GridView1_RowEditing(object sender,
GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
refreshdata();
}
protected void GridView1_RowUpdating(object sender,
GridViewUpdateEventArgs e)
{
TextBox txtname =
GridView1.Rows[e.RowIndex].FindControl("TextBox1") as TextBox;
TextBox txtemail =
GridView1.Rows[e.RowIndex].FindControl("TextBox3") as TextBox;
TextBox txtcity =
GridView1.Rows[e.RowIndex].FindControl("TextBox2") as TextBox;
int id=
Convert.ToInt16(GridView1.DataKeys[e.RowIndex].Values["id"].ToString()
);
bu.user_update(txtname.Text, txtemail.Text, txtcity.Text, id);
GridView1.EditIndex = -1;
refreshdata();
}
protected void GridView1_RowCancelingEdit(object sender,
GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
refreshdata();
}
}
This is your web.config file code:
Page
41
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<connectionStrings>
<add name="dbcon" connectionString="Data
Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Inte
grated Security=True;User Instance=True"/>
</connectionStrings>
</configuration>
OUTPUT CHAMBER:
s ads a
Download the Tutorial: Bind Gridview using 3 tier
Page
42
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
Get Data from Database
Using Selected ID
INITIAL CHAMBER
Step1) Open Your Visual Studio 2010 and Create an Empty Website, Give a suitable name
[gridview_demo].
Step2) In Solution Explorer you get your empty website, then add a Web Form and SQL Server
Database. By going like this –
For Web Form
gridview_demo (Your Empty Website) -> Right Click -> Add New Item -> Web Form. Name it as > gridviewid_demo.aspx.
For SQL Server Database
gridview_demo (Your Empty Website) -> Right Click -> Add New Item -> SQL Server Database.
[Add Database inside the App_Data_folder].
DATABASE CHAMBER
Step3) In Server Explorer, Click on your Database [Database.mdf] - -> Tables - -> Add New Table
-:- Make table like this:
Table - -> t l_data [Do ’t Forget to
ake ID as I“ Ide tit -- True]
Page
43
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
Make some entries in Database by going to - - Table - -> tbl_data - -> Right Click - -> Show Table
Data. Do ’t op
e tries - - Make yours uh uh uh.
DESIGN CHAMBER
Step 4) Now make some design for your application by going to gridviewid_demo.aspx and fry
the code like this:
Page
44
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
Gridviewid_demo.aspx:
<%@ 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></title>
<style type="text/css">
.style1
{
font-size: large;
text-align: center;
}
.style2
{
width: 272px;
}
.style3
{
width: 264px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div class="style1">
<strong>Get Data From Database using Seleceted
IDs</strong></div>
<table style="width:100%;">
<tr>
<td class="style2">
</td>
<td class="style3">
</td>
<td>
</td>
</tr>
Page
45
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
<tr>
<td class="style2">
</td>
<td class="style3">
<asp:DropDownList ID="DropDownList1" runat="server"
AppendDataBoundItems="True"
AutoPostBack="True" DataTextField="id"
DataValueField="id" Height="16px"
Width="118px">
<asp:ListItem Value="0">-- Select Id-</asp:ListItem>
</asp:DropDownList>
</td>
<td>
<asp:Button ID="Button1" runat="server"
BackColor="#FFFF66"
BorderColor="#CC3300" ForeColor="#6600FF"
onclick="Button1_Click"
Text="Click Here to show the Data" />
</td>
</tr>
<tr>
<td class="style2">
</td>
<td class="style3">
</td>
<td>
</td>
</tr>
<tr>
<td class="style2">
</td>
<td class="style3">
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False"
BackColor="White" BorderColor="#336666"
BorderStyle="Double" BorderWidth="3px"
CellPadding="4" DataKeyNames="id"
GridLines="Horizontal">
<Columns>
<asp:TemplateField HeaderText="UserId">
<EditItemTemplate>
<asp:TextBox ID="TextBox2"
runat="server" Text='<%# Bind("id") %>'></asp:TextBox>
Page
46
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server"
Text='<%# Bind("id") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<EditItemTemplate>
<asp:TextBox ID="TextBox1"
runat="server" Text='<%# Bind("name") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server"
Text='<%# Bind("name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="City">
<EditItemTemplate>
<asp:TextBox ID="TextBox3"
runat="server" Text='<%# Bind("city") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server"
Text='<%# Bind("city") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="White" ForeColor="#333333"
/>
<HeaderStyle BackColor="#336666" Font-Bold="True"
ForeColor="White" />
<PagerStyle BackColor="#336666" ForeColor="White"
HorizontalAlign="Center" />
<RowStyle BackColor="White" ForeColor="#333333" />
<SelectedRowStyle BackColor="#339966" FontBold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F7F7F7" />
<SortedAscendingHeaderStyle BackColor="#487575" />
<SortedDescendingCellStyle BackColor="#E5E5E5" />
<SortedDescendingHeaderStyle BackColor="#275353"
/>
</asp:GridView>
</td>
<td>
Page
47
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
</td>
</tr>
<tr>
<td class="style2">
</td>
<td class="style3">
</td>
<td>
</td>
</tr>
</table>
</form>
</body>
</html>
Your Design will look like this:
CODE CHAMBER
Step5) No it’s ti e for ser er side odi g so that our appli atio get ork, Ope
gridviewid_demo.aspx.cs file and code it like below.
Page
48
our
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
Gridviewid_demo.aspx.cs
Do ’t forget the a espa es –
using
using
using
using
using
using
using
using
System;
System.Collections.Generic;
System.Linq;
System.Web;
System.Web.UI;
System.Web.UI.WebControls;
System.Data;
System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
SqlConnection con = new SqlConnection(@"Data
Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Inte
grated Security=True;User Instance=True") ;
SqlCommand cmd = new SqlCommand("select * from tbl_data",
con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
Page
49
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
DropDownList1.DataSource = dt;
DropDownList1.DataBind();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(@"Data
Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Inte
grated Security=True;User Instance=True");
SqlCommand cmd = new SqlCommand("select * from tbl_data where
id=" + DropDownList1.SelectedItem.Value, con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
OUTPUT CHAMBER
Check out the database, that who is ID=2, we will get ID=2 [pur i a’s data i Gridview]
Page
50
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
Page
51
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
Gridview Sorting Example
In asp.net using C#
Here in this tutorial we will deal with Sorting Event of Gridview, where we take one Gridview and
its sorting event, we write some code in that event for making name ascending and descending.
INITIAL CHAMBER
Step1) Open Your Visual Studio 2010 and Create an Empty Website, Give a suitable name
[gridviewsorting_demo].
Step2) In Solution Explorer you get your empty website, Add a web form, SQL Database. By going
like this –
For Web Form:
gridviewsorting_demo (Your Empty Website) -> Right Click -> Add New Item -> Web Form. Name
it as -> gridviewsorting_demo.aspx.
For SQL Server Database:
gridviewsorting_demo (Your Empty Website) -> Right Click -> Add New Item -> SQL Server
Database. [Add Database inside the App_Data_folder].
DATABASE CHAMBER
Step3) Get to your Database [Database.mdf], we will create a table - -> tbl_Data, Go to the
database.mdf - -> Table - -> Add New table, design your table like this:
Table - -> t l_data [Do ’t forget to
ake ID - -> Identity Specification - -> Yes]
Page
52
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
DESIGN CHAMBER
Step5) Now Open your gridviewsorting_demo.aspx file, where we create our design for
Gridview sorting.
Gridviewsorting_demo.aspx:
<%@ 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></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table style="width:100%;">
<tr>
Page
53
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
<td>
</td>
<td>
</td>
<td>
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:GridView ID="GridView1" runat="server"
AllowSorting="True"
AutoGenerateColumns="False" BackColor="White"
BorderColor="#999999"
BorderStyle="Solid" BorderWidth="1px"
CellPadding="3" DataKeyNames="id"
ForeColor="Black" GridLines="Vertical"
onsorting="GridView1_Sorting">
<AlternatingRowStyle BackColor="#CCCCCC" />
<Columns>
<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>
</asp:TemplateField>
<asp:TemplateField HeaderText="First Name"
SortExpression="fname">
<EditItemTemplate>
<asp:TextBox ID="TextBox2"
runat="server" Text='<%# Bind("fname") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2"
runat="server" Text='<%# Bind("fname") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
Page
54
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
<asp:TemplateField HeaderText="Last Name" SortExpression="lname">
<EditItemTemplate>
<asp:TextBox ID="TextBox3"
runat="server" Text='<%# Bind("lname") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3"
runat="server" Text='<%# Bind("lname") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="City"
SortExpression="city">
<EditItemTemplate>
<asp:TextBox ID="TextBox4"
runat="server" Text='<%# Bind("city") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label4"
runat="server" Text='<%# Bind("city") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#CCCCCC" />
<HeaderStyle BackColor="Black" FontBold="True" ForeColor="White" />
<PagerStyle BackColor="#999999"
ForeColor="Black" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#000099" FontBold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1"
/>
<SortedAscendingHeaderStyle
BackColor="#808080" />
<SortedDescendingCellStyle BackColor="#CAC9C9"
/>
<SortedDescendingHeaderStyle
BackColor="#383838" />
</asp:GridView>
</td>
<td>
</td>
</tr>
<tr>
Page
55
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
<td>
</td>
<td>
</td>
<td>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
Now for whom those who are using Template Field Here, You have to embed single thing into to
the code i.e. – Sort Expression – hate er the field is for like [like if it is first a e the
rite
like sort e pressio = first a e ]. See below code.
Your design look like this:
Page
56
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
CODE CHAMBER
Step6) Open your gridviewsorting_demo.aspx.cs and write some code so that our application get
work.
gridviewsorting_demo.aspx.cs
using
using
using
using
using
using
using
using
System;
System.Collections.Generic;
System.Linq;
System.Web;
System.Web.UI;
System.Web.UI.WebControls;
System.Data;
System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
Page
57
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
{
refreshdata();
}
}
public void refreshdata()
{
SqlConnection con = new SqlConnection(@"Data
Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Inte
grated Security=True;User Instance=True");
SqlCommand cmd = new SqlCommand("select * from tbl_data",
con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
ViewState["dirState"] = dt;
ViewState["sortdr"] = "Asc";
}
protected void GridView1_Sorting(object sender,
GridViewSortEventArgs e)
{
DataTable dtrslt= (DataTable)ViewState["dirState"];
if (dtrslt.Rows.Count > 0)
{
if (Convert.ToString(ViewState["sortdr"]) == "Asc")
{
dtrslt.DefaultView.Sort = e.SortExpression + "
Desc";
ViewState["sortdr"] = "Desc";
}
else
{
dtrslt.DefaultView.Sort = e.SortExpression + "
Asc";
ViewState["sortdr"] = "Asc";
}
GridView1.DataSource = dtrslt;
GridView1.DataBind();
Page
58
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
}
}
}
OUTPUT CHAMBER
Page
59
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
Bind Datagrid in WPF using C#
I this tutorial I’ll sho ou ho to i d data i Datagrid i WPF usi g C#, here e use “QL
Server 2008 for making our database and table; we will create our design for Datagrid in XAML
format and after that we will bind that Datagrid in xaml.cs file.
INITIAL CHAMBER
Step1) Open Your Visual Studio 2010, Go to File - -> New - -> Projects - -> Under Visual C# - ->
WPF Application.
Page
60
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
DESIGN CHAMBER
In the Solution Explorer there is Main Window.Xaml file is there open that. You will see something
like below image.
Here you have to drag and drop the Datagrid from the toolbox. Initially there will be no columns
in Datagrid for that you have to write this code, to make columns.
You have to write this code in below chamber where XAML is written and all code should be in
between <grid> </grid>.
Page
61
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
<Window x:Class="WpfApplication3.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<DataGrid AutoGenerateColumns="False" Height="217"
HorizontalAlignment="Left" Margin="73,33,0,0" Name="dataGrid1"
VerticalAlignment="Top" Width="364">
<DataGrid.Columns>
<DataGridTextColumn Header="ID" Width="40"
Binding="{Binding id}"></DataGridTextColumn>
<DataGridTextColumn Header="FirstName" Width="100"
Binding="{Binding fname}"></DataGridTextColumn>
<DataGridTextColumn Header="LastName" Width="100"
Binding="{Binding lname}"></DataGridTextColumn>
<DataGridTextColumn Header="City" Width="100"
Binding="{Binding city}"></DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>
Page
62
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
Your design will look like below image:
DATABASE CHAMBER
In database chamber, I had made my table in SQL Server 2008, you can take help from local
database or SQL Service based database, you have to make a table there -- Add New Table
tbl_data.
Page
63
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
After you done with table, you have to feed some data in the table otherwise you get empty
Datagrid at run time.
CODE CHAMBER
In this step right click inside the Main Window.xaml -> View Code, you will get inside the coding
part, similar to page.aspx.cs file, here the file name is Main Window.xaml.cs.
Main Window.xaml.cs
using
using
using
using
using
using
using
using
using
using
using
using
using
using
using
System;
System.Collections.Generic;
System.Linq;
System.Text;
System.Windows;
System.Windows.Controls;
System.Windows.Data;
System.Windows.Documents;
System.Windows.Input;
System.Windows.Media;
System.Windows.Media.Imaging;
System.Windows.Navigation;
System.Windows.Shapes;
System.Data;
System.Data.SqlClient;
namespace WpfApplication3
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
Page
64
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
InitializeComponent();
refreshdata();
}
public void refreshdata()
{
SqlConnection con = new SqlConnection(@"Data
Source=NiluNilesh;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("select * from tbl_data",
con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
Database1DataSet ds = new Database1DataSet();
sda.Fill(ds);
if (ds.Tables[0].Rows.Count>0)
{
dataGrid1.ItemsSource = ds.Tables[0].DefaultView;
}
con.Close();
}
}
}
OUTPUT CHAMBER
Page
65
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
Bind Grid View Control using XML
In Asp.net C#
I this arti le I’ll sho ou ho to i d grid ie o trol usi g l i stead of taki g a data ase
table, where we will embed some data into the XML file and then we call that xml for binding
purpose.
INITIAL CHAMBER
Step1) Open Your Visual Studio 2010 and Create an Empty Website, Give a suitable name
[gridview_demo].
Step2) In Solution Explorer you get your empty website, Add a web form, SQL Database and XML
file. By going like this –
For Web Form:
gridview_demo (Your Empty Website) -> Right Click -> Add New Item -> Web Form. Name it as > gridview_demo.aspx.
For SQL Server Database:
gridview_demo (Your Empty Website) -> Right Click -> Add New Item -> SQL Server Database.
[Add Database inside the App_Data_folder].
For XML File:
gridview_demo (Your Empty Website) -> Right Click -> Add New Item -> XML File.
Page
66
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
We had taken SQL Server Database here, as we have to provide the connection string for the
binding purpose. Otherwise there is no use of database as we are not using the database table,
instead of that we are using Dataset.
Here is the code of XML File
<?xml version="1.0" encoding="utf-8" ?>
<studentdetails>
<student>
<id>01</id>
<name>Nilesh</name>
<city>Rajkot</city>
</student>
<student>
<id>02</id>
<name>Purnima</name>
<city>Ahmedabad</city>
</student>
<student>
<id>03</id>
<name>Chandni</name>
<city>Mumbai</city>
</student>
<student>
<id>04</id>
<name>Rinku</name>
<city>Pune</city>
</student>
<student>
<id>05</id>
<name>Nilu</name>
<city>Delhi</city>
</student>
Page
67
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
<student>
<id>06</id>
<name>Shailesh</name>
<city>Nashik</city>
</student>
</studentdetails>
This is the student details data that we have to bind to the Gridview, so that we can see the data
at run time.
DESIGN CHAMBER
Step4) Open you gridview_demo.aspx file and write some code for designing our application.
Gridview_demo.aspx
<%@ 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></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False"
CellPadding="4" ForeColor="#333333" GridLines="None">
Page
68
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="Student 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>
</asp:TemplateField>
<asp:TemplateField HeaderText="Student Name">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server"
Text='<%# Bind("name") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server"
Text='<%# Bind("name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Student City">
<EditItemTemplate>
<asp:TextBox ID="TextBox3" runat="server"
Text='<%# Bind("city") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server"
Text='<%# Bind("city") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#990000" Font-Bold="True"
ForeColor="White" />
<HeaderStyle BackColor="#990000" Font-Bold="True"
ForeColor="White" />
<PagerStyle BackColor="#FFCC66" ForeColor="#333333"
HorizontalAlign="Center" />
<RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True"
ForeColor="Navy" />
<SortedAscendingCellStyle BackColor="#FDF5AC" />
<SortedAscendingHeaderStyle BackColor="#4D0000" />
Page
69
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
<SortedDescendingCellStyle BackColor="#FCF6C0" />
<SortedDescendingHeaderStyle BackColor="#820000" />
</asp:GridView>
</div>
</form>
</body>
</html>
Here is your design look like:
CODE CHAMBER
Step 5) In code chamber we will write some binding code so that our application show the data
from xml file to the grid view.
Page
70
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
Gridview_demo.aspx.cs:
using
using
using
using
using
using
using
using
System;
System.Collections.Generic;
System.Linq;
System.Web;
System.Web.UI;
System.Web.UI.WebControls;
System.Data;
System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
refreshdata();
}
}
public void refreshdata()
{
SqlConnection con = new SqlConnection(@"Data
Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Inte
grated Security=True;User Instance=True");
DataSet ds = new DataSet();
ds.ReadXml(Server.MapPath("XMLFile.xml"));
if (ds!= null && ds.HasChanges())
{
GridView1.DataSource=ds;
GridView1.DataBind();
}
else
{
GridView1.DataBind();
}
Page
71
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
}
}
OUTPUT CHAMBER
Page
72
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
Bind Grid View without Database
In MVC 3 C#
I this tutorial I’ll sho ou ho to i d Grid ie usi g MVC3 C# usi g Razor, here I had ’t used
any data ase, a d e a uall feed that data i to our Co troller, so it’s a ki d of Bi di g
Gridview without any database.
Step1) Open Visual Studio 2010, Go to the New Project - -> Visual C# - -> Web - -> ASP.NET MVC3
Web Application - -> Click OK.
Page
73
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
Step2) After Clicking OK, New Asp.Net MVC3 Project window will open there you have you chose
- -> Internet Application and in View Engine Dropdown - -> Chose Razor.
Step3) After Clicking OK, you will see something like below image in your Solution Explorer, You
need to look out for Model, Controller and View Folders, which are the main files in MVC, others
are too but these are main files.
Page
74
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
In Model
Step4) Right Click on Models - - -> Add New Item - -> Add a Class File [Class.cs]- -> Name it as
Student.cs. Write Code in Student.cs file.
Student.cs
using
using
using
using
System;
System.Collections.Generic;
System.Linq;
System.Web;
namespace MvcApplication1.Models
Page
75
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
{
public class Students
{
public Int32 Std_ID { get; set; }
public string Std_Name { get; set; }
public string Std_City { get; set; }
}
}
In Controller
Step5) Open Controller, inside there HomeController.cs files is there, Open that - -> and write
ode like this. Do ’t forget to add a espa e of odel.
HomeController.cs
using
using
using
using
using
using
System;
System.Collections.Generic;
System.Linq;
System.Web;
System.Web.Mvc;
MvcApplication4.Models;
namespace MvcApplication4.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
Students stdnt = new Students();
List<Students> stdnt1 = new List<Students>();
stdnt.Std_ID = 1;
stdnt.Std_Name = "Nilesh";
stdnt.Std_City = "Rajkot";
Page
76
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
stdnt1.Add(stdnt);
stdnt = new Students();
stdnt.Std_ID = 2;
stdnt.Std_Name = "Purnima";
stdnt.Std_City = "Ahmedabad";
stdnt1.Add(stdnt);
stdnt = new Students();
stdnt.Std_ID = 3;
stdnt.Std_Name = "Rinku";
stdnt.Std_City = "Pune";
stdnt1.Add(stdnt);
stdnt = new Students();
stdnt.Std_ID = 4;
stdnt.Std_Name = "Chandni";
stdnt.Std_City = "Chennai";
stdnt1.Add(stdnt);
stdnt = new Students();
stdnt.Std_ID = 5;
stdnt.Std_Name = "Indrajeet";
stdnt.Std_City = "Mumbai";
stdnt1.Add(stdnt);
stdnt = new Students();
stdnt.Std_ID = 6;
stdnt.Std_Name = "Suhag";
stdnt.Std_City = "Mysore";
stdnt1.Add(stdnt);
var data = stdnt1;
return View(data);
Page
77
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
}
public ActionResult About()
{
return View();
}
}
}
In View
Step6) Open View Folder, inside their Home folder is there, Open the Index.cshtml file and
write code like this.
Index.cshtml
@model IEnumerable<MvcApplication1.Models.Students>
@{
ViewBag.Title = "Home Page";
WebGrid grid = new WebGrid(Model);
}
<h2>Binding Gridview in MVC3</h2>
<p>
This is my First Binding Tutorial of Gridview in MVC3
</p>
@grid.GetHtml(columns: new[]
{
grid.Column("Std_ID"),
grid.Column("Std_Name"),
grid.Column("Std_City")
Page
78
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
})
OUTPUT CHAMBER
Page
79
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
Bind Grid View with Database
In MVC 5 C#
I this tutorial I’ll sho ou ho to i d Grid ie usi g MVC5 C# usi g Razor, I pre ious tutorial
I ha e ’t used a data ase, but here we will use and then we manually feed some data into our
ta le a d i d that data to Grid ie . “o it’s a ki d of Bi di g Grid ie
ith data ase.
Step1) Open Visual Studio 2010, Go to the New Project - -> Visual C# - -> Web - -> ASP.NET MVC
Web Application - -> Click OK.
Page
80
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
Step2) After Clicking OK, New Asp.Net MVC5 Project window will open there you have you chose
- > MVC and Press OK.
Step3) After Clicking OK, you will see something like below image in your Solution Explorer, You
need to look out for Model, Controller and View Folders that are the main files in MVC, others
are too but these are main files.
Page
81
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
DATABASE CHAMBER:
Step4) Right Click on your Project - -> Add New Item - -> SQL Server Database and Add it. Get to
your Database resides in Server Explorer - - [Database.mdf], we will create a table - -> tbl_data,
Go to the Database.mdf - -> Table - -> Add New table; design your table like this:
Page
82
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
Web.config File:
<connectionStrings>
<add name="DefaultConnection" connectionString="Data
Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnetMVCBindGridView-20150920090324.mdf;Initial Catalog=aspnet-MVCBindGridView20150920090324;Integrated Security=True"
providerName="System.Data.SqlClient" />
<add name="StudentContext" connectionString="Data
Source=NiluNilesh;Initial Catalog=mynewdata;Integrated Security=True"
providerName="System.Data.SqlClient"></add>
</connectionStrings>
In Model
Step4) Right Click on Models - - -> Add New Item - -> Add a Class File [Class.cs]- -> Name it as
Student.cs. Write Code in Student.cs file.
Page
83
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
Student.cs
using
using
using
using
using
using
System;
System.Collections.Generic;
System.Linq;
System.Web;
System.ComponentModel.DataAnnotations;
System.ComponentModel.DataAnnotations.Schema;
namespace MVCBindGridView.Models
{
[Table("tbl_data")]
public class Student
{
[Key]
public int id { get; set; }
public string name { get; set; }
public string city { get; set; }
}
}
Add another Class file to Model name it as – “StudentContext”.
StudentContext.cs
using
using
using
using
using
System;
System.Collections.Generic;
System.Linq;
System.Web;
System.Data.Entity;
namespace MVCBindGridView.Models
{
public class StudentContext : DbContext
{
public DbSet<Student> student { get; set; }
}
}
Page
84
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
In Controller
Step5) Right Click on Controller, Add Empty Controller, Name it – StudentController.cs. Write
ode like this. Do ’t forget to add a espa e of odel.
using
using
using
using
using
using
System;
System.Collections.Generic;
System.Linq;
System.Web;
System.Web.Mvc;
MVCBindGridView.Models;
namespace MVCBindGridView.Controllers
{
public class StudentController : Controller
{
// GET: Student
public ActionResult Index()
{
StudentContext stdntcntxt = new StudentContext();
var data = stdntcntxt.student;
return View(data.ToList());
}
}
}
In View
Step6) Right Click on Index () method - - Add View and do like below image.
Page
85
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
You will see under view - - there is a folder named student created and inside that folder get your
index.cshtml. Write code like this.
Index.cshtml
@model IEnumerable<MVCBindGridView.Models.Student>
@{
ViewBag.Title = "Bind Gridview with Database";
WebGrid grid = new WebGrid(Model);
}
<h2>Bind GridView in MVC5 with Database</h2>
@grid.GetHtml(columns: new[]
{
grid.Column("id"),
Page
86
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
grid.Column("name"),
grid.Column("city")
})
OUTPUT CHAMBER
Page
87
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
CRUD operation of Dropdownlist
Inside Gridview in asp.net
I this tutorial I’ll sho ou ho to use dropdo
list i side Grid ie , a d ho
update, and delete operation on each field along with dropdown list.
to
ake edit,
INITIAL CHAMBER:
Step1) Open Your Visual Studio 2010 and Create an Empty Website, Give a suitable name
[gridview_demo].
Step2) In Solution Explorer you get your empty website, Add a web form, SQL Database. By going
like this –
For Web Form:
gridview_demo (Your Empty Website) -> Right Click -> Add New Item -> Web Form. Name it as >gridview_demo.aspx.
For SQL Server Database:
gridview_demo (Your Empty Website) -> Right Click -> Add New Item -> SQL Server Database.
[Add Database inside the App_Data_folder].
Page
88
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
DATABASE CHAMBER
Step3) Get to your Database [Database.mdf], we will create a table - -> tbl_Data, Go to the
database.mdf - -> Table - -> Add New table, design your table like this:
Table - -> t l_data [Do ’t forget to
ake ID - -> Identity Specification - -> Yes]
DESIGN CHAMBER
Step5) Now Open your gridview_demo.aspx file, where we create our design for binding and
making edit, delete, and update operation with Dropdownlist.
Page
89
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
Gridview_demo.aspx:
<%@ 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></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False"
AutoGenerateDeleteButton="True"
AutoGenerateEditButton="True" DataKeyNames="id"
onrowcancelingedit="GridView1_RowCancelingEdit"
onrowdeleting="GridView1_RowDeleting"
onrowediting="GridView1_RowEditing"
onrowupdating="GridView1_RowUpdating" BackColor="White"
BorderColor="White" BorderStyle="Ridge" BorderWidth="2px"
CellPadding="3"
CellSpacing="1" GridLines="None">
<Columns>
<asp:TemplateField HeaderText="Name">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server"
Text='<%# Bind("name") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server"
Text='<%# Bind("name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Email">
<EditItemTemplate>
Page
90
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
<asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("email")
%>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server"
Text='<%# Bind("email") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Gender">
<EditItemTemplate>
<asp:DropDownList ID="DropDownList2"
runat="server"
SelectedValue='<%# Bind("gender") %>'>
<asp:ListItem>--Select Gender-</asp:ListItem>
<asp:ListItem>Male</asp:ListItem>
<asp:ListItem>Female</asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label4" runat="server"
Text='<%# Bind("gender") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#C6C3C6" ForeColor="Black" />
<HeaderStyle BackColor="#4A3C8C" Font-Bold="True"
ForeColor="#E7E7FF" />
<PagerStyle BackColor="#C6C3C6" ForeColor="Black"
HorizontalAlign="Right" />
<RowStyle BackColor="#DEDFDE" ForeColor="Black" />
<SelectedRowStyle BackColor="#9471DE" Font-Bold="True"
ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#594B9C" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#33276A" />
</asp:GridView>
</div>
Page
91
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
</form>
</body>
</html>
Your design look like this:
You have to look around this Property in Gridview:
1) DataKeysNames: id
2) Auto Generate Delete Button: True
3) Auto Generate Edit Button : True
In Events: [Make Double Click in each events shown below to go to the code]
1)
2)
3)
4)
Row Canceling Edit
Row Deleting
Row Editing
Row Updating
Page
92
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
CODE CHAMBER
Step6) Open your gridview_demo.aspx.cs and write some code so that our application get work.
using
using
using
using
using
using
using
using
System;
System.Collections.Generic;
System.Linq;
System.Web;
System.Web.UI;
System.Web.UI.WebControls;
System.Data.SqlClient;
System.Data;
public partial class _Default : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(@"Data
Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Inte
grated Security=True;User Instance=True");
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
refreshdata();
Page
93
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
}
}
public void refreshdata()
{
SqlCommand cmd = new SqlCommand("select * from tbl_data",
con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void GridView1_RowEditing(object sender,
GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
refreshdata();
}
protected void GridView1_RowDeleting(object sender,
GridViewDeleteEventArgs e)
{
int id =
Convert.ToInt16(GridView1.DataKeys[e.RowIndex].Values["id"].ToString()
);
SqlCommand cmd = new SqlCommand("delete from tbl_data where id
= @id", con);
cmd.Parameters.AddWithValue("@id", id);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
refreshdata();
}
protected void GridView1_RowCancelingEdit(object sender,
GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
refreshdata();
}
Page
94
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
protected void GridView1_RowUpdating(object sender,
GridViewUpdateEventArgs e)
{
int id =
Convert.ToInt16(GridView1.DataKeys[e.RowIndex].Values["id"].ToString()
);
TextBox txtname =
GridView1.Rows[e.RowIndex].FindControl("TextBox2") as TextBox;
TextBox txtemail =
GridView1.Rows[e.RowIndex].FindControl("TextBox3") as TextBox;
DropDownList drpgender =
GridView1.Rows[e.RowIndex].FindControl("DropDownList2") as
DropDownList;
SqlCommand cmd = new SqlCommand("update tbl_data set
name=@name, email=@email,gender=@gender where id =@id", con);
cmd.Parameters.AddWithValue("@name", txtname.Text);
cmd.Parameters.AddWithValue("@email", txtemail.Text);
cmd.Parameters.AddWithValue("@gender",
drpgender.SelectedItem.Text);
cmd.Parameters.AddWithValue("@id", id);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
refreshdata();
}
}
Page
95
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
OUTPUT CHAMBER
Update:
Page
96
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
Show table Data:
Page
97
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
How to export grid view to Excel
Using ItextSharp library
I this Arti le I’ll sho ou a out ho to e port grid ie to E el Do u e t t using ItextSharp
Library in asp.net c#, were we take one grid view that have some field, then we export that grid
view in Excel document using ItextSharp library. This article is really very similar my previous
article were I explain how to export grid view to Word Document.
INITIAL CHAMBER
Step1) Open Your Visual Studio 2010 and Create an Empty Website, Give a suitable name
[gridviewexcel_demo].
Step2) In Solution Explorer you get your empty website, then add a Web Form and SQL Server
Database. By going like this –
For Web Form:
gridviewexcel_demo (Your Empty Website) -> Right Click -> Add New Item -> Web Form. Name
it as -> gridviewexcel_demo.aspx.
For SQL Server Database:
gridviewexcel_demo (Your Empty Website) -> Right Click -> Add New Item -> SQL Server
Database. [Add Database inside the App_Data_folder].
Page
98
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
DATABASE CHAMBER
Step3) In Server Explorer, Click on your Database [Database.mdf] - -> Tables - -> Add New Table
-:- Make table like this:
Table - -> t l_data [Do ’t Forget to
ake ID as IS Ide tity -- True]
DESIGN CHAMBER
Step 4) Now make some design for your application by going to gridviewexcel_demo.aspx and
fry the code like this:
<%@ 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">
Page
99
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
AutoGenerateColumns="False" BackColor="White"
BorderColor="#999999"
BorderStyle="None" BorderWidth="1px" CellPadding="3"
DataKeyNames="id"
GridLines="Vertical"
onpageindexchanging="GridView1_PageIndexChanging1"
PageSize="5">
<AlternatingRowStyle BackColor="#DCDCDC" />
<Columns>
<asp:TemplateField HeaderText="Name">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"
Text='<%# Bind("name") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server"
Text='<%# Bind("name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Education">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server"
Text='<%# Bind("education") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server"
Text='<%# Bind("education") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Email">
<EditItemTemplate>
<asp:TextBox ID="TextBox3" runat="server"
Text='<%# Bind("email") %>'></asp:TextBox>
Page
100
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server"
Text='<%# Bind("email") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Location">
<EditItemTemplate>
<asp:TextBox ID="TextBox4" runat="server"
Text='<%# Bind("location") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label4" runat="server"
Text='<%# Bind("location") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#CCCCCC" ForeColor="Black" />
<HeaderStyle BackColor="#000084" Font-Bold="True"
ForeColor="White" />
<PagerStyle BackColor="#999999" ForeColor="Black"
HorizontalAlign="Center" />
<RowStyle BackColor="#EEEEEE" ForeColor="Black" />
<SelectedRowStyle BackColor="#008A8C" Font-Bold="True"
ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#0000A9" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#000065" />
</asp:GridView>
<br />
<br />
</div>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click1"
Text="Export To PDF" />
</form>
</body>
</html>
Page
101
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
Your design would look like this:
You can show paging by going to Gridview properties [Press F4] - -> find - - Allow Paging – Make
it - - True. Here I made page size to – 5, you can select page size as per your data.
Page
102
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
CODE CHAMBER
Before this coding part you need to download ItextSharp library from the souceforge website,
here is the link just download the file, the file is in zip format so just unzipped the files at
suitable location, so that we can easily browse it.
Itextsharp Library download - - itextsharp-all-5.5.6
After you download the file, you check this out that you download the right file or not, look at
below image.
Page
103
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
Step5) No it’s ti e for ser er side odi g so that our appli atio get
gridviewexcel_demo.aspx.cs file and code it like below.
ork, Ope
our
You first have to import the dll of ItextSharp by going to your empty website
[gridviewexcel_demo] - - Right Click - - > Add References.
Page
104
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
Now Browse the ItextSharp unzip file and Open it up, Make sure you got all unzip dll files into
your application. See below image to know what .dll you have to import.
Now import these namespaces, as it will needed when we write code for exporting the Gridview
to excel.
It’s ti e for ode, first e i d the grid ie , tha e ake ode for pagi g usi g the Gridview
event – OnPageIndexChanging, then we will write code for exporting grid view to Excel
document on button click.
Page
105
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
using
using
using
using
using
using
using
using
using
using
using
using
using
using
System;
System.Collections.Generic;
System.Linq;
System.Web;
System.Web.UI;
System.Web.UI.WebControls;
System.Data;
System.Data.SqlClient;
System.IO;
System.Text;
iTextSharp.text;
iTextSharp.text.html;
iTextSharp.text.html.simpleparser;
iTextSharp.text.pdf;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
refreshdata();
}
}
// Bind the gridview here
public void refreshdata()
{
SqlConnection con = new SqlConnection(@"Data
Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Inte
grated Security=True;User Instance=True");
SqlCommand cmd = new SqlCommand("select * from tbl_data",
con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
Page
106
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
}
// Gridview Paging code here
protected void GridView1_PageIndexChanging1(object sender,
GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
refreshdata();
}
// Exporting Gridview to pdf code here
protected void Button1_Click1(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("content-disposition",
"attachment;filename=GridViewExport.xls");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter swr = new StringWriter();
HtmlTextWriter htmlwr = new HtmlTextWriter(swr);
GridView1.AllowPaging = false;
refreshdata();
GridView1.RenderControl(htmlwr);
Response.Output.Write(swr.ToString());
Response.Flush();
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
}
}
Page
107
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
When you run your code, it will run perfectly, but when you click on the button you will stuck
with this error, this error generally occurs when we are exporting Gridview to word, excel, pdf
because compiler think that the control is not added to the form.
To solve this problem we just embed a code below the Button_click event like this.
Now run your code, it works perfect.
OUTPUT CHAMBER
Page
108
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
Page
109
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
Export selected data from Gridview
In Excel in asp.net using C#
I this tutorial I’ll sho ou ho
Library in asp.net using C#.
e port sele ted data fro
Grid ie
i e el usi g Ite t“harp
INITIAL CHAMBER:
Step1) Open Your Visual Studio 2010 and Create an Empty Website, Give a suitable name
[gridviewexcel_demo].
Step2) In Solution Explorer you get your empty website, then add a Web Form and SQL Server
Database. By going like this –
For Web Form:
gridviewexcel_demo (Your Empty Website) -> Right Click -> Add New Item -> Web Form. Name
it as -> gridviewexcel_demo.aspx.
For SQL Server Database:
gridviewexcel_demo (Your Empty Website) -> Right Click -> Add New Item -> SQL Server
Database. [Add Database inside the App_Data_folder].
Page
110
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
DATABASE CHAMBER
Step3) In Server Explorer, Click on your Database [Database.mdf] - -> Tables - -> Add New Table
-:- Make table like this:
Table - -> t l_data [Do ’t Forget to
ake ID as IS Ide tity -- True]
DESIGN CHAMBER
Step 4) Now make some design for your application by going to gridviewexcel_demo.aspx and
fry the code like this:
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="Default.aspx.cs" EnableEventValidation = "false"
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></title>
</head>
<body>
<form id="form1" runat="server">
Page
111
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
<div>
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False"
CellPadding="4" ForeColor="#333333" GridLines="None">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="Checkbox1"
</ItemTemplate>
runat="server" />
</asp:TemplateField>
Text='<%#
Text='<%#
Text='<%#
Text='<%#
<asp:TemplateField HeaderText="ID">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"
Bind("id") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server"
Bind("id") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server"
Bind("name") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server"
Bind("name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="City">
<EditItemTemplate>
Page
112
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
<asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("city")
%>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server"
Text='<%# Bind("city") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#990000" Font-Bold="True"
ForeColor="White" />
<HeaderStyle BackColor="#990000" Font-Bold="True"
ForeColor="White" />
<PagerStyle BackColor="#FFCC66" ForeColor="#333333"
HorizontalAlign="Center" />
<RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True"
ForeColor="Navy" />
<SortedAscendingCellStyle BackColor="#FDF5AC" />
<SortedAscendingHeaderStyle BackColor="#4D0000" />
<SortedDescendingCellStyle BackColor="#FCF6C0" />
<SortedDescendingHeaderStyle BackColor="#820000" />
</asp:GridView>
<br />
</div>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click"
Text="Export to Excel" />
</form>
</body>
</html>
You’re Desig Look like this:
Page
113
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
CODE CHAMBER
Before this coding part you need to download iTextsharp library from the souceforge website,
here is the link just download the file, the file is in zip format so just unzipped the files at
suitable location, so that we can easily browse it.
Itextsharp Library download - - itextsharp-all-5.5.6
Page
114
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
After you download the file, you check this out that you download the right file or not, look at
below image.
Step5) Now it’s ti e for ser er side odi g so that our appli atio
gridviewexcel_demo.aspx.cs file and code it like below.
get
ork, Ope
our
You first have to import the dll of ItextSharp by going to your empty website
[gridviewexcel_demo] - - Right Click - - > Add Refrences.
Page
115
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
Now Browse the ItextSharp unzip file and Open it up, Make sure you got all unzip dll files into
your application. See below image to know what .dll you have to import.
Now import these namespaces, as it will needed when we write code for exporting the Gridview
to excel.
Page
116
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
using
using
using
using
using
using
using
using
using
using
using
using
using
using
System;
System.Collections.Generic;
System.Linq;
System.Web;
System.Web.UI;
System.Web.UI.WebControls;
System.Data;
System.Data.SqlClient;
System.IO;
System.Text;
iTextSharp.text;
iTextSharp.text.html;
iTextSharp.text.html.simpleparser;
iTextSharp.text.pdf;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
refreshdata();
}
}
public void refreshdata()
{
SqlConnection con = new SqlConnection(@"Data
Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Inte
grated Security=True;User Instance=True");
SqlCommand cmd = new SqlCommand("select * from tbl_data",
con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
Page
117
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
protected void Button1_Click(object sender, EventArgs e)
{
bool isselected = false;
foreach (GridViewRow gvrow in GridView1.Rows)
{
CheckBox chck = gvrow.FindControl("Checkbox1") as
CheckBox;
if (chck != null && chck.Checked)
{
isselected = true;
break;
}
}
if (isselected)
{
GridView grdxport = GridView1;
grdxport.Columns[0].Visible = false;
foreach (GridViewRow gvrow in GridView1.Rows)
{
grdxport.Rows[gvrow.RowIndex].Visible = false;
CheckBox chck = gvrow.FindControl("Checkbox1") as
CheckBox;
if (chck != null && chck.Checked)
{
grdxport.Rows[gvrow.RowIndex].Visible = true;
}
}
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition",
"attachment;filename=GridViewExport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter swr = new StringWriter();
HtmlTextWriter htmlwtr = new HtmlTextWriter(swr);
grdxport.RenderControl(htmlwtr);
Response.Output.Write(swr.ToString());
Page
118
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
Response.End();
}
}
public override void VerifyRenderingInServerForm(Control
control)
{
}
}
OUTPUT CHAMBER
Page
119
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
In Excel Sheet:
Page
120
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
Bind Gridview with MS Access Database
In Asp.Net C#
I this tutorial I’ll sho ou ho to i d Grid ie
ith M“ A ess Data ase i asp. et usi g C#,
where we make our database in MS Access and bind that data to our Gridview.
INITIAL CHAMBER
Step1) Open Your Visual Studio 2010 and Create an Empty Website, Give a suitable name
[gridview_demo].
Step2) In Solution Explorer you get your empty website, Add a web form, by going like this –
For Web Form:
gridview_demo (Your Empty Website) -> Right Click -> Add New Item -> Web Form. Name it as >gridview_demo.aspx.
DATABASE CHAMBER
Here open your MS Access 2007 or whatever version you have, click on Blank Database. - ->
Create.
Page
121
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
After Creating Database, In the left pane you see your default table-- > right Click on that table
and - -> Design View, Here in Design view we will add some entity to our table.
Page
122
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
When you get complete with this design, again go to the table [tbl_data], Right Click and - - ->
Click on Datasheet View. Feed some data in those fields, so that we can bind our data.
Creating Connection between MS Access and Visual Studio
Open your Visual Studio - -> In Server Explorer - - > Connect to Database - - -> Add Connection
window will open like below image.
Page
123
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
Click on Change you get new window of - -> Change Data Source, like below image.
Page
124
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
Here you see Microsoft Access Database in been taken, because we have access database, for
that we have changed the connection, after that you have to browse the database of Access that
you saved, browse it - - -> test Connection - -> if it says Test Connection Succeeded, than you
can go ahead with the other process, otherwise you have to repeat the process.
DESIGN CHAMBER
Step5) Now Open your gridview_demo.aspx file, where we create our design for binding
Gridview
Page
125
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
Gridview_demo.aspx:
<%@ 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></title>
<style type="text/css">
.style1
{
text-decoration: underline;
color: #0000FF;
font-size: large;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<span class="style1"><strong>Gridview Databind using MS Access
Database</strong></span><br />
<br />
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False"
DataKeyNames="id" BackColor="White" BorderColor="White"
BorderStyle="Ridge" BorderWidth="2px" CellPadding="3"
CellSpacing="1"
GridLines="None">
<Columns>
<asp:TemplateField HeaderText="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>
</asp:TemplateField>
<asp:TemplateField HeaderText="First Name">
Page
126
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%#
Bind("fname") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%#
Bind("fname") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Last Name">
<EditItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" Text='<%#
Bind("lname") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%#
Bind("lname") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="City">
<EditItemTemplate>
<asp:TextBox ID="TextBox4" runat="server" Text='<%#
Bind("city") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%#
Bind("city") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#C6C3C6" ForeColor="Black" />
<HeaderStyle BackColor="#4A3C8C" Font-Bold="True"
ForeColor="#E7E7FF" />
<PagerStyle BackColor="#C6C3C6" ForeColor="Black"
HorizontalAlign="Right" />
<RowStyle BackColor="#DEDFDE" ForeColor="Black" />
<SelectedRowStyle BackColor="#9471DE" Font-Bold="True"
ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#594B9C" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#33276A" />
</asp:GridView>
</div>
</form>
</body>
</html>
Page
127
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
Your design will look like this:
CODE CHAMBER
Step6) Open your gridview_demo.aspx.cs and write some code so that our application get
work.
Gridview_demo.cs:
using
using
using
using
using
using
using
using
System;
System.Collections.Generic;
System.Linq;
System.Web;
System.Web.UI;
System.Web.UI.WebControls;
System.Data;
System.Data.OleDb;
public partial class _Default : System.Web.UI.Page
{
Page
128
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
refreshdata();
}
}
public void refreshdata()
{
OleDbConnection con = new
OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data
Source=C:\Users\nilu\Desktop\Database1.accdb");
OleDbCommand cmd = new OleDbCommand("select * from tbl_data",con);
OleDbDataAdapter olda = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
olda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
OUTPUT CHAMBER
Page
129
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
Insert Images into DataGridView
In Windows Application
I this tutorial I’ll sho ou ho to i sert i ages i to Datagrid i Wi dows Application using C#,
where we use PictureBox control to add pictures and then that picture will get insert into
DataGridView.
INITIAL CHAMBER
Step1) Open Your Visual Studio 2010, Go to File - -> New - -> Projects - -> Under Visual C# - ->
Windows.
Page
130
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
You can change the name of the project and you can browse your project to different location
too. And then press – OK.
DESIGN CHAMBER
Step5) Now open your Form1.cs file, where we create our design for DataGridView and Picture
Image Control. We will drag PictureBox, a button, and a DataGridView from toolbox to Form1.cs.
You will see your Form look like this.
Form1.cs [Design]:
CODE CHAMBER
Right Click on the blank part of Form1.cs - -> View Code. You will see you are entered in the code
part of the form. Write Below code for Form1.cs
Page
131
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace WindowsFormsApplication4
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void pictureBox1_Click(object sender, EventArgs e)
{
OpenFileDialog opnfd = new OpenFileDialog();
opnfd.Filter = "Image Files
(*.jpg;*.jpeg;.*.gif;)|*.jpg;*.jpeg;.*.gif";
if (opnfd.ShowDialog() == DialogResult.OK)
{
pictureBox1.Image = new Bitmap(opnfd.FileName);
}
}
private void button1_Click(object sender, EventArgs e)
{
MemoryStream mmst = new MemoryStream();
pictureBox1.Image.Save(mmst, pictureBox1.Image.RawFormat);
byte[] img = mmst.ToArray();
dataGridView1.Rows.Add(img);
}
private void Form1_Load(object sender, EventArgs e)
{
Page
132
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
DataGridViewImageColumn dgvimgcol = new DataGridViewImageColumn();
dgvimgcol.HeaderText = "Uploaded Image";
dgvimgcol.ImageLayout = DataGridViewImageCellLayout.Stretch;
dataGridView1.Columns.Add(dgvimgcol);
dataGridView1.RowTemplate.Height = 250;
dataGridView1.AllowUserToAddRows = false;
}
}
}
OUTPUT CHAMBER
Page
133
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
Validation inside Gridview in asp.net
I this tutorial I’ll sho ou ho to use alidatio i side Grid ie i asp. et, here e use edit
operation on our Template field to check our Validation.
INITIAL CHAMBER
Step1) Open Your Visual Studio 2010 and Create an Empty Website, Give a suitable name
[gridview_demo].
Step2) In Solution Explorer you get your empty website, Add a web form, SQL Database. By going
like this –
For Web Form:
gridview_demo (Your Empty Website) -> Right Click -> Add New Item -> Web Form. Name it as >gridview_demo.aspx.
For SQL Server Database:
gridview_demo (Your Empty Website) -> Right Click -> Add New Item -> SQL Server Database.
[Add Database inside the App_Data_folder].
DATABASE CHAMBER
Step3) Get to your Database [Database.mdf], we will create a table - -> tbl_Data, Go to the
database.mdf - -> Table - -> Add New table, design your table like this:
Page
134
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
Table - -> t l_data [Do ’t forget to
ake ID - -> Identity Specification - -> Yes]
DESIGN CHAMBER
Step5) Now Open your gridview_demo.aspx file, where we create our design for binding and
making edit operation and place our validation control.
Gridview_demo.aspx:
<%@ 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></title>
<style type="text/css">
.style1 {
text-decoration: underline;
}
</style>
</head>
<body>
<form id="form1" runat="server">
Page
135
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
<div>
<span class="style1"><strong>Gridview Demo with DropDownlist<br />
</strong></span><br />
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False"
AutoGenerateDeleteButton="True" AutoGenerateEditButton="True"
DataKeyNames="id"
onrowcancelingedit="GridView1_RowCancelingEdit"
onrowdeleting="GridView1_RowDeleting"
onrowediting="GridView1_RowEditing"
onrowupdating="GridView1_RowUpdating" BackColor="White"
BorderColor="White" BorderStyle="Ridge" BorderWidth="2px"
CellPadding="3"
CellSpacing="1" GridLines="None">
<Columns>
<asp:TemplateField HeaderText="Name">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%#
Bind("name") %>'></asp:TextBox>
<asp:RequiredFieldValidator
ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox2"
ForeColor="Red" ErrorMessage="Name Field can't be
blanked"></asp:RequiredFieldValidator>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%#
Bind("name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Email">
<EditItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" Text='<%#
Bind("email") %>'></asp:TextBox>
<asp:RequiredFieldValidator
ID="RequiredFieldValidator2" runat="server" ControlToValidate="TextBox3"
ForeColor="Red" ErrorMessage="Email Field can't be
blanked"></asp:RequiredFieldValidator>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%#
Bind("email") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Sport">
<EditItemTemplate>
Page
136
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
<asp:DropDownList ID="DropDownList2" DataTextField="sport"
DataValueField="sport" AppendDataBoundItems="True" runat="server"
SelectedValue='<%# Bind("sport") %>'>
<asp:ListItem>--Select Sport--</asp:ListItem>
<asp:ListItem Value="Volleyball"></asp:ListItem>
<asp:ListItem Value="Basketball"></asp:ListItem>
<asp:ListItem Value="Cricket"></asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator
ID="RequiredFieldValidator3" runat="server" InitialValue="--Select Sport--"
ControlToValidate="DropDownList2" ForeColor="Red" ErrorMessage=" Sport field
is required
"></asp:RequiredFieldValidator>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%#
Bind("sport") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#C6C3C6" ForeColor="Black" />
<HeaderStyle BackColor="#4A3C8C" Font-Bold="True"
ForeColor="#E7E7FF" />
<PagerStyle BackColor="#C6C3C6" ForeColor="Black"
HorizontalAlign="Right" />
<RowStyle BackColor="#DEDFDE" ForeColor="Black" />
<SelectedRowStyle BackColor="#9471DE" Font-Bold="True"
ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#594B9C" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#33276A" />
</asp:GridView>
<asp:ValidationSummary ID="ValidationSummary1" ForeColor="Red"
runat="server" />
</div>
</form>
</body>
</html>
Page
137
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
CODE CHAMBER
Step6) Open your gridview_demo.aspx.cs and write some code so that our application get work.
using
using
using
using
using
using
using
using
System;
System.Collections.Generic;
System.Linq;
System.Web;
System.Web.UI;
System.Web.UI.WebControls;
System.Data.SqlClient;
System.Data;
public partial class _Default : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(@"Data
Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated
Security=True;User Instance=True");
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
refreshdata();
}
}
public void refreshdata()
{
SqlCommand cmd = new SqlCommand("select * from tbl_data", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs
e)
{
GridView1.EditIndex = e.NewEditIndex;
refreshdata();
}
Page
138
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
protected void GridView1_RowDeleting(object sender,
GridViewDeleteEventArgs e)
{
int id =
Convert.ToInt16(GridView1.DataKeys[e.RowIndex].Values["id"].ToString());
SqlCommand cmd = new SqlCommand("delete from tbl_data where id =
@id", con);
cmd.Parameters.AddWithValue("@id", id);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
refreshdata();
}
protected void GridView1_RowCancelingEdit(object sender,
GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
refreshdata();
}
protected void GridView1_RowUpdating(object sender,
GridViewUpdateEventArgs e)
{
int id =
Convert.ToInt16(GridView1.DataKeys[e.RowIndex].Values["id"].ToString());
TextBox txtname = GridView1.Rows[e.RowIndex].FindControl("TextBox2")
as TextBox;
TextBox txtemail = GridView1.Rows[e.RowIndex].FindControl("TextBox3")
as TextBox;
DropDownList drpsport =
GridView1.Rows[e.RowIndex].FindControl("DropDownList2") as DropDownList;
SqlCommand cmd = new SqlCommand("update tbl_data set name=@name,
email=@email,sport=@sport where id =@id", con);
cmd.Parameters.AddWithValue("@name", txtname.Text);
cmd.Parameters.AddWithValue("@email", txtemail.Text);
cmd.Parameters.AddWithValue("@sport", drpsport.SelectedItem.Text);
cmd.Parameters.AddWithValue("@id", id);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
refreshdata();
}
}
Page
139
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
OUTPUT CHAMBER
Validation with Textbox:
Validation with Dropdownlist:
Page
140
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
Bound Control Demo in Asp.Net
I this Arti le I’ll sho ou a out Bou d Co trol i Grid Vie usi g Asp. et C# here e
select query and you will see your output your result inside grid view.
ake a
INITIAL CHAMBER
Step1) Open Your Visual Studio 2010 and Create an Empty Website, Give a suitable name
[BoundControl_demo].
Step2) In Solution Explorer you get your empty website, Add a web form and SQL Database. By
going like this –
For Web Form:
BoundControl_demo (Your Empty Website) -> Right Click -> Add New Item -> Web Form. Name
it as -> BoundControl_demo.aspx.
For SQL Server Database:
BoundControl _demo (Your Empty Website) -> Right Click -> Add New Item -> SQL Server
Database. [Add Database inside the App_Data_folder].
DATABASE CHAMBER
Step3) In Server Explorer, Click on your Database [Database.mdf] - -> Tables - -> Add New Table
Page
141
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
-:- Make table like this:
Table - -> tbl_data [Do ’t Forget to
ake ID as I“ Ide tit -- True]
DESIGN CODE
Step6) Ope
Application:
our Bou dCo trol_de o.asp file fro
solutio E plorer a d start desig
ou’re
Here is the Code:
<body>
<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
CellPadding="4"
DataSourceID="SqlDataSource1" ForeColor="#333333" GridLines="None">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="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>
</asp:TemplateField>
Page
142
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
<asp:TemplateField HeaderText="Name">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%#
Bind("name") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%#
Bind("name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="City">
<EditItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" Text='<%#
Bind("city") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%#
Bind("city") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#7C6F57" />
<FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White"
/>
<HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White"
/>
<PagerStyle BackColor="#666666" ForeColor="White"
HorizontalAlign="Center" />
<RowStyle BackColor="#E3EAEB" />
<SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True"
ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F8FAFA" />
<SortedAscendingHeaderStyle BackColor="#246B61" />
<SortedDescendingCellStyle BackColor="#D4DFE1" />
<SortedDescendingHeaderStyle BackColor="#15524A" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
DeleteCommand="INSERT INTO tbl_data(id, name, city) VALUES (5, Keyur,
Pune)"
SelectCommand="SELECT * FROM [tbl_data] ">
</asp:SqlDataSource>
<div>
</div>
</form>
</body>
Page
143
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
Besides this if ou do ’t a t to go ith ode tha ou a
a uall add the thi g
your Toolbox - -> Data - -> Gridview - -> Drag it into the .aspx page.
goi g to
When you press that arrow sign Grid view task will open from there - -> Select Edit Columns. You
come to a new Window - -> Fields. Go to Available Window - -> Button Field - -> ADD.
Add three Button Field. [ID, Name, City]. Uncheck Auto-generate Fields.
Page
144
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
Now Click on ID and in the Next Section you see – Template Field Properties. In that go to - ->
HeaderText - -> Give name of the header that you want to show in your Grid view Column. Then
in that section find Data Field - - > Name it as ID. At the Bottom part of Template Field Properties
- - > Convert this field into Template Field is there Cli k o that.
You will see your Bound Field get converted into template field. Press OK. In the same way you
have to do for Name and City. If you get any problem you can ask me in comments.
Page
145
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
Step8) Come back to Grid view in Normal Mode. Press Again that arrow in grid view, your get
back to grid view task. Inside that you will see – Choose Data Source .
Page
146
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
As you had Added SQL Server Database [Database.mdf]. Select from that dropdown
SqlDataSource1. You will get something like this:
Press that arrow in SQL DataSource - -> Configure Data Source. Inside Configure Datasource
Window - -> Select your Database - - > Database.mdf (that you had added initially) - -> Press Next.
Get you table by going to - -> Specify Columns from table view - -> Select your table from
dropdown - -> tbl_data.
Page
147
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
As you can see they queried Select * from tbl_data - -> so we will get our Data from Database to
our Grid View in our Browser. Just Press Next. You get to Test Query Window - -> Press Finish.
OUTPUT CHAMBER
Page
148
EASY GRIDVIEW WITH GRIDVIEW TUTORIALS
You even can test your Query Here - - > Click Test Query - -> you will get your Result in that black
window. It will fetch all content that you had added in your Database.
You also can check it out into the Browser. Going to - -> BoundControl_demo.aspx - -> View in
Browser.
Page
149