Grid View Example Code

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 40
At a glance
Powered by AI
The document discusses techniques for interacting with checkboxes in a GridView without postbacks using JavaScript, adding hover effects to GridView rows using CSS, and displaying images as thumbnails in a GridView.

Checkboxes in a GridView can be checked/unchecked using JavaScript by getting a reference to the GridView, looping through its rows and cells, and checking/unchecking the checkboxes based on the status of a 'Select All' checkbox.

Hover effects can be added to GridView rows using CSS by adding a class to the GridView and styling its rows on hover. No JavaScript is required.

I.

Check/Uncheck

Introduction

Check/uncheck CheckBox control inside a GridView using javascript without


postback. This article will give an idea on how to achieve this task.

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.

Inside the TemplateField a CheckBox control is placed in the HeaderTemplate (with


ID cbSelectAll and Text Select All), ItemTemplate and AlternatingItemTemplate.
Using the code
Code that will be required to achieve this task.
Javascript that will be required to perform the Select All action is as follow:

<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];

//loop according to the number of childNodes in the cell


for (j=0; j<cell.childNodes.length; j++)
{
//if childNode type is CheckBox
if (cell.childNodes[j].type =="checkbox")
{
//assign the status of the Select All checkbox to the cell
checkbox within the grid
cell.childNodes[j].checked =
document.getElementById(id).checked;
}
}
}
}
}
</script>

Code required to add an attribute of cbSelectAll CheckBox is as follow:

protected void Page_Load(object sender, EventArgs e)


{
if (!IsPostBack)
{
//Binding GridView with the datasource

//FillDataTable is a method that will return a DataTable


//filled with some rows (code available in download)
this.GridView1.DataSource = FillDataTable();
this.GridView1.DataBind();
}
}

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)


{
if (e.Row.RowType == DataControlRowType.Header)
{
//Find the checkbox control in header and add an attribute
((CheckBox)e.Row.FindControl("cbSelectAll")).Attributes.Add("onclick",
"javascript:SelectAll('" +
((CheckBox)e.Row.FindControl("cbSelectAll")).ClientID + "')");
}
}
Before clicking the Select All CheckBox

After clicking the Select All CheckBox

II. Hover Effects for GridView Rows Using


CSS
Introduction

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 GridView HTML Code

The HTML code for the GridView in this article will looks like:

<asp:GridView ID="gvHover" BackColor="WhiteSmoke" runat="server"


AutoGenerateColumns="False"
GridLines="Vertical" CssClass="grid-view"
OnRowCreated="gvHover_RowCreated">
<Columns>
<asp:BoundField HeaderText="n" DataField="n">
<HeaderStyle Width="25px" />
<ItemStyle Width="25px" />
</asp:BoundField>
<asp:BoundField HeaderText="sqrt(n)" DataField="sqrtn">
<HeaderStyle Width="150px" />
<ItemStyle Width="150px" />
</asp:BoundField>
<asp:BoundField HeaderText="qbrt(n)" DataField="qbrtn">
<HeaderStyle Width="150px" />
<ItemStyle Width="150px" />
</asp:BoundField>
</Columns>
</asp:GridView>

Styling the GridView

In order to style the Gridview, attach a CSS class to it, like so:

<asp:GridView ... CssClass="grid-view" ... > ... </asp:GridView>

Styling the GridView’s Header Row, Normal Row, and Alternate


Row

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:

//Add CSS class on header row.


if (e.Row.RowType == DataControlRowType.Header)
e.Row.CssClass = "header";

//Add CSS class on normal row.


if (e.Row.RowType == DataControlRowType.DataRow &&
e.Row.RowState == DataControlRowState.Normal)
e.Row.CssClass = "normal";

//Add CSS class on alternate row.


if (e.Row.RowType == DataControlRowType.DataRow &&
e.Row.RowState == DataControlRowState.Alternate)
e.Row.CssClass = "alternate";

The CSS Classes

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;
}

Adding a Hover Effect to the GridView rows

Finally, to apply the hover effect to the GridView rows, the following CSS is used:

.grid-view tr.normal:hover, .grid-view tr.alternate:hover


{
background-color: white;
color: black;
font-weight: bold;
}

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:

