Step by Step GridView Tutorials with Asp.net - Documents Free

0 downloads 0 Views 6MB Size Report
... in MVC 3 C#. 10. Bind Grid View with Database in MVC 5 C# ... Export selected data from Gridview in Excel in asp.net using C#. 14. Bind Gridview .... 2) RowCommand: It will invoke when a button is clicked in Gridview control. ... Here is the link for Downloading: SQL Server Management Studio Express 2008. Here is the ...
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 “Gridview”.

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. 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 comes under “Data Section”.

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 Button” for each row in your Gridview. By which you can easily delete any data from your Gridview. Page 7

EASY GRIDVIEW WITH GRIDVIEW TUTORIALS

5) Auto Generate Edit Button: This property lets you to generate a common field with “Edit button” for each row in your Gridview. Data is never to be constant, it changes with 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 “DataKeysNames”- 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 can’t use local database anywhere, I mean local database will not give you the extra utilities and 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 by creating New Database. Click on Database in Object Explorer and -- > 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 database (this is all we want don’t we?) 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 comes in “Selected Area”. Now input the proper heading by going to - > “Header Text” give heading as ID, Name and City (Template Field Properties – Right Hand side) you have to find another property too named as – “Data Field” input the same data field as you had taken in the database. After all these convert 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 “Web 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 Again you need to add “SQL Server Database" and "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 - -> tbl_data [Don’t Forget to make 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 design in Grid View. Let’s begin by opening your gridview_demo.aspx page and fry the code like this: Bind Grid View Using 3Tier

Page 31

EASY GRIDVIEW WITH GRIDVIEW TUTORIALS



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” window will open (Below Image). Here you have to add three “BoundField” Button from - -> 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 - -> Change every Bound 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 description for Commonfunctions /// 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 database property that must be the lengthy process, that’s why we had made this class and now 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 description for DAL_user_operation /// 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 description for BAL_user_operation /// 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



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 - -> tbl_data [Don’t Forget to make ID as IS Identity -- True] Page 43

EASY GRIDVIEW WITH GRIDVIEW TUTORIALS

Make some entries in Database by going to - - Table - -> tbl_data - -> Right Click - -> Show Table Data. Don’t copy my entries - - 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:

.style1 { font-size: large; text-align: center; } .style2 { width: 272px; } .style3 { width: 264px; }
Get Data From Database using Seleceted IDs
Page 45

EASY GRIDVIEW WITH GRIDVIEW TUTORIALS

     
  -- Select Id-
     
  Page 46

EASY GRIDVIEW WITH GRIDVIEW TUTORIALS

Page 47

EASY GRIDVIEW WITH GRIDVIEW TUTORIALS

 
     


Your Design will look like this:

CODE CHAMBER

Step5) Now it’s time for server side coding so that our application get work, Open your gridviewid_demo.aspx.cs file and code it like below.

Page 48

EASY GRIDVIEW WITH GRIDVIEW TUTORIALS



Gridviewid_demo.aspx.cs

