Friday, June 5, 2009

Displaying Two DataTables In One DataGrid

Introduction

Typically one dataGrid is bound with one DataTable. However, consider the case of two tables both having a common key column called ID. Say one table contains personal information about employees and another table contains some official information. EmployeeID is the common in both the tables and both tables have same number of rows (equal to the no of employees). How to display such tables in one DataGrid? Read on to know more.

SQL Server Databases

In order to work with this example you need to have following tables in SQL server database.
CREATE TABLE [dbo].[Table1] (
[EmployeeID] [char] (10)
COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[Name] [char] (10)
COLLATE SQL_Latin1_General_CP1_CI_AS NULL
) ON [PRIMARY]
CREATE TABLE [dbo].[Table2] (
[EmployeeID] [char] (10)
COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[Department] [char] (10)
COLLATE SQL_Latin1_General_CP1_CI_AS NULL
) ON [PRIMARY]
Note, that the two tables can be linked via EmployeeID column. This is very simplified view of the tables to keep the example simple.

Filling DataSets

Next we will fill two separate DataSets from these two tables. If you wish you can also populate them in the same DataSet.
Dim connstr As String = "Integrated Security=SSPI;
User ID=sa;Initial Catalog=Northwind;Data Source=SERVER\netsdk"
Dim cnn As New SqlConnection(connstr)
Dim da1 As New SqlDataAdapter("select * from table1", cnn)
Dim da2 As New SqlDataAdapter("select * from table2", cnn)
Dim ds1 As New DataSet()
Dim ds2 As New DataSet()

da1.Fill(ds1, "table1")
da2.Fill(ds2, "table1")
This is a typical code that you must have used many times. Note that in both the DataSets the DataTable name is same.

Setting Primary Keys

Now, we will set the primary keys for both of the tables. Why is it necessary? When we merge results of these two DataSets (discussed in next section) primary key plays important role.
Dim pk1(0) As DataColumn
Dim pk2(0) As DataColumn

pk1(0) = ds1.Tables(0).Columns("EmployeeID")
ds1.Tables(0).PrimaryKey = pk1

pk2(0) = ds2.Tables(0).Columns("EmployeeID")
ds2.Tables(0).PrimaryKey = pk2

Merging DataSets

In this step, we will merge the two DataSets by calling the Merge method of the DataSet class.
ds1.Merge(ds2, False, MissingSchemaAction.Add)
In the above method we are merging data from ds2 with ds1. While merging the DataSets they will be checked for schema information. Depending on the MissingSchemaAction set by us we can add the missing columns, raise an error or ignore the error. The second argument - True/False - indicates whether changes made to ds1 to be preserved while merging operation or not. Previously I mentioned that setting primary key is important. This is because if we do net set it the rows from ds2 will be appended to ds1. After we set the primary key they we be really merged based on the primary key.

Binding to DataGrid

Finally we will bind our DataGrid with the above merged dataset.
DataGrid1.DataSource=ds1
DataGrid1.DataBind()
That's it. See you soon with some more interesting stuff.

Highslide JS .NET

Description

Highslide JS .NET is a .NET 2.0 server control to very easily enable developers to create image thumbnails that are zoomable to their full sized versions right on the same page. Similar to lightbox type functionality, but even better and with support for multiple images zoomed concurrently.

Highslide dll is available on this website http://www.asp.net/community/control-gallery/Item.aspx?i=1710

Syntax Example

Screenshots

