Grid View Example Code
Grid View Example Code
Grid View Example Code
Check/Uncheck
Introduction
Some sample code is provided under Using the code heading and complete code is
available in the project download.
Background
(Forums are flooded with the questions about how to check/uncheck CheckBox
control inside a GridView using javascript without postback.
How To’s:
In this article a GridView control is used. Inside the GridView control there are 3
fields. One template field and two are bound fields to display some sample data.
<script type="text/javascript">
function SelectAll(id)
{
//get reference of GridView control
var grid = document.getElementById("<%= GridView1.ClientID %>");
//variable to contain the cell of the grid
var cell;
if (grid.rows.length > 0)
{
//loop starts from 1. rows[0] points to the header.
for (i=1; i<grid.rows.length; i++)
{
//get the reference of first column
cell = grid.rows[i].cells[0];
Last week, I learned a technique of applying a hover effect to an HTML table’s rows with the
help of pure CSS, without using a single line of JavaScript code. Great! Isn’t it? Before that,
I’ve been doing this using JavaScript, as in my previous article: Hotmail-like Mouse Over
and Mouse Out Effects on GridView. I thought it might be interesting to implement this
technique on a GridView in order to create a hover effect on the GridView rows. So, I’ve
quickly created a sample application and decided to share it. Below is the implementation
details of this technique for applying hover effect to GridView rows using CSS.
The HTML code for the GridView in this article will looks like:
In order to style the Gridview, attach a CSS class to it, like so:
In order to style the GridWiew’s header, normal, and alternate rows, attach the CSS
classes to these rows through the RowCreated event of the GridView, as:
Below are the CSS classes that have been used above to style the GridView and its
header, normal, and alternate rows:
.grid-view
{
padding: 0;
margin: 0;
border: 1px solid #333;
font-family: "Verdana, Arial, Helvetica, sans-serif, Trebuchet MS";
font-size: 0.9em;
}
.grid-view tr.header
{
color: white;
background-color: #FF5600;
height: 25px;
vertical-align: middle;
text-align: center;
font-weight: bold;
}
.grid-view tr.normal
{
color: black;
background-color: #FDC64E;
height: 25px;
vertical-align: middle;
text-align: center;
}
.grid-view tr.alternate
{
color: black;
background-color: #D59200;
height: 25px;
vertical-align: middle;
text-align: center;
}
Finally, to apply the hover effect to the GridView rows, the following CSS is used:
Note that the hover effect has been applied to the normal and alternate rows only, not on
the header row. You can also use different color schemes for the normal and alternate rows
separately, for the hover effect.
Using the CSS Classes
Put all the corresponding CSS classes in a stylesheet and give its reference on the web
page’s head section, as:
Conclusion
That’s all about this technique. Just download the sample application and happy CSS! I have
tested this application on various browsers and it worked fine. Below is the list of those
browsers:
How It Works
It's very easy actually, all we do is use a <asp:SqlDataSource/> web control to bind to
the master database (remember you'll need to change the connection section in the
web.config to point at your own database). The GridView data is obtained using a simple
select statement SELECT TOP 5 * FROM dbo.spt_values table, and then have the
GridView control use this <asp:SqlDataSource/>. Then we include a
<asp:CommandField ShowSelectButton="True" Visible="False" /> field which
we set to be invisible.
One more point to note is that the Page must have the following directive set in order to
allow the JavaScript postback mechanism that is described below.
So that's the ASPX file (web form), but we also need to write some code in the code behind
and use a little bit of JavaScript. So the code behind (C# for the attached demo) looks like :
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
/// <summary>
/// Check the item being bound is actually a DataRow, if it is,
/// wire up the required html events and attach the relevant JavaScripts
/// </summary>
/// <param name="sender">GridView1</param>
/// <param name="e">The event args for the RowDataBound event</param>
protected void GridView1_RowDataBound(object sender,
GridViewRowEventArgs e)
{
//check the item being bound is actually a DataRow, if it is,
//wire up the required html events and attach the relevant JavaScripts
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onmouseover"] =
"javascript:setMouseOverColor(this);";
e.Row.Attributes["onmouseout"] =
"javascript:setMouseOutColor(this);";
e.Row.Attributes["onclick"] =
ClientScript.GetPostBackClientHyperlink
(this.GridView1, "Select$" + e.Row.RowIndex);
}
}
/// <summary>
/// Show the 1st cell value in the web pages TextBox to show the user
/// it is actually selecting rows at client side
/// </summary>
/// <param name="sender"> GridView1</param>
/// <param name="e">The event args for the SelectedIndexChanged event
/// </param>
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
TextBox1.Text = GridView1.SelectedRow.Cells[1].Text;
}
}
One for onmouseover which simply sets the current row to be highlighted a certain
color. I chose Yellow, but you can change that.
One for onmouseout which simply resets the current row to be the original color
e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink
(this.GridView1, "Select$" + e.Row.RowIndex);
This cunningly creates a client hyperlink which posts back the current ASPX web form, using
the Select$0 to select row 0 say.
function setMouseOverColor(element)
{
oldgridSelectedColor = element.style.backgroundColor;
element.style.backgroundColor='yellow';
element.style.cursor='hand';
element.style.textDecoration='underline';
}
function setMouseOutColor(element)
{
element.style.backgroundColor=oldgridSelectedColor;
element.style.textDecoration='none';
}
</script>
And that's it. So what we get is now a nice GridView control, that we select rows with
using JavaScript, and it looks like a table, rather than a table plus some nasty SELECT
button, or a hyperlink column (that is only being used as a row selection method anyway).
That's it
And that as they say is that. Simple wasn't it. Probably my most simple article yet. But I
think it's a useful one, I have always wondered how my online bank did produced such a
nice grid.
I would just like to ask, if you liked the article please vote for it, and leave some comments,
as it lets me know if the article was at the right level or not, and whether it contained what
people need to know.
Conclusion
Well that's it actually. Although the code is very simple, I'm sure you'll agree this JavaScript
selection method sure looks better than having a button column, or a hyperlink column to
do the row selection. And it's more intuitive, I think. The users simply point and click the
row they want, job done.
Introduction
In this article, I will show you how to can refresh a GridView control on the parent page,
from a pop up window. I will discuss different scenarios which you will find very helpful
when implementing your solution.
Database Table
I will be using my own custom table for this article. The table name is Users, and it contain
columns for UserID, UserName, FirstName, and LastName. UserID is an automatically
generated primary key. Here is the schema of the Users table:
The parent page will contain a GridView control and a href tag. The href tag will open a
new popup window which will be used to insert the data into the database and refresh the
GridView control which is contained in the parent page. Let's see how the parent page is
implemented.
ad.Fill(ds,"Users");
GridView1.DataSource = ds;
GridView1.DataBind();
}
As you can see, I am not doing anything fancy. I simply populate the GridView from the
database, using a SELECT query in the BindData method.
The parent page also contains the href tag which is used to open the popup window. Let's
see the code for this href tag in the HTML view of the page.
}
</script>
Pretty simply, right? The OpenWindow function is fired when you click on the href tag. This
will open a small pop up window. Take a look at the screenshot below to have a clear idea:
Yes, you have guessed right, the small window which contains the textboxes for user name,
first name, and last name is our small popup window. Now, after filling all the required
information in the textboxes and pressing the Add User button, we want it to add the user
to the database and refresh the parent page which contains the GridView control, hence
populating the newly inserted data into the GridView.
Now, let's see that how the popup page is implemented. First, let's see the HTML code for
the popup page so we will know how the controls are setup on the page.
Now, let's implement the code that will insert the data into the database. The following code
is triggered when the user presses the "Add User" button.
The above code simply attaches the parameters to the parameterized query and inserts
them into the database. I am pretty sure you have done similar stuff several times.
Now, let's see the code that will refresh the parent page which contains the GridView.
Refreshing the GridView control on the parent page sounds refreshing! Sorry about the
bad joke, let's get to the point. Refreshing the GridView control is pretty simple. Take a
look at the code below:
// ASP.NET 2.0
if (!Page.ClientScript.IsClientScriptBlockRegistered(scriptString))
{
Page.ClientScript.RegisterClientScriptBlock(this.GetType(),
"script", scriptString);
}
if (!Page.IsPostBack) { }
}
I have included the code for both the versions. The commented out code can be used if you
are using Visual Studio .NET 2003 or the .NET framework 1.X. All I am doing in the page
load event is, attaching the client side script to the page. The script
window.opener.document.forms(0).submit(); means that the parent of the current
page will be submitted. This will cause a postback to happen on the parent page, and since
we are binding the GridView control on every page load, it will work fine. Take a look at
the screenshot below:
So, you see, it is pretty simple, right? Now, let's take care of some important things. Let's
say that you want to close the window when the "Close Window" button is pressed. You can
do this by simply attaching the JavaScript "window.close()" function to the button click
event.
// ASP.NET 2.0
Btn_CloseWindow.OnClientClick = "window.close();";
// ASP.NET 1.X
Btn_CloseWindow.Attributes.Add("onclick", "window.close();");
You might want to attach the window close event to the "Add User" button. This way, when
the user is added, the popup window is automatically closed. For this, you can use the
OnUnload event. Check out the code below:
<body onunload="opener.location.reload();">
<body onunload="opener.location.reload();">
Also keep in mind that you don't have to register any scripts when you are using
opener.location.reload().
V. Display image gallery in ASP.NET
GridView Control
Introduction
In this article I will try to explain you how you can display images as a gallery view using
GridView control of ASP.NET.
I face problem of paging when I had tried it with DataList control. In DataList we can define
repeat column direction to display images as gallery. But main problem is paging, and you
have to use third party control to apply paging in DataList and it is difficult to manage with
third party control.
But here I have taken GridView control to display image gallery. With use of internal paging.
So we can done all operation very simply on GridView control.
Lets Start.
Here we have taken Gridview control named by “gvListProperty”. In this GridView control I
have taken one template column. So in that we can apply some formatting as we want to
display.
You can also apply some CSS to table inside this template column. Here we have set
AllowPaging=True. Because we need to use paging in this gallery view. This GridView will
display 40 records on each page. Here I have set pageSize=10 so it has fix page size to
display records only 40*10=400. You can change it as per your requirement.
Paging mode is numeric and page number will display on Top and Bottom of the GridView.
First column is 4 static column noted with bold face.
These columns I have define are not related to Database Table columns. The data will fillup
in this column from code behind. Because I face problem to display images as repeat
column manner. This is possible in DataList only to display record in repeat column
direction. But here in GridView Control it is not possible. And same in DataList control
internal paging is not possible.
Here you can simplify code by writing it in a region section. Declare object variable first in a
code behind file. (before page load)
'To set page nuber after redirecting back from detail page
If Request.QueryString("iPn") <> Nothing Or IsNumeric(Request.QueryString("iPn"))
Then
gvListProperty.PageIndex = CInt(Request.QueryString("iPn"))
End If
In a page load event I am calling function that will retrieve records form table.
'Integrate this record with DataTable and then bind it with GridView
Call DataTableBind(dsProperty)
End If
End With
End Sub
Imports Microsoft.VisualBasic
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Imports commonlib
"ConnectionString").ConnectionString)
Dim sSql As String
Dim retVal As New DataSet
#Region "Method"
This is a sample code written in class file. I have created my own DBManager file, that is
used for performing all DB operation. You can use DataAdepter or DataReader to do same in
code behind file.
Integrate this record with DataTable and then bind it with GridView
Read this code very carefully because all display and paging logic is dependent on this code.
I face too much problem when writing code first time. It has taken too much time to write
this simple code.
Here I have used DataTable to insert each image in its 4 columns one by one. After 4
columns have data it will generate new row with new 4 columns and same way it rotating
up to last record of the Dataset.
'Due to Paging Counter == 40 Records per page, On Every 40 records Page number
will get increment.
If (iCount + 1) > iCountIncre Then
iCountIncre = iCountIncre + 40
iPn = iPn + 1
End If
dsProperty.Tables(0).Rows(iCount).Item("sImageName") & _
"' border='0' alt='Vis'/>"
'This will maintain 4 columns per row. When column get number 5, at that time
it
'turns for new row
If iColumn = 5 Then
dtTable.Rows.Add(dtRow)
dtRow = dtTable.NewRow
iColumn = 1
End If
ds.Tables.Add(dtTable)
'Now GridView get ds(dataset) as DataSource
gvListProperty.DataSource = ds
gvListProperty.DataBind()
End Sub
In a function DataTableBind I have passed a dataset with records. Here I have taken
variable dtTable of type DataTable. As explain early. dtTable has 4 columns
DataColumn("Column1") to DataColumn("Column4"). If you can’t getting why I have taken
this then again look at column description of GridView control explain early on.
For Loop with iCount will run up to last record of the dataset.
Variable iCountIncre will get increment of value 40 at every 40 records so we can manage
page number consistency. This is why because we have to pass current page number of
browsed image gallery page to its detail page. And when returning back from detail page to
gallery view at that time we have to maintain this page number.
Variable iColumn is used to maintain column consistency from column no.1 to 4. Because
here we have to display 4 images at each row.
In this logic dtRow(“Column” & iColumn) will be like this dtRow(“Column1”) and upto
dtRow(“Column4”).
So this dtRow has Column and that column value will display image in gallery because it call
that image from path with image name from database table
dsProperty.Tables(0).Rows(iCount).Item("sImageName").
And link on that image represent the link page name with iPn (page number), iPropertyID
(because image is related to that property. It represent unique id of property).
ds.Tables.Add(dtTable)
And after that bind this table with dataset “ds”. And bind this dataset “ds” to GridView.
When user click on any page number it will call this event and code written inside this event
will change the current page index and assign new page number to GridView and bind this
GridView again with record. After binding GridView the page which you see it is of new
assign page number.
One more thing I want to share with you that is I also got suggestion to bind this GridView
in RowDataBound Event of the GridView. To bind this GridView in RowDataBound we have
to take Record Dataset either Public Variable or in a ViewState and then need to do some
extra operation then as I wrote in function DataTableBind(). So Dataset with records in
Public Variable or with ViewState will occupy more memory compare to existing code
memory usage. That's why I had let go that concept.
Hello, readers.
While building a web project, we may often come across the situation of displaying records
or other types of data. We can do it in the best way by using DataGrid/GridView. It's
very simple and requires only a knowledge of C#, of web application building and of SQL
2005.
"A picture is worth 1000 words!!" so I have explained a lot of things using pictures. I hope
you will find it really easy. This is roughly what the final result looks like...
Design Info
Data Source
For the data I have used, see the two data tables Emp_table and Emp_dept, which you
can create in SQL looking at the picture below...
You can execute these queries. In which case, choose the database name first.
NOTE: I have used two different tables. The databound <Label1> in the Department
column is bound to Emp_dept_name in the Emp_dept table. For the rest of the work,
Emp_table is used.
Coming to the coding part: don't forget to use the correct database connection string. Put it
as a parameter at the time of declaring the SQL connection. Also, make sure that the
web.config file contains the correct connection string.
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
//
//
//*******************Use of dataview to be noted here*************************
//
//
//
//To bind MasterGrid the use of strored procedure named-----BindMasterGrid----
//
//
MasterGrid.DataSource = ds;
MasterGrid.DataBind();
//Before the GridView control can be rendered, each row in the control must be
//bound to a record in the data source.The RowDataBound event is raised when a
//data row (represented by a GridViewRow object)is bound to data in the GridView
//control.
gr = ((GridView)e.Row.FindControl("ChildGrid"));
dv.RowFilter = "Emp_dept=" + Convert.ToString(
MasterGrid.DataKeys[e.Row.RowIndex].Value);
gr.DataSource = dv;
gr.DataBind();
}
}
//
//Use of Select statement to bind the ChildGrid
//
//
private void BindChildGrid()
{
((GridView)MasterGrid.Rows[i].Cells[1].Controls[1]).DataSource = null;
Label lbl1 = (Label)(MasterGrid.Rows[i].Cells[0].Controls[3]);
DataSet ds1 = new DataSet();
SqlCommand cmd =
new SqlCommand(
"SELECT Emp_no, Emp_name, Emp_sal FROM Emp_table where Emp_dept ='" +
lbl1.Text + "'", con);
SqlDataAdapter da = new SqlDataAdapter(cmd.CommandText, con);
da.Fill(ds1, "Emp_table");
((GridView)MasterGrid.Rows[i].Cells[1].Controls[1]).DataSource = ds1;
((GridView)MasterGrid.Rows[i].Cells[1].Controls[1]).AllowSorting = true;
((GridView)MasterGrid.Rows[i].Cells[1].Controls[1]).DataBind();
}
}
//
//The event below is fired when "Edit" button in Department column is clicked
//
//The point to be noted here is that----we store the index of the row in which
//Edit button was clicked----using Sessions.
//
//Modify column in the ChildGrid apears
//
int i = (int)Session["ind"];
GridView Childgrid = (GridView)(MasterGrid.Rows[i].Cells[1].Controls[1]);
Childgrid.Columns[3].Visible = true;
MasterGrid.Rows[i].FindControl("CancelMaster").Visible = true;
}
//
//The event below is fired when "Edit" button in Modify column of CildGrid is
clicked
//
//
Childgrid.EditIndex = e.NewEditIndex;
BindChildGrid();
}
//
//The event below is fired when "Cancel" button in Department column is clicked
//
//
//
//The event below is fired when "Cancel" button in
//Modify column(ChildGrid) is clicked
//
//
//To update the editing done in the ChildGrid
//
//
int empno =
Convert.ToInt16(((Label)Childgrid.Rows[e.RowIndex].FindControl(
"Label1")).Text);
string empname =
((TextBox)Childgrid.Rows[e.RowIndex].FindControl("TextBox2")).Text;
double salary =
Convert.ToDouble(((
TextBox)Childgrid.Rows[e.RowIndex].FindControl("TextBox3")).Text);
SqlCommand cmd =
new SqlCommand("Update Emp_table set Emp_name='" +
empname + "',Emp_sal='" + salary +"'where Emp_no='" + empno+"'", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Childgrid.EditIndex = -1;
BindChildGrid();
//
//Delete button will fire event below to delete a row in ChildGrid
//
//
//
//
//Add a record in selected department
//
int i = (int)Session["ind"];
GridView Childgrid = (GridView)(MasterGrid.Rows[i].Cells[1].Controls[1]);
int empno =
Convert.ToInt16(((TextBox)Childgrid.FooterRow.FindControl("TextBox4")).Text);
string empname = ((TextBox)Childgrid.FooterRow.FindControl("TextBox5")).Text;
double salary =
Convert.ToDouble(((
TextBox)Childgrid.FooterRow.FindControl("TextBox6")).Text);
string deptname = ((Label)MasterGrid.Rows[i].FindControl("Label1")).Text;
SqlCommand cmd =
new SqlCommand("Insert into Emp_table values('" +
empno + "','" + empname + "','" + deptname + "','" + salary + "')", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
BindChildGrid();
((TextBox)Childgrid.FooterRow.FindControl("TextBox4")).Visible = false;
((TextBox)Childgrid.FooterRow.FindControl("TExtBox5")).Visible = false;
((TextBox)Childgrid.FooterRow.FindControl("TextBox6")).Visible = false;
//
//New button is used to Expose TextBoxes to Enter new record
//
//
BindChildGrid();
((TextBox)Childgrid.FooterRow.FindControl("TextBox4")).Visible = true;
((TextBox)Childgrid.FooterRow.FindControl("TExtBox5")).Visible = true;
((TextBox)Childgrid.FooterRow.FindControl("TextBox6")).Visible = true;
((LinkButton)Childgrid.FooterRow.FindControl("New")).Visible = false;
((LinkButton)Childgrid.FooterRow.FindControl("Add")).Visible = true;
((LinkButton)Childgrid.FooterRow.FindControl("Cancel")).Visible = true;
}
//
//When Cancel button in Modify column is clicked
//
//
BindChildGrid();
((TextBox)Childgrid.FooterRow.FindControl("TextBox4")).Visible = false;
((TextBox)Childgrid.FooterRow.FindControl("TExtBox5")).Visible = false;
((TextBox)Childgrid.FooterRow.FindControl("TextBox6")).Visible = false;
((LinkButton)Childgrid.FooterRow.FindControl("New")).Visible = true;
((LinkButton)Childgrid.FooterRow.FindControl("Add")).Visible = false;
((LinkButton)Childgrid.FooterRow.FindControl("Cancel")).Visible = false;
}
}
Conclusion
I found it very interesting working with grids. We can extend this by further inserting a grid
within a grid, although in real use we include various other features like JavaScript, etc. so
as to avoid the transfer of bulk again and again over the web. There might be many other
ways to do this efficiently, but as I am also at a beginner level, it will be best to start with
this. I welcome any queries and responses from your side. Keep on making sincere efforts
and you will be a good programmer one day.
ASP.Net have the gridview which is very usefull to display such kind of some datas or
images like this. Here is I'm going to display images which are in a folder with thumbnail
size.
Thumbnail Image
(First of all I need a support page which is create thumbnail image. Here is I'm working with
imageresize.cs. This file will help you for creating thumbnail images.
ImageResize class have some functionalities for creating thumbnail images. I'm creating
thumbnail images and write the image in that supporting page. In my image viewer page I
have created a grid view and give the supporting page as resolving url in every images
contain's in that appropriate folder.
From this above code I'm searching images with .jpg extension in the Images folder. I'm
putting row number for every image and binding the thumbnail image from
ThumbnailCreator.aspx page for the appropriate image.
In ThumbnailCreator page,
From above,the query string will be come with the path of image which is to be conver to
thumbnail image. I'm creating thumbnail page using ImageResize.cs. See the
ImageResize.cs file in app_code. Thumbnail image is writing in page using
Response.OutputStream.
Response type is "image/Jpeg". It's must for image. This will help to write in page as jpeg
file.
Hence the Image has been created thumbnail image and displayed in a gridview.