Don’t forget the namespaces –

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 [purnima’s data in 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 - -> tbl_data [Don’t forget to make 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 53

EASY GRIDVIEW WITH GRIDVIEW TUTORIALS

Page 55

EASY GRIDVIEW WITH GRIDVIEW TUTORIALS

     
  --%> Page 54

EASY GRIDVIEW WITH GRIDVIEW TUTORIALS

 
     


Now for whom those who are using Template Field Here, You have to embed single thing into to the code i.e. – Sort Expression – “whatever the field is for like [like if it is first name then write like sort expression=”firstname”]. 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#

In this tutorial I’ll show you how to bind data in Datagrid in WPF using C#, where we use SQL 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 .

Page 61

EASY GRIDVIEW WITH GRIDVIEW TUTORIALS







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 { /// /// Interaction logic for MainWindow.xaml /// 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# In this article I’ll show you how to bind grid view control using xml instead of taking any database 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

01 Nilesh Rajkot 02 Purnima Ahmedabad 03 Chandni Mumbai 04 Rinku Pune 05 Nilu Delhi Page 67

EASY GRIDVIEW WITH GRIDVIEW TUTORIALS

06 Shailesh Nashik



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 68

EASY GRIDVIEW WITH GRIDVIEW TUTORIALS

Page 69

EASY GRIDVIEW WITH GRIDVIEW TUTORIALS



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#

In this tutorial I’ll show you how to bind Grid view using MVC3 C# using Razor, here I hadn’t used any database, and we manually feed that data into our Controller, so it’s a kind of Binding 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 code like this. Don’t forget to add namespace of model.

 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 stdnt1 = new List();

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 @{ ViewBag.Title = "Home Page"; WebGrid grid = new WebGrid(Model); }

Binding Gridview in MVC3

This is my First Binding Tutorial of Gridview in MVC3

@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#

In this tutorial I’ll show you how to bind Grid view using MVC5 C# using Razor, In previous tutorial I haven’t used any database, but here we will use and then we manually feed some data into our table and bind that data to Gridview. So it’s a kind of Binding Gridview with database.

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:



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 { get; set; } } } Page 84

EASY GRIDVIEW WITH GRIDVIEW TUTORIALS

In Controller Step5) Right Click on Controller, Add Empty Controller, Name it – StudentController.cs. Write code like this. Don’t forget to add namespace of model. 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 @{ ViewBag.Title = "Bind Gridview with Database"; WebGrid grid = new WebGrid(Model); }

Bind GridView in MVC5 with Database

@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

In this tutorial I’ll show you how to use dropdown list inside Gridview, and how to make edit, update, and delete operation on each field along with dropdown list.

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 - -> tbl_data [Don’t forget to make 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 90

EASY GRIDVIEW WITH GRIDVIEW TUTORIALS

--Select Gender- Male Female
Page 91

EASY GRIDVIEW WITH GRIDVIEW TUTORIALS



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

In this Article I’ll show you about how to export grid view to Excel Document 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 - -> tbl_data [Don’t Forget to make ID as IS Identity -- 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 99

EASY GRIDVIEW WITH GRIDVIEW TUTORIALS



Page 100

EASY GRIDVIEW WITH GRIDVIEW TUTORIALS







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) Now it’s time for server side coding so that our application get work, Open your gridviewexcel_demo.aspx.cs file and code it like below.

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 time for code, first we bind the grid view , than we make code for paging using 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#

In this tutorial I’ll show you how export selected data from Gridview in excel using ItextSharp Library in asp.net using C#.

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 - -> tbl_data [Don’t Forget to make ID as IS Identity -- 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 111

EASY GRIDVIEW WITH GRIDVIEW TUTORIALS







Text=' '> '> '> Page 112

EASY GRIDVIEW WITH GRIDVIEW TUTORIALS






You’re Design 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 time for server side coding so that our application get work, Open your gridviewexcel_demo.aspx.cs file and code it like below.

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#

In this tutorial I’ll show you how to bind Gridview with MS Access Database in asp.net using 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:

.style1 { text-decoration: underline; color: #0000FF; font-size: large; }
Gridview Databind using MS Access Database

Page 126

EASY GRIDVIEW WITH GRIDVIEW TUTORIALS

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

In this tutorial I’ll show you how to insert images into Datagrid in Windows 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

In this tutorial I’ll show you how to use validation inside Gridview in asp.net, where we 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 - -> tbl_data [Don’t forget to make 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:

.style1 { text-decoration: underline; } Page 135

EASY GRIDVIEW WITH GRIDVIEW TUTORIALS

Gridview Demo with DropDownlist

Page 136

EASY GRIDVIEW WITH GRIDVIEW TUTORIALS

--Select Sport--


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

In this Article I’ll show you about Bound Control in Grid View using Asp.net C# where we make a select query and you will see your output your result inside grid view.

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 [Don’t Forget to make ID as IS Identity -- True]

DESIGN CODE

Step6) Open your BoundControl_demo.aspx file from solution Explorer and start design you’re Application:

Here is the Code: Page 142

EASY GRIDVIEW WITH GRIDVIEW TUTORIALS

Page 143

EASY GRIDVIEW WITH GRIDVIEW TUTORIALS

Besides this if you don’t want to go with code than you can manually add the thing by going to your Toolbox - -> Data - -> Gridview - -> Drag it into the .aspx page.

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 Click on 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