Using Lightbox in an ASP.NET Application (C#)

Introduction

Lightbox 2 is a free download is available on this website:

http://www.huddletogether.com/projects/lightbox2

The site describes Lightbox as, "... a simple, unobtrusive script used to overlay images on the current page." It delivers a nice, professional looking method for displaying images as overlays through the use of hyperlinks. Implementation of Lightbox is quite simple involving nothing more that adding some JavaScript and a style sheet to the page and then adding some simple attributes to each link where the effect is to be used. The download includes all of the images, style sheets, and JavaScript necessary to implement Lightbox.

Lightbox allows the developer the option of displaying images singly or in sequence. Images grouped into sequences may be viewed by the user in a slideshow like presentation that the user can control with either the mouse or the left and right arrow keys. All in all, it is a nice way to present a image gallery of thumbnails. As each image is displayed, the control is resized to fit the image and the image is centered on the page. If the image is too large, it will overrun the page so it is important to resize the images so that they will fit within the space available. Once the image is displayed, the user may click off the image or hit the Escape key in order to return to the page.



Figure 1: Lightbox in Use within an ASP.NET Web Application



Figure 2: Lightbox at Rest within an ASP.NET Web Application
(Clicking a link or an image will launch the image into Lightbox)

Getting Started

In order to get started, unzip the included project and save it to your hard drive. Open the web application and examine the contents in the solution explorer.



Figure 3: Solution Explorer

The solution contains a single web application entitled, "LightBoxDemo". The solution contains three added folders: css, images, and js. These folders contain the style sheet, images, and JavaScript provided with the Lightbox download. Additional images were added to the images folder to support the demonstration project. If starting a new project, just create the three folders using these folder names and then copy the contents over into each of the folders from the Lightbox 2 download.

Code: Default.aspx.cs

No additional code was provided to the default page's code behind file. It is in its default condition and is shown here to illustrate that no coding is required to make use of Lightbox 2.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
}


Code: Default.aspx

What little work is required to implement Lightbox 2 is contained in the Default.aspx file itself.

The markup starts with the following unmodified, default code:

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

DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

The first bit of actual work is contained in the head section of the markup; here the JavaScript is references as is the style sheet:

<head runat="server">
<%--javascript references="" for="" lightbox--=""%>
<script type="text/javascript" src="js/prototype.js">script>
<script type="text/javascript"
src="js/scriptaculous.js?load=effects,builder">script>
<script type="text/javascript" src="js/lightbox.js">script>
<%--stylesheet for="" lightbox--=""%>
<link rel="stylesheet" href="css/lightbox.css" type="text/css"
media="screen" />
<%--page title--=""%>
<title>Lightbox Demotitle>
head>

Next up, within the form, the first example shows using a simple link to an image; the "rel" tag defines the relationship to the Lightbox style sheet and that is pretty much all that you need to do to evoke the effect.

<body bgcolor="Black">
<
form id="form1" runat="server" style="background-color: #000000; color:
FFFFFF">
<%--single image="" hyperlink--=""%>
<div>
Single Image<br /><br />
<br />
<
a href="images/image-1.jpg" rel="lightbox" title="Plant
Life">Look at This Planta>
<br /><br />
div>

The next example shows how to setup a sequence of images. The defined sequence may be controlled by the user with either the mouse or the left and right arrow keys (to move back and forth through the images). Note the passing of "roadtrip1" to Lightbox; all links using 'roadtrip1' will be treated as a group of images. In this case, there are three images using that name and so those three images are treated as a single series; other images on the page that do not use 'roadtrip1' are ignored. This example as well as the next both display thumbnail versions of the image.

<%--using multiple="" images="" in="" a="" sequence="", link="" is="" thumbnail="" of="" image--=""%>
<div>
Raccoons<br /><br />

<
a href="images/bottletree1.JPG" rel="lightbox[roadtrip1]"
title="Raccoons and Baby Bottles">
<img src="images/bottletree1.JPG" width="60" height="60" alt="" />
a>

<a href="images/bottletree2.JPG" rel="lightbox[roadtrip1]"
title="Sugar Water Bottles">
<img src="images/bottletree2.JPG" width="60" height="60" alt="" />
a>

<a href="images/bottletree3.JPG" rel="lightbox[roadtrip1]"
title="More Sugar Water">
<img src="images/bottletree3.JPG" width="60" height="60" alt="" /> a>
div>
<
br />
<
br />
<
br />
<
br />

The last example shows how to setup a second sequence of images; note that these images are banded together as 'roadtrip2' and as such they will be kept separate from the other images on this page when viewed using Lightbox:

<%--using multiple="" images="" in="" a="" sequence="", link="" is="" thumbnail=""
of="" image--=""%>
<div>
Birds<br /><br />

<a href="images/AmericanGoldfinch_male.jpg" rel="lightbox[roadtrip2]"
title="American Goldfinch">
<img src="images/AmericanGoldfinch_male.JPG" width="60" height="60"
alt="" />
a>

<a href="images/birdgroup1.jpg" rel="lightbox[roadtrip2]"
title="Mixed Birds">
<img src="images/birdgroup1.JPG" width="60" height="60" alt="" />
a>
<
a href="images/doves.jpg" rel="lightbox[roadtrip2]"
title="Mourning Doves">
<img src="images/doves.JPG" width="60" height="60" alt="" />
a>
<
a href="images/goldfinch_fiesta.jpg" rel="lightbox[roadtrip2]"
title="American Goldfinches">
<img src="images/goldfinch_fiesta.JPG" width="60" height="60" alt="" />
a>

<a href="images/hummingbird.jpg" rel="lightbox[roadtrip2]"
title="Ruby Throated Hummingbird">
<img src="images/hummingbird.JPG" width="60" height="60" alt="" />
a>

<a href="images/RoseBreastedGrosbeak_male.jpg"
rel="lightbox[roadtrip2]"
title="Rose Breasted Grosbeak">
<img src="images/RoseBreastedGrosbeak_male.JPG" width="60" height="60" alt="" />
a>

div>
form>
body>
html>

Summary

Lightbox 2 is sort of a fun little tool that is very useful if one wants to display images from either links or thumbnail versions of an image. I thought it was a good find that simplified the process of displaying a large or small number of images in an interesting way and of course the price is perfect.

How to open popup windows in IE/Firefox and return values using ASP.NET and Javascript