<link href="StyleSheet.css" rel="stylesheet" type="text/css" />

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:

III. Using JavaScript To Select GridView


Rows

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 in the page declarations section, ensure the following is set


EnableEventValidation="false"

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;

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


{
protected void Page_Load(object sender, EventArgs e)
{

/// <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;
}
}

This works by attaching 2 JavaScripts to the current GridView row.

 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

There is also a clever line as given below:

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.

The ASPX pages JavaScript is as follows:

<script language="javascript" type="text/javascript">


var oldgridSelectedColor;

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.

So What Do You Think ?

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.

IV. Refresh a GridView control on the parent


page, from a pop up window

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:

if exists (select * from dbo.sysobjects where


id = object_id(N'[dbo].[Users]') and
OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[Users]
GO

CREATE TABLE [dbo].[Users] (


[UserID] [int] IDENTITY (1, 1) NOT NULL ,
[UserName] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[FirstName] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[LastName] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
) ON [PRIMARY]
GO

Making the Parent Page

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.

Code-Behind of the Parent Page

protected void Page_Load(object sender, EventArgs e)


{
BindData();
}

private void BindData()


{
// make the query
string query = "SELECT * FROM Users";
SqlConnection myConnection = new SqlConnection(ConnectionString);
SqlDataAdapter ad = new SqlDataAdapter(query, myConnection);

DataSet ds = new DataSet();

ad.Fill(ds,"Users");
GridView1.DataSource = ds;
GridView1.DataBind();
}

private string ConnectionString


{
get { return @"Server=localhost;Database" +
@"=MyDatabase;Trusted_Connection=true"; }
}

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.

<a href="#" onclick="OpenWindow()">Insert Data

<script language="javascript" type="text/javascript">


function OpenWindow()
{
window.open ("PopUpWindow.aspx",
"mywindow", "menubar=0,resizable=0," +
"width=350,height=250,toolbars=0");

}
</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.

Implementation of the Popup Page

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.

<form id="form1" runat="server">


<div>
UserName: <asp:TextBox ID="txtUserName" runat="server"></asp:TextBox><br>
FirstName:<asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox><br>
LastName:<asp:TextBox ID="txtLastName" runat="server"></asp:TextBox><br>

<asp:Button ID="BtnAdd" runat="server" Text="Add User" OnClick="BtnAdd_Click"/>


<asp:Button ID="Btn_CloseWindow" runat="server" Text="Close Window"/>
</div>
</form>

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.

private void AddUser(string userName, string firstName, string lastName)


{
string QUERY_ADDUSER = @"INSERT INTO Users(UserName," +
@" FirstName, LastName) VALUES(@UserName,@FirstName,@LastName)";
SqlConnection myConnection = new SqlConnection(ConnectionString);
SqlCommand myCommand = new SqlCommand(QUERY_ADDUSER, myConnection);
myCommand.Parameters.AddWithValue("@UserName", userName);
myCommand.Parameters.AddWithValue("@FirstName", firstName);
myCommand.Parameters.AddWithValue("@LastName", lastName);
myConnection.Open();
myCommand.ExecuteNonQuery();
myConnection.Close();
}

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

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:

protected void Page_Load(object sender, EventArgs e)


{
string scriptString = "<script language="JavaScript"> " +
"window.opener.document.forms(0).submit(); </script>";

// ASP.NET 2.0
if (!Page.ClientScript.IsClientScriptBlockRegistered(scriptString))
{
Page.ClientScript.RegisterClientScriptBlock(this.GetType(),
"script", scriptString);
}

//// ASP.NET 1.X


//if (!Page.IsClientScriptBlockRegistered(scriptString))
//{
// Page.RegisterClientScriptBlock("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();">

As I already explained, the JavaScript function


window.opener.document.forms(0).submit(); will cause a postback, and in order to
work with this example, you need to bind the GridView each time the page is loaded. This
is not a good idea, and you can improve that by using the opener.location.reload();
function which will reload the parent page. This way, you can bind the GridView and other
controls only when the page is reloaded and not if there is a postback. In order to use
opener.location.reload();, simply attach it to the OnUnload event of the parent
page, as shown below:

<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.

1. Code for .ASPX page is as follow


<asp:GridView ID="gvListProperty" runat="server" AutoGenerateColumns="false"
Width="100%"
border="0" AllowPaging="true" BorderColor="white" cssClass="griditem" PageSize="10"
>
<PagerSettings Mode="Numeric" Position="TopAndBottom"/>
<PagerStyle CssClass="mypager" HorizontalAlign="right" />
<Columns>
<asp:TemplateField>
<HeaderStyle CssClass="dispnone" />
<ItemTemplate>
<table width="100%">
<tr>
<td class="bdr-grey">
<table width="100%" border="0" cellspacing="0" cellpadding="0" Class="griditem" >
<tr>
<td width="60px" height="60px" Class="griditem" >
<%#Container.DataItem("Column1")%>
</td>
<td width="60px" height="60px" Class="griditem" >
<%#Container.DataItem("Column2")%>
</td>
<td width="60px" height="60px" Class="griditem" >
<%#Container.DataItem("Column3")%>
</td>
<td width="60px" height="60px" Class="griditem" >
<%#Container.DataItem("Column4")%>
</td>
</tr>
</table>
</td>
</tr>
</table>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

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.

Now look at <%#Container.DataItem("Column1")%>, <


%#Container.DataItem("Column2")%>, <%#Container.DataItem("Column3")%>,
<%#Container.DataItem("Column4")%>.

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.

2. Code behind operations.

Declaring object variable

Here you can simplify code by writing it in a region section. Declare object variable first in a
code behind file. (before page load)

#Region " Data Members "


Dim objPropertyForSale As New Propertyforsale
#End Region

Variable objPropertyForSale is a object of class Propertyforsale.vb class file. In


propertyforsale.vb you can write method to fetch data from database table.

Call function that retrive records from database


Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)_
Handles Me.Load
If Not IsPostBack Then

'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

'Call function that retrieve records from database


Call BindPropertyGallery()
End If
End Sub

In a page load event I am calling function that will retrieve records form table.

Here is code for this function.

Public Sub BindPropertyGallery()


Dim dsProperty As DataSet
With objPropertyForSale
dsProperty = .Galleryview_PropertyList()
If dsProperty.Tables(0).Rows.Count > 0 Then

'Integrate this record with DataTable and then bind it with GridView

Call DataTableBind(dsProperty)
End If
End With
End Sub

Galleryview_PropertyList function is written in class file propertyforSale.vb. This


function will retrive records and return DataSet.

Function DataTableBind will bind this records with gridview columns.


Look below code that is written in propertyforSale.vb class file.

Imports Microsoft.VisualBasic
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Imports commonlib

Public Class Propertyforsale


Dim DM As New commonlib.DBManager(ConfigurationManager.ConnectionStrings(

"ConnectionString").ConnectionString)
Dim sSql As String
Dim retVal As New DataSet
#Region "Method"

Public Function Gallaryview_PropertyList() As DataSet


sSql = "Gallaryview_PropertyList"
retVal = DM.ExecuteDataSet(CommandType.StoredProcedure, sSql)
Return retVal
End Function
#End Region
End Class

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.

Classfile function Gallaryview_PropertyList() is returning value as DataSet. sSql is


representing procedure name that used to retrive records. retVal dataset will return records
back to codebehind file from where this function is called.

Now come back to code behind file operation.

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.

This is lengthy but very 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.

Public Sub DataTableBind(ByVal dsProperty As DataSet)


'-- Paging Variables --'
'Due to Paging Counter == 40 Records per page
Dim iCountIncre As Integer = 40 ' Records per page
Dim iPn As Integer = 0 'Current Page Number
'-- End Paging Variables --'

Dim iCount As Integer


Dim iColumn As Integer = 1
Dim dtTable As New DataTable
Dim dtCol As DataColumn
Dim dtRow As DataRow

dtCol = New DataColumn("Column1")


dtTable.Columns.Add(dtCol)
dtCol = New DataColumn("Column2")
dtTable.Columns.Add(dtCol)
dtCol = New DataColumn("Column3")
dtTable.Columns.Add(dtCol)
dtCol = New DataColumn("Column4")
dtTable.Columns.Add(dtCol)
dtRow = dtTable.NewRow
For iCount = 0 To dsProperty.Tables(0).Rows.Count - 1

'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

dtRow("Column" & iColumn) = "<a href='fulladdforrent.aspx?iPn=" & iPn.ToString


& _
"&QCD=GLV&QID=" &
dsProperty.Tables(0).Rows(iCount).Item("iPropertyID") & _
"' class='txt-grey'> <img
src='../Images/Property/thumb/" & _

dsProperty.Tables(0).Rows(iCount).Item("sImageName") & _
"' border='0' alt='Vis'/>"

'This will maintain 4 columns per row.


iColumn = iColumn + 1

'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

If iCount = dsProperty.Tables(0).Rows.Count - 1 And iColumn <= 5 Then


dtTable.Rows.Add(dtRow)
dtRow = dtTable.NewRow
End If
Next

'Add table to the dataset


Dim ds As New DataSet

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.

dtRow("Column" & iColumn) = "<a href='fulladdforrent.aspx?iPn=" & iPn.ToString &


"&QID=" &_
dsProperty.Tables(0).Rows(iCount).Item("iPropertyID") &_
"' class='txt-grey'> <img src='../Images/Property/thumb/"
&_
dsProperty.Tables(0).Rows(iCount).Item("sImageName") &_
"' border='0' alt='View'/>"

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.

Following code is used to manage paging of GridView control.

Protected Sub gvListProperty_PageIndexChanging(ByVal sender As Object, _


ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs)
& _
Handles gvListProperty.PageIndexChanging
gvListProperty.PageIndex = e.NewPageIndex
Call BindPropertyGallary()
End Sub

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.

VI. GridView within GridView


Introduction

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

First of all is the MasterGrid. You can design it as...

It has two columns, as shown. Here's a description of column zero...


Label1 is databound to Emp_dept_name, which I have described after the design info.
MasterGrid column[1] can be designed as...
In ItemTemplate we have the ChildGrid. All the columns are template columns that
contain a label (individually bound to fields in Emp_table, which is also described after the
design info, as per the column name) in their ItemTemplate. All the columns have
TextBoxes in their FooterTemplate. These are exposed when the New (in the Modify
column) button is clicked. A Modify column that will be visible only when the Edit button
in the 0th column of MasterGrid is clicked can be designed as...
I think that's sufficient to let you design all that is required.

NOTE: The DataKeyNames property of MasterGrid is set to Emp_dept_name.

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.

I have used an SQL procedure...


You can save this using the procedure name (BindMasterGrid) itself.

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.

Using the Code

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;

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


{
SqlConnection con=new SqlConnection ("
Your database connection string here(
under which you create Emp_table,Emp_dept tables)");
DataView dv=new DataView();

//
//
//*******************Use of dataview to be noted here*************************
//
//

protected void Page_Load(object sender, EventArgs e)


{
dv = ((DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty));
Page.MaintainScrollPositionOnPostBack = true;
if (!Page.IsPostBack)
{
BindMasterGrid();
BindChildGrid();
}
}

//
//To bind MasterGrid the use of strored procedure named-----BindMasterGrid----
//
//

private void BindMasterGrid()


{
SqlCommand cmd = new SqlCommand("BindMasterGrid",con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);

DataSet ds = new DataSet();


da.Fill(ds);

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.

protected void MasterGrid_RowDataBound(object sender, GridViewRowEventArgs e)


{
GridView gr;
if (e.Row.RowType == DataControlRowType.DataRow)
{

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()
{

for (int i = 0; i < MasterGrid.Rows.Count; i++)


{

((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
//

protected void MasterGrid_RowEditing(object sender, GridViewEditEventArgs e)


{
int indx = e.NewEditIndex;
Session["ind"] = indx;

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
//
//

protected void ChildGrid_RowEditing(object sender, GridViewEditEventArgs e)


{
int i = (int)Session["ind"];
GridView Childgrid = (GridView)(MasterGrid.Rows[i].Cells[1].Controls[1]);

Childgrid.EditIndex = e.NewEditIndex;
BindChildGrid();
}

//
//The event below is fired when "Cancel" button in Department column is clicked
//
//

protected void MasterGrid_RowCancelingEdit(


object sender, GridViewCancelEditEventArgs e)
{
int i = (int)Session["ind"];
MasterGrid.Rows[i].FindControl("CancelMaster").Visible = false;
GridView Childgrid = (GridView)(MasterGrid.Rows[i].Cells[1].Controls[1]);
Childgrid.Columns[3].Visible = false;
Childgrid.EditIndex = -1;
BindMasterGrid();
BindChildGrid();

//
//The event below is fired when "Cancel" button in
//Modify column(ChildGrid) is clicked
//

protected void ChildGrid_RowCancelingEdit(object sender,


GridViewCancelEditEventArgs e)
{
int i = (int)Session["ind"];
GridView Childgrid = (GridView)(MasterGrid.Rows[i].Cells[1].Controls[1]);
Childgrid.EditIndex = -1;
BindChildGrid();

//
//To update the editing done in the ChildGrid
//
//

protected void ChildGrid_RowUpdating(object sender, GridViewUpdateEventArgs e)


{
int i = (int)Session["ind"];
GridView Childgrid = (GridView)(MasterGrid.Rows[i].Cells[1].Controls[1]);

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
//
//

protected void ChildGrid_RowDeleting(object sender, GridViewDeleteEventArgs e)


{
int i = (int)Session["ind"];
GridView Childgrid = (GridView)(MasterGrid.Rows[i].Cells[1].Controls[1]);
int empno =
Convert.ToInt16(((Label)Childgrid.Rows[e.RowIndex].FindControl(
"Label1")).Text);
SqlCommand cmd =
new SqlCommand("Delete from Emp_table where Emp_no='" + empno + "'", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Childgrid.EditIndex = -1;
BindChildGrid();

//
//
//Add a record in selected department
//

protected void Add_Click(object sender, EventArgs e)


{

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
//
//

protected void New_Click(object sender, EventArgs e)


{
int i = (int)Session["ind"];
GridView Childgrid = (GridView)(MasterGrid.Rows[i].Cells[1].Controls[1]);

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
//
//

protected void Cancel_Click(object sender, EventArgs e)


{
int i = (int)Session["ind"];
GridView Childgrid = (GridView)(MasterGrid.Rows[i].Cells[1].Controls[1]);

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.

Thanking you all,

VII. Thumbnail Images in GridView using C#


Introduction

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.

Using the code

In my image viewer page

protected void Page_Load(object sender, EventArgs e)


{
if (!IsPostBack)
bindData();
}

private void bindData()


{
DataTable dt = new DataTable();
dt.Columns.Add("S.No", typeof(string));
dt.Columns.Add("grdImage", typeof(string));
DataRow dr;
int i = 1;
foreach (string file in Directory.GetFiles(Server.MapPath("Images")
+"\\","*.jpg"))
{
dr = dt.NewRow();
dr[0] = i.ToString();
dr[1] = ResolveUrl("ThumbnailCreator.aspx?ImageId="+file);
dt.Rows.Add(dr);
i += 1;
}
grdImageViewer.DataSource = dt;
grdImageViewer.DataBind();
}

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,

protected void Page_Load(object sender, EventArgs e)


{
string imgPath;
if (Request.QueryString["ImageId"] != null)
{
if (!string.IsNullOrEmpty(Request.QueryString["ImageId"].ToString()))
{
imgPath = Request.QueryString["ImageId"].ToString();
if (!string.IsNullOrEmpty(imgPath))
{
byte[] imgByte = GetImageByteArr(new Bitmap(imgPath));
MemoryStream memoryStream = new MemoryStream();
memoryStream.Write(imgByte, 0, imgByte.Length);
System.Drawing.Image imagen =
System.Drawing.Image.FromStream(memoryStream);
Response.ContentType = "image/Jpeg";
ImageResize ir = new ImageResize();
ir.File = imagen;
ir.Height = 60;
ir.Width = 60;
ir.GetThumbnail().Save(Response.OutputStream,
System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
}
}

converting image to byte array

private static byte[] GetImageByteArr(System.Drawing.Image img)


{
byte[] ImgByte;
using (MemoryStream stream = new MemoryStream())
{
img.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
ImgByte = stream.ToArray();
}
return ImgByte;
}

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.

You might also like