With the forums flooded with questions of opening a popup window, passing values to the popup window and then return values back to the parent page using both Internet Explorer and Firefox, I decided to take a plunge into the subject and experiment with an easy implementation. This article explains how to transfer values between the Parent page and a Pop-up window. The code has been tested against IE7 and Firefox.
Internet Explorer(IE) contains the showModalDialog() method which proves very effective while creating a modal dialog box and displaying a html document in it. One caveat being, showModalDialog() is not a W3C implementation. So it is not supported in Firefox (as of version 2.0.0.11). Firefox supports the window.open() method. However there is no built in functionality in Firefox that keeps the popup modal. At the most, you can use ‘modal=yes’ to make the popup appear in front. However unlike the showModalDialog() in IE, you cannot restrict the user to access the parent page when the popup is opened in Firefox. In short, it is not truly modal. There are different ways to get around this problem, however in this article, we will only focus on exchanging values between the parent and popup page.
In this article, we will see how to take a simple approach and create a popup window using both IE and Firefox. In the first part, we will pass in the first name from the parent page to the popup window. In the second part, the popup window will reverse the name and return the reversed string to the parent window. All set!! Let us get started.
Part 1 - Passing value to Popup window
Step 1: Open Visual Studio. Create a new website (File > New > Website). Set the location, filename and language of the project.
Step 2: In your Default.aspx, add a label (lblFName), textbox (txtFName) and a button (btnPopup). Set the ‘Text’ property of the label to ‘FirstName’. Similarly set the ‘Text’ property of the button control to ‘Show Popup’.
Step 3: Now add the popup form. Right click your project > Add New Item > Web Form > Rename form as ‘PopupWin.aspx’ and click on Add.
Step 4: In the PopupWin.aspx, add a textbox (txtReverse) and a button (btnReverse).
Well now we have two pages, Default.aspx which is the parent page and PopupWin.aspx which will be the popup page. Let us now pass a value from Default.aspx to the popup window.
Step 5: We will invoke the popup window on the button (btnPopup) click of Default.aspx. To do so, we will use Button.Attribute.Add and call a javascript function that will open the popup window. The javascript function will be contained in a seperate pop.js file which we will create shortly. Add this code in the code behind file of your Default.aspx.
C#
protected void Page_Load(object sender, EventArgs e)
{
btnPopup.Attributes.Add("onClick", "javascript:InvokePop('" + txtFName.ClientID + "');");
}
VB.NET
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
btnPopup.Attributes.Add("onClick", "javascript:InvokePop('" & txtFName.ClientID & "');")
End Sub
Over here we are passing the ClientID of the textbox. ClientID is the identifier of the server control, generated by ASP.NET. You must be wondering why I am not passing the value of the textbox directly. Well passing the control has an advantage where there is more than one control that is passed to the popup page. While returning back the values from the popup to the parent page; it helps you to decide and determine which control receives which value. Even though we will be using only one textbox for simplicity, I thought of creating a sample which can be extended later by you to suit your needs. If the use of ClientID is not clear to you, wait till we get to part 2 of this article, and I will again touch upon the subject.
Step 6: Let us now create the javascript functionality which will open the Popup. Right click your project > Add New Item > Jscript file > Rename the file to pop.js. Add the following function to the pop.js file
function InvokePop(fname)
{
val = document.getElementById(fname).value;
// to handle in IE 7.0
if (window.showModalDialog)
{
retVal = window.showModalDialog("PopupWin.aspx?Control1=" + fname + "&ControlVal=" + val ,'Show Popup Window',"dialogHeight:90px,dialogWidth:250px,resizable:
yes,center:yes,");
document.getElementById(fname).value = retVal;
}
// to handle in Firefox
else
{
retVal = window.open("PopupWin.aspx?Control1="+fname + "&ControlVal=" + val,'Show Popup Window','height=90,width=250,resizable=yes,modal=yes');
retVal.focus();
}
}
This function accepts the textbox control, retrieve’s the value of the textbox that needs to be reversed and passes the textbox control and its value to PopupWin.aspx through query string. This is the function which will be called on the btnPopup click.
Step 7: To wire up the .js with your asp.net pages, add a link to the javascript file in both the pages as shown below:
Default.aspx
<head runat="server">
<title>Parent Pagetitle>
<script type="text/javascript" src="pop.js">script>
head>
PopupWin.aspx
<head runat="server">
<title>Popup Pagetitle>
<script type="text/javascript" src="pop.js">script>
head>
Step 8: In the code behind file of PopupWin.aspx, add the following code at the Page_Load() to retrieve the value from the querystring and display the value in the TextBox ‘txtReverse’, placed in the popup window.
C#
protected void Page_Load(object sender, EventArgs e)
{
txtReverse.Text = Request.QueryString["ControlVal"].ToString();
}
VB.NET
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
txtReverse.Text = Request.QueryString("ControlVal").ToString()
End Sub
If you are eager to test the value going from Parent page to the popup window, you can do so now. Make Default.aspx as ‘Set as Start page’ and run the sample. Enter your name in txtFName TextBox and click on Show Popup button. A popup window opens with the value entered in the Parent page.
Part 2 - Passing value from Popup window to the Parent page
In this second part, we will reverse the string and pass the reversed string back to the parent page. To do so, follow these steps:
Step 1: Add additional functions to the pop.js file which will reverse the string and return the string back to the parent page.
// pop.js
function ReverseString()
{
var originalString = document.getElementById('txtReverse').value;
var reversedString = Reverse(originalString);
RetrieveControl();
// to handle in IE 7.0
if (window.showModalDialog)
{
window.returnValue = reversedString;
window.close();
}
// to handle in Firefox
else
{
if ((window.opener != null) && (!window.opener.closed))
{
// Access the control.
window.opener.document.getElementById(ctr[1]).value = reversedString;
}
window.close();
}
}
function Reverse(str)
{
var revStr = "";
for (i=str.length - 1 ; i > - 1 ; i--)
{
revStr += str.substr(i,1);
}
return revStr;
}
function RetrieveControl()
{
//Retrieve the query string
queryStr = window.location.search.substring(1);
// Seperate the control and its value
ctrlArray = queryStr.split("&");
ctrl1 = ctrlArray[0];
//Retrieve the control passed via querystring
ctr = ctrl1.split("=");
}
As you saw in part 1, the value was passed from the parent window to the popup window and was kept in the txtReverse TextBox. The function ReverseString() retrieves the value from this textbox and passes the string to the Reverse() function which reverses the string. The reversed string is then kept in the ‘reversedString’ variable. The ‘RetrieveControl’ splits the query string and identifies the control in the parent page to which the reversed string value is to be sent.
Note: If you observe, in the IE implementation, I am not really making use of the RetrieveControl(), however in Firefox I am. If you remember, in the beginning of part1 , I had mentioned the use of ClientID, using which both controls and their values can be passed to determine which control recieves which value. This is especially needed when there are multiple controls. Well the RetrieveControl seperates the different controls and you can use the variables in this method to return values to the respective contro.l
The value is then returned to the parent window and the popup window is closed.
Step 2: Now in order to use these newly added javacript functions, just call the ReverseString() function on the btnReverse click. To do so, add the onclick attribute to the btnReverse.
<input class="button" type="button" id="btnReverse" value="Reverse value back" onclick="ReverseString();"/>
That’s it. Now test the code. Pass your name from the Parent window to the Popup window and then reverse the string and pass it back to the Parent window.

I hope you enjoyed this article !.

Searching a ListBox or DropDownList using the ListSearchExtender Control using ASP.NET AJAX

The ListSearchExtender control is a control that ships with the Microsoft AJAX Control Toolkit. ListSearchExtender enables the DropDownList and ListBox to be searchable. The user can navigate to and select an item in the list by simply typing the first few characters. This could be especially useful if there is a long list to be searched.
Let us quickly see how to use the ListSearchExtender control in our projects.
Step 1: Add a ListBox and DropDownList to the webform.
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<div>
Click on the
ListBox and type the word to search<br />
<br />
<br />
<asp:ListBox ID="ListBox1" runat="server">asp:ListBox>
<br />
<br />
<br />
Click on the
DropDownList and type the word to search<br />
<br />
<br />
<asp:DropDownList ID="DropDownList1" runat="server">
asp:DropDownList>
<br />
div>
form>
body>
Step 2: Populate the ListBox and DropDownList with a few items. Over here, we are using the ‘for’ loop to add items to the ListBox and DropDownList. If you want, you can implement a real world scenario where you can connect to a database and bind the controls to a collection.
C#
protected void Page_Load(object sender, EventArgs e)
{
for (int i = 0; i <>
{
ListBox1.Items.Add("Items " + i.ToString());
DropDownList1.Items.Add("Items " + i.ToString());
}
}
VB.NET
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
For i As Integer = 0 To 99
ListBox1.Items.Add("Items " & i.ToString())
DropDownList1.Items.Add("Items " & i.ToString())
Next i
End Sub
Step 3: Drag and drop two ’ ListSearchExtender’ controls to the form. If you have the AJAX Control Toolkit, you will find the ListSearchExtender control in the ‘Ajax Toolkit’ tab of the toolbox. Set the ‘TargetControlID’ of ListSearchExtender1 as ‘ListBox1’ and ‘TargetControlID’ of ListSearchExtender2 as ‘DropDownList1’ as shown below:
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<div>
Click on the
ListBox and type the word to search<br />
<br />
<br />
<asp:ListBox ID="ListBox1" runat="server">asp:ListBox>
<br />
<cc1:ListSearchExtender ID="ListSearchExtender1" runat="server" TargetControlID="ListBox1">
cc1:ListSearchExtender>
<br />
<br />
Click on the
DropDownList and type the word to search<br />
<br />
<br />
<asp:DropDownList ID="DropDownList1" runat="server">
asp:DropDownList>
<cc1:ListSearchExtender ID="ListSearchExtender2" runat="server" TargetControlID="DropDownList1">
cc1:ListSearchExtender>
<br />
div>
form>
body>
Run the application and click on the ListBox control. Search for an item (Eg: “Items 45”). You will observe that the ListSearchExtender searches the item and highlights it for us. Similarly try it out for the dropdownlist control too.

Popular Posts