Sunteți pe pagina 1din 126

5.

User controls

6.1 How can I include an Asp.NET page in many other Asp.Net pages so that I
don't need to rewrite the code?

One of the approaches is to write and use a UserControl. You can define the user interface, handle events and

expose properties in a UserControl, and then mark a reference and reuse these Controls in any page of your Web

application.

Here is some Sample code

6.2 Is there anything similar to web templates in ASP that I can use in
ASP.Net?

In ASP.NET, you would typically use a User Control to create reusable controls.

6.3 Are there any settings on the application level to make certain elements
appear on every page without having to manually insert code or insert
UserControls?

You can use HttpHandlers and/or HttpModules to insert information on all pages transparently. Check out Bipin

Joshi's article Extending ASP.NET with HttpHandlers and HttpModules

6.4 How to pass a parameter to a user control?

Create a User Control

Below Code goes in User Control

<asp:ImageButton id="ImageButton1" runat="server"></asp:ImageButton>

Create a property called source

VB.NET

Public Property source() As String


Get
Return ImageButton1.ImageUrl
End Get
Set(ByVal Value As String)
ImageButton1.ImageUrl = Value
End Set
End Property

C#

1
public string source
{
get
{
return ImageButton1.ImageUrl;
}
set
{
ImageButton1.ImageUrl = value;
}
}

Now in your webform:

Drag and drop User Control and set the source property.

<uc1:UCImageButton source="b2346.jpg" id="UCImageButton1" runat="server"></uc1:UCImageButton>

6.5 How to add user control dynamically into another usercontrol?

Here is an example of adding one UserControl into another:

uc1.ascx:
<asp:Label runat="server" text="uc1" ID="Label1" />
<asp:Panel runat="server" id="p1" >Panel UC1</asp:Panel>

uc2.ascx:
<br><asp:Label runat="server" text="uc2" ID="Label1" />

VB.NET

Dim uc1 As UserControl = CType(LoadControl("uc1.ascx"), UserControl)


Controls.Add(uc1)
Dim uc2 As Control = uc1.LoadControl("uc2.ascx")
Dim p1 As Control = uc1.FindControl("p1")
p1.Controls.Add(uc2)

C#

UserControl uc1 = (UserControl)LoadControl("uc1.ascx");


Controls.Add(uc1);
Control uc2 = uc1.LoadControl("uc2.ascx");
Control p1 = uc1.FindControl("p1");
p1.Controls.Add(uc2);

2
6.6 I have a function inside of the .ascx file. How can I call it from the web
application page(the .aspx file)?

All you need to do is give your user control an ID in the aspx. e.g.

<myTagTest:MarcTest id=myUC runat="server">


</myTagTest:MarcTest>

Then in your aspx code, you can simply use the id to call public methods (and properties) defined by the ascx. e.g.

VB.NET

myUC.writeData(...)

C#

myUC.writeData(...)

6.7 How to dynamically load User Controls?

Create a User Control

<P>
<asp:Button id="Button1" runat="server" Text="Button"></asp:Button></P>
<P>
<asp:Label id="Label1" runat="server"></asp:Label></P>

On button Click

VB.NET

Label1.Text = "Hello"

C#

Label1.Text = "Hello" ;

3
Create a Webform to use a UserControl

<asp:Panel id="Panel1" runat="server"></asp:Panel>

VB.NET

Dim myControl As Control = CType(Page.LoadControl("UC1.ascx"), Control)


Panel1.Controls.Add(myControl)

C#

Control myControl =(Control)Page.LoadControl("UC1.ascx");


Panel1.Controls.Add(myControl);

6.8 How to change the imageurl of the image control that exists in a
usercontrol?

In the .ascx:

<asp:Image id="Image1" runat="server"></asp:Image>

In .aspx

VB.NET

<uc1:UCImage id="UCImage1" source="b2346.jpg" runat="server"></uc1:UCImage>

Dim UC As UserControl
Dim imgUC As System.Web.UI.WebControls.Image
UC = Page.FindControl("UCImage1")
imgUC = UC.FindControl("Image1")
imgUC.ImageUrl = "b2346.jpg"

C#

UserControl UC ;
System.Web.UI.WebControls.Image imgUC ;
UC = (UserControl)Page.FindControl("UCImage1");
imgUC =(System.Web.UI.WebControls.Image)UC.FindControl("Image1");
imgUC.ImageUrl = "b2346.jpg";

4
6. Security
9.1 What is the difference between authentication and authorization?

Authentication is the process of identifying and verifying who the client accessing the server is.

For example, if you use

• Windows authentication and are browsing an ASP.NET page from server -- ASP.NET/IIS would automatically

use NTLM to authenticate you as SYNCFUSION\user1 (for example).

• Forms based authentication, then you would use an html based forms page to enter username/password --

which would then check a database and authenticate you against the username/password in the database.

Authorization is the process of determining whether an authenticated user has access to run a particular page within
an ASP.NET web application. Specifically, as an application author decide to grant or deny the authenticated user
"SYNCFUSION\user1" access to the admin.aspx page. This could be done either by explictly granting/denying rights
based on the username -- or use role based mappings to map authenticated users into roles (for example: an
administrator might map "SYNCFUSION\user1" into the "Power Users" role) and then grant/deny access based on
role names (allowing a degree of abstraction to separate out your authorization policy).

9.2 How to implement authentication via web.config?

Include the <authorization> element.

<authorization>
<deny users="?"/>
</authorization>

9.3 How to run a Web application using the permission of an authenticated


user?

Use the <identity> element in the web.config

<identity impersonate="true"/>

9.4 Which are the different ASP.NET authentication modes?

ASP.NET supports the following Authentication Providers

• Windows : Is used in conjunction with IIS authentication. Authentication is performed by IIS in one of three

ways: basic, digest, or Integrated Windows Authentication. When IIS authentication is complete, ASP.NET

5
uses the authenticated identity to authorize access

• Forms : The user provides credentials and submits the form.

• Passport : Centralized authentication service provided by Microsoft that offers a single logon and core

profile services for member sites.

• None : No Authentication provided. This is default Authentication mode

In the web.config file, you can specify this setting:

<authentication
mode= " [ Windows | Forms | Passport | None ] ">
</authentication>

9.5 How to determine the Windows User from a Web form Application?

Use the System.Security.Principal namespace.

VB.NET

dim wp as WindowsPrincipal = new WindowsPrincipal(WindowsIdentity.GetCurrent())


Response.Write(wp.Identity.Name)

C#

WindowsPrincipal wp = new WindowsPrincipal(WindowsIdentity.GetCurrent());


Response.Write(wp.Identity.Name);

9.6 After installing SP4 none of my ASP.NET pages developed using


Framework 1.0 are showing the errors related to security?

To resolve this issue, identify the user account that is used to run the program, and then assign the "Impersonate a

client after authentication" user right to that user account. To do this, follow these steps:

1. Click Start, point to Programs, point to Administrative Tools, and then click Local Security Policy.

2. Expand Local Policies, and then click User Rights Assignment.

6
3. In the right pane, double-click Impersonate a client after authentication.

4. In the Local Security Policy Setting dialog box, click Add.

5. In the Select Users or Group dialog box, click the user account that you want to add, click Add, and then

click OK.

6. Click OK.

For more details refer Overview of the "Impersonate a Client After Authentication"....

7. Client Side Scripting

11.1 How to emit client-side javascript blocks from VB.NET/C#?

The RegisterStartupScript method emits the script just before the closing tag of the Page object's <form runat=

server> element.

VB.NET

RegisterStartupScript("Sample", "<SCRIPT Language='javascript'>alert('Hello World');</SCRIPT>")

C#

RegisterStartupScript("Sample", "<SCRIPT Language='javascript'>alert('Hello World');</SCRIPT>");

Alternatively, use the RegisterClientScriptBlock method which emits the client-side script just after the opening

tag of the Page object's <form runat= server> element.

11.2 How to open a new Window using javascript function from a Link
button?

VB.NET

link.Attributes( "onClick" ) = "window.open( 'url', 'name', 'properties' )";

C#

7
link.Attributes[ "onClick" ] = "window.open( 'url', 'name', 'properties' )";

You can also check out Andy Smith's RemoteWindow Control

11.3 Is there a JavaScript Quick Reference Guide?

Here is a JavaScript Quick Reference Guide in Poster Format that you can print out and refer easily. Covers the older

and newer version of DOM and IE and Mozilla.

Danny Goodman's JavaScript and Browser Objects Quick Reference

11.4 How to set the background color of a web page using code behind?

Yes

1. In the body tag, add runat="server" and give the tag an id (e.g. id="bodyID").

2. In the class definition in the code-behind, add VB.NET

Protected bodyID As System.Web.UI.HtmlControls.HtmlGenericControl

C#

protected System.Web.UI.HtmlControls.HtmlGenericControl bodyID ;

In code, use the attributes collection to set the bgcolor attribute: VB.NET

bodyID.Attributes.Add("bgcolor", "green")

C#

bodyID.Attributes.Add("bgcolor", "green");

11.5 How to resolve error message "String constants must end with a double
quote."?

To resolve this check out PRB: The Tag Is Treated As a Closing Tag When Inside a Quoted String

11.6 Why can't I open a new browser window from within server code?

8
Server code executes on Server, whereas the new window is created on the client. You need to use client-side script

to open new window.

11.7 How to get the confirmation of Yes/No from a javascript pop-up and
display the value on the page?

Code Behind

Button1.Attributes.Add("onclick", "getMessage()")

Client Side

<SCRIPT language=javascript>
function getMessage()
{
var ans;
ans=window.confirm('Is it your confirmation.....?');

if (ans==true)
{
document.Form1.hdnbox.value='Yes';
}
else
{
document.Form1.hdnbox.value='No';}
}
</SCRIPT>

To display the Yes/No value selected by user, in your code behind file:

Response.Write(Request.Form("hdnbox"))

11.8 How to open a browser window with maximum size on click of a button?

VB.NET

Button1.Attributes.Add("onclick", "window.open('page2.aspx','','fullscreen=yes')")

C#

Button1.Attributes.Add("onclick", "window.open('page2.aspx','','fullscreen=yes')");

9
11.9 How can I know if the client browser supports active scripting?

You can detect and interept the capabilities of your client using the namespace System.Web.HttpBrowserCapabilities

VB.NET

Dim browser As System.Web.HttpBrowserCapabilities = Request.Browser


Response.Write("Support ActiveXControl: " + browser.ActiveXControls.ToString())

C#

System.Web.HttpBrowserCapabilities browser = Request.Browser;


Response.Write ("Support ActiveXControl: " + browser.ActiveXControls.ToString ());

For more details Refer: Detecting Browser Types in Web Forms

11.10 How to determine if the Browser supports javascript?

VB.NET

if Page.Request.Browser.JavaScript then
...
else
...
end if

C#

if (Page.Request.Browser.JavaScript )
{
...
}
else
{
...
}

11.11 How can I change the scroll bar color?

Use Style Sheet to change the color of scroll-bar

10
body
{
FONT-SIZE: 8pt;
COLOR: #000000;
background-color: #EEEEEE;
scrollbar-face-color: #EEEE99;
scrollbar-highlight-color: #DDDDDD;
scrollbar-shadow-color: #DEE3E7;
scrollbar-3dlight-color: #FF6600;
scrollbar-arrow-color: #006699;
scrollbar-track-color: #EFEFEF;
scrollbar-darkshadow-color: #98AAB1;
}

11.12 How to create dynamic javascripts in server side code based on server
side variables?

Here's and example:

VB.NET

Dim value As String = "pic1.jpg"


Button1.Attributes("onMouseOver") = "alert( '" + value + "');"

C#

string value = "pic1.jpg";


Button1.Attributes["onMouseOver"] = "alert( \"" + value + "\");" ;

11.13 How can I use a Timer Control to refresh a page automatically at a


specified interval?

<asp:DropDownList id="DropDownList1" runat="server" onChange="SetClientRefresh(this);">


<asp:ListItem Value="1000">1 second</asp:ListItem>
<asp:ListItem Value="2000">2 seconds</asp:ListItem>
<asp:ListItem Value="3000">3 seconds</asp:ListItem>
</asp:DropDownList>

<script language='javascript'>
var cTimeOut = null;
function SetClientRefresh(sel)

11
{
var newRefresh = sel.options[sel.selectedIndex].value;
if (cTimeOut != null)
{
window.clearTimeout(cTimeOut);
}
cTimeOut = window.setTimeout("ReLoadPage()", newRefresh);
}

function ReLoadPage()
{
window.location.reload();
}
</script>

11.14 How to open a new window without IE menus and toolbars on click of a
button?

VB.NET

Button2 .Attributes.Add ("onclick", "window.open('webform1.aspx','_blank','toolbar=no')")

C#

Button2 .Attributes.Add ("onclick", "window.open('webform1.aspx','_blank','toolbar=no')");

11.15 Does JavaScript support hashtables/ hash tables or dictionary type


data structures?

All Objects in JavaScript implicitly support hash table like syntax by virtue of behaving as Associative Arrays.

Properties of an object can be accessed in 2 ways as shown below:

object.property = value;
object["property"] = value;

So, when used in a hash table like syntax as shown above, you will be simply creating dynamic properties and

assigning values to those properties.

11.16 How to disable the right click option on a web page?

<body oncontextmenu="return false;">


...

12
</body>

Note :User can still do a View/Source in their browser menu.

11.17 How to hide a control using javascript?

document.getElementById("<id>").style.visibility="hidden";

11.18 Can I modify WebUIValidation.js?

Extract from MSDN :

You are encouraged to read the script to see more of what is going on. However, it is not recommended that you
modify these scripts, because their function is very closely tied to a particular version of the run time. If the run
time is updated, the scripts may need a corresponding update, and you will have to either lose your changes or face
problems with the scripts not working. If you must change the scripts for a particular project, take a copy of the files
and point your project to them by overriding the location of the files with a private web.config file.It is perfectly fine
to change this location to be a relative or absolute reference.

For more details refer ASP.NET Validation in Depth

11.19 How to change a Label element's text in javascript?

document.getElementById("Label1").innerText = "Changed Text";

11.20 How to resize two <div> tags on a webform?

<script>
function ResizeDivs()
{
var DivTop = document.getElementById('Top')
var DivBottom = document.getElementById('Bottom')
var BodyHeight = 0;

var DivTopHeight = 0;
var DivBottomHeight = 0;
var DivBottomPosition = 0;

BodyHeight = document.body.clientHeight;
DivBottomHeight = DivBottom.clientHeight;
DivBottom.style.top = BodyHeight - DivBottomHeight;
DivTop.style.height = DivBottom.style.top;

13
}

window.onload = ResizeDivs;
window.onresize = ResizeDivs;</script>

<div id="Top" style="position:absolute; top:0px; left:0px; background-color:#c0c0c0; overflow:auto;


width:100%">
Top Div Text:
<br>Syncfusion
<br>Sample code
<br>To
<br>autosize
<br><div>
<br>tag

</div>
<div id="Bottom" style="position:absolute; background-color:#808080; width:100%">
Bottom Div Text:
<br> Footer for the page
<br> Line1
<br> Line2
</div>

Note : if the DIV has no borders, clientHeight works. If you are going to be using a border or margins, then use

offsetHeight

11.21 How to check/ uncheck a checkbox based on the text entered in


textbox?

<asp:CheckBox id="CheckBox1" runat="server"></asp:CheckBox>


<asp:TextBox id="TextBox1" runat="server"></asp:TextBox>

<script type="text/javascript">
function chkTextEntered()
{
document.getElementById("CheckBox1").checked = true;
if(document.getElementById("TextBox1").value =="" )
{
document.getElementById("CheckBox1").checked = false;
}
}
</script>

In Page_Load

VB.NET

TextBox1.Attributes.Add("onKeyDown", "chkTextEntered();")

14
C#

TextBox1.Attributes.Add("onKeyDown", "chkTextEntered();");

11.22 How to rotate a Label Text?

<asp:Label id="Label1" style="writing-mode:tb-rl" runat="server">Label</asp:Label>

11.23 How to display a message in the status bar of a browser window?

<body onload ="window.status='First Page'">


..
</body>

11.24 How to change the BackGroundColor of a page based on the value


selected in a DropdownList?

<asp:DropDownList id="DropDownList1" runat="server" AutoPostBack="True">


<asp:ListItem Value="Red">Red</asp:ListItem>
<asp:ListItem Value="Blue">Blue</asp:ListItem>
<asp:ListItem Value="Green">Green</asp:ListItem>
</asp:DropDownList>

VB.NET

Page.RegisterClientScriptBlock("BodyStyle", "<style type='text/css'>body{background-color: " +


DropDownList1.SelectedItem.Value + ";}</style>")

C#

Page.RegisterClientScriptBlock("BodyStyle", "<style type='text/css'>body{background-color: " +


DropDownList1.SelectedItem.Value + ";}</style>");

15
11.25 How to disable a Dropdownlist once someone has selected an item in
the Dropdownlist?

<asp:DropDownList id="DropDownList1" runat="server">


<asp:ListItem Value="Red">Red</asp:ListItem>
<asp:ListItem Value="Blue">Blue</asp:ListItem>
<asp:ListItem Value="Green">Green</asp:ListItem>
</asp:DropDownList>

VB.NET

DropDownList1.Attributes.Add("onChange","this.disabled=true;" )

C#

DropDownList1.Attributes.Add("onChange","this.disabled=true;" );

11.26 How can I make a Textbox a mandatory field if a checkbox is checked


on a button click event in the client side?

<asp:TextBox id="TextBox1" style="Z-INDEX: 101; LEFT: 32px; POSITION: absolute; TOP: 104px" runat="server">
<asp:CheckBox id="CheckBox1" style="Z-INDEX: 102; LEFT: 24px; POSITION: absolute; TOP: 80px"
runat="server">
<asp:Button id="Button1" style="Z-INDEX: 103; LEFT: 32px; POSITION: absolute; TOP: 144px" runat="server"
Text="Button">

<script>
function func1()
{
if(document.getElementById ("CheckBox1").checked==true)
{
if(document.getElementById("TextBox1").value=="")
{
alert("Enter something in textbox");
}
}

}
</script>

VB.NET

Button1.Attributes.Add ("onclick" , "return func1()");

16
C#

Button1.Attributes.Add ("onclick" , "return func1()");

11.27 Why does the SmartNavigation does not work on the live server but
works perfectly on the Development Machine?

May be the domain does not have access to the aspnet_client folder which is located in the wwwroot folder. i.e the

website is not able to find the scripts for smart navigation. So set up a virtual folder to the wwwroot/aspnet_client

and it will fix the problem.

11.28 How to pop up a message box when no item in the dropdownlist is


selected before postback?

• Make sure to add a ListItem with Text="Please Choose" and Value ="".

• Add a RequiredFieldValidator with ControlToValidate= <Dropdownlist1> and Display="None"

• Add a ValidationSummary with ShowMessageBox =true

<asp:DropDownList id="DropDownList1" runat="server">


<asp:ListItem Value="">Please Choose</asp:ListItem>
<asp:ListItem Value="Faq">Faq</asp:ListItem>
<asp:ListItem Value="Tips">Tips</asp:ListItem>
<asp:ListItem Value="Tricks">Tricks</asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator id="RequiredFieldValidator1" style="Z-INDEX: 102; LEFT: 176px; POSITION: absolute;
TOP: 48px"
runat="server" ErrorMessage="Please Select an Item in the dropdownlist" ControlToValidate="DropDownList1"
Display="None"></asp:RequiredFieldValidator>
<asp:Button id="Button1" style="Z-INDEX: 104; LEFT: 128px; POSITION: absolute; TOP: 16px" runat="server"
Text="Button"></asp:Button>
<asp:ValidationSummary id="ValidationSummary1" style="Z-INDEX: 105; LEFT: 176px; POSITION: absolute; TOP:
72px"
runat="server" ShowMessageBox="True" ShowSummary="False"></asp:ValidationSummary>

11.29 Are there any resources regarding the Mozilla specific Browser Objects
and CSS information?

Official Gecko DOM Reference:

Gecko Dom Reference

17
Here is a very useful list of custom CSS styles specific to Mozilla:

XUL Planet

8. XML

12.1 How to write the data from database into an XML file?

VB.NET

'Fill the DataSet


ds.WriteXml(Server.MapPath ("products.xml" ) )

C#

//Fill the DataSet


ds.WriteXml(Server.MapPath ("products.xml" ) );

Note : Make sure you have write and modify rights.

12.2 How to read data from an XML file and display it in a DataGrid?

VB.NET

dim ds as new DataSet()


ds.ReadXml (Server.MapPath ("products.xml"))
DataGrid1.DataSource =ds
DataGrid1.DataBind()

C#

DataSet ds= new DataSet ();


ds.ReadXml (Server.MapPath ("products.xml"));
DataGrid1.DataSource =ds;
DataGrid1.DataBind();

12.3 How to read data from the XML file using FileStream and display it in a
DataGrid?

Use namespace System.IO

18
VB.NET

dim ds as new DataSet()


dim fs as FileStream = new FileStream (Server.MapPath ("products.xml"),FileMode.Open , FileAccess.Read )
ds.ReadXml (fs)
DataGrid1.DataSource = ds
DataGrid1.DataBind ()

C#

DataSet ds= new DataSet ();


FileStream fs = new FileStream (Server.MapPath ("products.xml"),FileMode.Open , FileAccess.Read );
ds.ReadXml (fs);
DataGrid1.DataSource = ds;
DataGrid1.DataBind ();

12.4 How to save an xml-string into an Xml document?

VB.NET

Dim xmlText As String = "

9. RadioButton

21.1 How can I have the first item in the radiobuttonlist selected?

VB.NET

RadioButtonList1.Items(0).Selected = true

C#

RadioButtonList1.Items[0].Selected = true;

21.2 What is the difference between a series of RadioButton controls and a


series of Checkbox controls?

RadioButton control is designed to allow users to choose atleast one option from a list of available options.

Checkbox is designed to allow users to choose from zero to all options.

19
21.3 How can I enforce that only one radiobutton gets selected among a list
of Radiobutton controls?

Set same Groupname for the radiobutton controls

10. Controls
22.1 How to close the browser window on button control click?

Method 1. This will cause a postback on button click in response to which we will send some script to close the

window.

VB.NET
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Response.Write("<script>window.close();</script>")
End Sub

C#
private void Button1_Click(object sender, System.EventArgs e)
{
Response.Write("<script>window.close();</script>");
}

Method 2. This is preferrable since there is no postback involved.

Use the Attribute collections i.e use Attributes of button control to add client side JavaScript code
VB.NET
Button1.Attributes.Add("OnClick", "window.close();")

C#
Button1.Attributes.Add("OnClick", "window.close();");

22.2 How to create server controls at runtime?

Here is an example of creating a HyperLink control in code.

VB.NET

Dim hpl As New HyperLink()


hpl.Text="Text"
hpl.NavigateUrl="http://www.syncfusion.com"'
hpl.ID="theID"
Page.Controls(1).Controls.Add(hpl)

20
C#
HyperLink hpl = new HyperLink();
hpl.Text="Text";
hpl.NavigateUrl="http://www.syncfusion.com";
hpl.ID="theID";
Page.Controls[1].Controls.Add(hpl);

22.3 How to change the text color of a linkbutton control?

<asp:LinkButton forecolor ="green" id="LinkButton1" runat="server">LinkButton</asp:LinkButton>

22.4 How to dynamically add validator controls?

VB.NET

Dim i As Integer = 1

'Textbox
Dim txtBox As TextBox = New TextBox
txtBox.ControlStyle.CssClass = "textbox"
txtBox.ID = "txtbox" + i.ToString()

'RequiredFieldValidator
Dim rqdVal As RequiredFieldValidator = New RequiredFieldValidator
rqdVal.ID = "rqdVal" + i.ToString()
rqdVal.ControlToValidate = "txtbox" + i.ToString()
rqdVal.ErrorMessage = "Please enter a value"
rqdVal.Display = ValidatorDisplay.Dynamic

'RangeValidator
Dim rngVal As RangeValidator = New RangeValidator
rngVal.ID = "rngVal" + i.ToString()
rngVal.MinimumValue = "1"
rngVal.MaximumValue = "100"
rngVal.ControlToValidate = "txtbox" + i.ToString()
rngVal.Type = ValidationDataType.Double
rngVal.ErrorMessage = " Value should be between 1 and 100"

'Add Controls on the page


Page.Controls(1).Controls.Add(txtBox)
Page.Controls(1).Controls.Add(rqdVal)
Page.Controls(1).Controls.Add(rngVal)

C#

21
int i=1;

//Textbox
TextBox txtBox = new TextBox();
txtBox.ControlStyle.CssClass = "textbox";
txtBox.ID = "txtbox" + i.ToString();

//RequiredFieldValidator
RequiredFieldValidator rqdVal = new RequiredFieldValidator();
rqdVal.ID = "rqdVal" + i.ToString();
rqdVal.ControlToValidate = "txtbox" + i.ToString();
rqdVal.ErrorMessage = "Please enter a value";
rqdVal.Display =ValidatorDisplay.Dynamic;

//RangeValidator
RangeValidator rngVal = new RangeValidator();
rngVal.ID = "rngVal" + i.ToString();
rngVal.MinimumValue = "1";
rngVal.MaximumValue = "100";
rngVal.ControlToValidate = "txtbox" + i.ToString();
rngVal.Type = ValidationDataType.Double;
rngVal.ErrorMessage = " Value should be between 1 and 100";

//Add Controls on the page


Page.Controls[1].Controls.Add (txtBox);
Page.Controls[1].Controls.Add (rqdVal);
Page.Controls[1].Controls.Add (rngVal);

22.5 How to change the image button size during runtime?

VB.NET

Dim x As New Unit("80px")


Dim y As New Unit("20px")
Dim imagestate as string= "stand"
If imagestate = "stand" then
imagebutton1.height = x
else
imagebutton1.height = y
end if

C#

Unit x = new Unit ("80px");


Unit y = new Unit("20px");
string imagestate="stand";
if( imagestate != "stand")
{
ImageButton1.Height = x;
}
else
{
ImageButton1.Height = y;
}

22
For more details Setting Web Server Control Properties Programmatically

22.6 How can I to divide the .aspx page to different parts with different
functionality in a neat and organized manner. Is there any control that can do
that?

You can use Panel controls, which render as HTML div elements. You can then show or hide the panels by

enabling/disabling them. In addition, you can specify different formatting options for different Panels/divs using

manual formatting or CSS styles.

22.7 How to maintain Scroll Position in any Page Element?

Check out Jim Ross's article Maintain Scroll Position in any Page Element

The article describes, when using a scrollable Datagrid--one inside an overflow-auto DIV control--how to maintain

the user's scroll position inside the DIV across postbacks. It does this using IE behaviors, HTC files.

22.8 DataBinder.Eval imposes performance penalty on code as it uses late


bound reflection. How can I replace this calls with explicit calls?

Change the Databinding Expression

<%#DataBinder.Eval (Container.DataItem , "StartDate" , "{0:c}")%>

to In VB.NET

<%#String.Format("{0:d}" , (CType(Container.DataItem, DataRowView))("StartDate"))%>

C#

<%#String.Format("{0:d}" , ((DataRowView)Container.DataItem)["StartDate"])%>

22.9 What is the difference between User Controls and Custom Controls?

User Controls are text files with the extension '.ascx' which enables you to make GUI re-usable controls. Its a text

file, which contains a mixture of HTML and scripting. User Controls can be edited in an editor.

23
On the other hand Custom Controls reside in compiled ( Dll ) assemblies. They are non-GUI but can emit HTML GUI

at runtime. Example of Custom Controls would be the sever controls which come bundled with the .NET SDK like

DataGrid, Repeater, DataList etc. Custom Controls are always compiled into Dll's and hence require good

programming knowledge. The purpose of Custom Controls is also to create re-usable units of code.

22.10 How to apply Style to a Web Server control programmatically?

User Interface

<asp:TextBox id="TextBox1" style="Z-INDEX: 101; LEFT: 40px; POSITION: absolute; TOP: 64px"
runat="server">Syncfusion</asp:TextBox>
<asp:Button id="Button1" style="Z-INDEX: 102; LEFT: 48px; POSITION: absolute; TOP: 120px" runat="server"
Text="Button"></asp:Button>
<asp:CheckBox id="CheckBox1" style="Z-INDEX: 103; LEFT: 40px; POSITION: absolute; TOP: 200px"
runat="server" Text="Syncfusion"></asp:CheckBox>

VB.NET

Create a function

Protected Function createStyleForControl(ByVal _forecolor As Color, ByVal _backcolor As Color, ByVal _fontbold As
Boolean) As Style
Dim s As Style = New Style
s.ForeColor = _forecolor
s.BackColor = _backcolor
s.Font.Bold = _fontbold
Return s
End Function

In Page_Load

Dim textboxStyle As Style = createStyleForControl(Color.Pink, Color.Yellow, False)


Dim buttonStyle As Style = createStyleForControl(Color.Blue, Color.Teal, True)
Dim checkboxStyle As Style = createStyleForControl(Color.AliceBlue, Color.PowderBlue, False)

TextBox1.ApplyStyle(textboxStyle)
Button1.ApplyStyle(buttonStyle)
CheckBox1.ApplyStyle(checkboxStyle)

C#

Create a function

protected Style createStyleForControl(Color _forecolor ,Color _backcolor ,bool _fontbold )


{
Style s = new Style();
s.ForeColor = _forecolor;

24
s.BackColor =_backcolor;
s.Font.Bold = _fontbold;
return s;
}

In Page_Load

Style textboxStyle=createStyleForControl (Color.Pink , Color.Yellow ,false );


Style buttonStyle=createStyleForControl (Color.Blue , Color.Teal ,true );
Style checkboxStyle =createStyleForControl (Color.AliceBlue , Color.PowderBlue ,false );

TextBox1.ApplyStyle(textboxStyle );
Button1.ApplyStyle (buttonStyle );
CheckBox1.ApplyStyle (checkboxStyle );

22.11 How can I disable a button to prevent the user from multiple clicking?

In the very last line of the button1_Click subroutine, add this line:

VB.NET

Button1.Enabled = False

C#

Button1.Enabled =false;

22.12 Why do I get the error message "Access is denied : <myctrl>" when I
try to load a Custom Control?

This is a common problem in ASP.NET. It happens because some program is scanning the Temporary ASP.NET files

folders where your assemblies are copied. They have the files open in a mode that prevents ASP.NET itself from

using the assembly file.

For solution refer PRB: Access Denied Error When You Make Code Modifications with Index Services Running

22.13 How to pass information between panels. Information entered in one


panel should be displayed in other panel?

<asp:Panel id="Panel1" runat="server" Width="271px" Height="41px">


<TABLE id="Table1" cellSpacing="1" cellPadding="1" width="300" border="1">
<TR>
<TD>

25
<P><asp:TextBox id="TextBox1" runat="server"></asp:TextBox></P>
</TD>
</TR>
<TR>
<TD>
<asp:Button id="Button1" runat="server" Text="Button"></asp:Button></TD>
</TR>
</TABLE>
</asp:Panel>
<asp:Panel id="Panel2" style="Z-INDEX: 102; LEFT: 16px; POSITION: absolute; TOP: 120px" runat="server"
Width="176px" Height="91px" Visible="False">
<asp:Label id="Label1" runat="server"></asp:Label>
</asp:Panel>

On Button Click

VB.NET

Panel2.Visible =true
Label1.Text = TextBox1.Text

C#

Panel2.Visible =true;
Label1.Text = TextBox1.Text ;

Note: Based on the criteria you can hide and show panels

22.14 Why do I get error message "The control '_ctl1' of type 'TextBox' must
be inside a form label with runat=server" while trying to place a control
inside a form dynamically?

You are probably adding the textbox into the Page directly instead of adding it to the Page's form. Try doing this:

VB.NET

Me.Page.Controls(1).Controls.Add(txtboxctrl)

C#

this.Page.Controls[1].Controls.Add(txtboxctrl);

22.15 How to implement mouseover effects in a <asp:image> web server


control?

26
<asp:Image id="Image1" runat="server" ImageUrl="b2346.jpg"></asp:Image>

VB.NET

Image1.Attributes.Add("onmouseover", "this.src='b2456.jpg'")

C#

Image1.Attributes.Add("onmouseover", "this.src='b2456.jpg'");

22.16 Is there a way to set the position of the controls dynamically?

Yes.

<asp:Button id="Button1" style="Z-INDEX: 101; LEFT: 116px; POSITION: absolute; TOP: 152px" runat="server"
Text="Move"></asp:Button>
<asp:RadioButtonList id="RadioButtonList1" style="Z-INDEX: 103; LEFT: 87px; POSITION: absolute; TOP: 27px"
runat="server" AutoPostBack="True">
<asp:ListItem Value="10px">10 pixels</asp:ListItem>
<asp:ListItem Value="100px">100 pixels</asp:ListItem>
<asp:ListItem Value="200px">200 pixels</asp:ListItem>
</asp:RadioButtonList>

VB.NET

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load


' Put user code to initialize the page here
If Not Page.IsPostBack Then
Button1.Style.Add("LEFT", "1px")
End If
End Sub 'Page_Load

Private Sub RadioButtonList1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles RadioButtonList1.SelectedIndexChanged
Button1.Style.Add("LEFT", RadioButtonList1.SelectedItem.Value.ToString())
End Sub 'RadioButtonList1_SelectedIndexChanged

C#

private void Page_Load(object sender, System.EventArgs e)


{
// Put user code to initialize the page here

27
if (!Page.IsPostBack )
{
Button1.Style.Add("LEFT", "1px");
}
}

private void RadioButtonList1_SelectedIndexChanged(object sender, System.EventArgs e)


{
Button1.Style.Add("LEFT",RadioButtonList1.SelectedItem.Value.ToString());
}

22.17 How can I set the maximum and minimum value for RangeValidator
based on two dates?

<asp:textbox id="TextBox1" runat="server"></asp:textbox>


<asp:rangevalidator id="RangeValidator1" type="Date" controltovalidate="TextBox1" runat="server"
errormessage="Not in range" />
<asp:button id="Button1" runat="server" text="Button"></asp:button>

VB.NET

...
Dim dtMinDate As DateTime
Dim dtMaxDate As DateTime
dtMinDate = Convert.ToDateTime("04/25/04")
dtMaxDate = Convert.ToDateTime("10/17/04")
RangeValidator1.MinimumValue = dtMinDate
RangeValidator1.MaximumValue = dtMaxDate
TextBox1.Text = dtMaxDate.ToShortDateString
RangeValidator1.ErrorMessage = "Not in Range of " & dtMinDate.ToShortDateString() & " to " &
dtMaxDate.ToShortDateString()

C#

DateTime dtMinDate ;
DateTime dtMaxDate ;
dtMinDate = Convert.ToDateTime("04/25/04");
dtMaxDate = Convert.ToDateTime("10/17/04");
RangeValidator1.MinimumValue = dtMinDate.ToShortDateString () ;
RangeValidator1.MaximumValue = dtMaxDate.ToShortDateString () ;
TextBox1.Text = dtMaxDate.ToShortDateString();
RangeValidator1.ErrorMessage = "Not in Range of " + dtMinDate.ToShortDateString() + " to " +
dtMaxDate.ToShortDateString();

22.18 How to specifiy the hspace and vspace in a <asp:Image>?

VB.NET

28
Image1.Attributes.Add("hspace", "50")
Image1.Attributes.Add("vspace", "50")

C#

Image1.Attributes.Add("hspace", "50") ;
Image1.Attributes.Add("vspace", "50") ;

22.19 How to disable status bar messages for Hyperlink Controls?

VB.NET

HyperLink1.Attributes.Add("onMouseOver", "window.status=' '; return true;")

C#

HyperLink1.Attributes.Add("onMouseOver", "window.status=' '; return true;") ;

22.20 How to get the list of all System.Web.UI.WebControls in my page?

<asp:Repeater runat="server" DataSource='<%# GetControls() %>' ID="Repeater1">


<HeaderTemplate>
<ul>
</HeaderTemplate>
<ItemTemplate>
<li>
<%# DataBinder.Eval(Container.DataItem, "Name") %>
</li>
</ItemTemplate>
<FooterTemplate>
</ul>
</FooterTemplate>
</asp:Repeater>

VB.NET

Protected Function GetControls() As ArrayList


Dim arrList As New ArrayList()
Dim t As Type
For Each t In GetType(Page).Assembly.GetTypes()
If t.Namespace = "System.Web.UI.WebControls" And GetType(Control).IsAssignableFrom(t) Then
arrList.Add(t)

29
End If
Next
Return arrList
End Function 'GetControls

'In Page_Load
DataBind()

C#

protected ArrayList GetControls()


{
ArrayList arrList = new ArrayList();
foreach (Type t in typeof(Page ).Assembly.GetTypes())
{
if (t.Namespace == "System.Web.UI.WebControls" && typeof(Control).IsAssignableFrom(t))
arrList.Add(t);
}
return arrList;
}

//In Page_Load
DataBind();

22.21 How to set the vertical align of a TableCell programmatically?

VB.NET

Dim tbl As New TableCell()


'VerticalAlign is enumeration in System.Web.UI.WebControls namespace
tbl.VerticalAlign = VerticalAlign.Top

C#

TableCell tbl=new TableCell();


//VerticalAlign is enumeration in System.Web.UI.WebControls namespace
tbl.VerticalAlign = VerticalAlign.Top;

22.22 How to control viewstate on individual controls?

You can set the EnableViewState property of the control. You should disable viewstate for any control that doesn't

use it to gurantee optimum performance.

11. Table Control

30
23.1 How to create a table control dynamically to populate data?

<asp:Table id="Table1" runat="server"></asp:Table>

VB.NET

Dim mycn As SqlConnection


Dim myda As SqlDataAdapter
Dim ds As DataSet
mycn = New SqlConnection("server = localhost;uid=sa;password=;database=northwind")
myda = New SqlDataAdapter("Select Employeeid, FirstName , LastName from employees", mycn)
ds = New DataSet
myda.Fill(ds, "Employees")

Dim dc As DataColumn
Dim dr As DataRow
For Each dr In ds.Tables(0).Rows
Dim trow As New TableRow
For Each dc In ds.Tables(0).Columns
Dim tcell As New TableCell
tcell.Controls.Add(New LiteralControl(dr(dc.ColumnName).ToString))
trow.Cells.Add(tcell)
Next
Table1.Rows.Add(trow)
Next

C#

SqlConnection mycn ;
SqlDataAdapter myda ;
DataSet ds ;
mycn = new SqlConnection("server = localhost;uid=sa;password=;database=northwind");
myda = new SqlDataAdapter("Select Employeeid, FirstName , LastName from employees", mycn);
ds = new DataSet();
myda.Fill(ds, "Employees");

TableRow trow ;
TableCell tcell;
foreach (DataRow dr in ds.Tables[0].Rows)
{
trow = new TableRow ();
foreach( DataColumn dc in ds.Tables[0].Columns)
{
tcell= new TableCell ();
tcell.Controls.Add(new LiteralControl(dr[dc.ColumnName].ToString()));
trow.Cells.Add(tcell);
}
Table1.Rows.Add(trow);
}

23.2 How to limit table cell size with long strings?

31
Set style property for the table cell as

style="WORD-BREAK:break-all"

23.3 How to use a Table control to display data vertically?

<asp:Table id="Table1" runat="server"></asp:Table>

VB.NET

'Populate the DataSet ds


Dim dr As DataRow
For Each dc In ds.Tables(0).Columns
Dim trow As New TableRow()
Dim tcellcolname As New TableCell()
'To Display the Column Names
For Each dr In ds.Tables(0).Rows
tcellcolname.Text = dc.ColumnName
trow.BackColor = System.Drawing.Color.Beige
tcellcolname.BackColor = System.Drawing.Color.AliceBlue
'Populate the TableCell with the Column Name
tcellcolname.Controls.Add(New LiteralControl(dc.ColumnName.ToString))
Next
trow.Cells.Add(tcellcolname)
'To Display the Column Data
For Each dr In ds.Tables(0).Rows
Dim tcellcoldata As New TableCell()
'Populate the TableCell with the Column Data
tcellcoldata.Controls.Add(New LiteralControl(dr(dc.ColumnName).ToString))
trow.Cells.Add(tcellcoldata)
Next
Table1.Rows.Add(trow)
Next

C#

//Populate the DataSet ds


foreach(DataColumn dc in ds.Tables[0].Columns )
{
TableRow trow = new TableRow();
TableCell tcellcolname = new TableCell() ;
foreach(DataRow dr in ds.Tables[0].Rows )
{
tcellcolname.Text = dc.ColumnName ;
trow.BackColor = System.Drawing.Color.Beige ;
tcellcolname.BackColor = System.Drawing.Color.AliceBlue ;
//Populate the TableCell with the Column Name
tcellcolname.Controls.Add(new LiteralControl(dc.ColumnName.ToString())) ;
}

32
trow.Cells.Add(tcellcolname) ;
//To Display the Column Data
foreach(DataRow dr in ds.Tables[0].Rows )
{
TableCell tcellcoldata =new TableCell() ;
//Populate the TableCell with the Column Data
tcellcoldata.Controls.Add(new LiteralControl(dr[dc.ColumnName].ToString())) ;
trow.Cells.Add(tcellcoldata);
}
Table1.Rows.Add(trow) ;
}

23.4 Are there any IE specific performance imporvement possible with Table
Layout?

In IE5 and later, significantly faster Table Rendering is now possible. Here is some information in MSDN : Enhancing

Table Presentation.

Among other things, you can specific col specific widths using the colgroup tag or col tag and also set the visibility

of rows and columns using special styles.

12. DataGrid

Why do I get the Columns twice in the datagrid. I am using BoundColumns


and TemplateColumns in DataGrid?

Set the AutogenerateColumns= False. By Default it is set to true for a datagrid

25.2 How to Format and display currency with n decimal points in a


BoundColumn.

Set the Dataformatstring of the boundcolumn to {0:Nn} where n=> number of decimal points For more details refer

Format Function

25.3 How do I specify more than one parameter for my HyperlinkColumn?

<asp:DataGrid id="DataGrid1" runat="server" AutoGenerateColumns="False">


<Columns>
<asp:TemplateColumn HeaderText="Sample Column">
<ItemTemplate>
<asp:Hyperlink runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "ProductName").ToString()%>'
NavigateUrl='<%# "page1.aspx?id=" + DataBinder.Eval(Container.DataItem,"ProductId").ToString() + "&Name=" +
DataBinder.Eval(Container.DataItem,"ProductName").ToString()%>' ID="Hyperlink1" NAME="Hyperlink1"/>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>

33
25.4 Why am I getting an 'AllowCustomPaging must be true and
VirtualItemCount must be set for a DataGrid with ID MyDataGrid when
AllowPaging is set to true and the selected datasource does not implement
ICollection' Error?

You are probably trying to implement paging in a DataGrid while binding the DataGrid with a DataReader. To fix this,

instead of using a DataReader use a DataSet

25.5 How do I use a "helper function" to change the column value as Boolean
in database to be displayed as Yes/No in Datagrid?

<asp:DataGrid id="DataGrid1" runat="server" AutoGenerateColumns="False">


<Columns>
<asp:TemplateColumn HeaderText="Status">
<ItemTemplate>
<%#ShowStatus(bool.Parse(DataBinder.Eval(Container.DataItem,"Discontinued").ToString()))%>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>

VB.NET

protected Function ShowStatus(ByVal someval as boolean)


If someval = true Then
ShowStatus = "Yes"
Else
ShowStatus = "No"
End If
End Function

C#

protected string ShowStatus(bool someval)


{
if (someval == true)
{
return "Yes";
}
else
{
return "No";
}
}

25.6 How to display only date part in the Datagrid if the Date is of DateTime

34
datatype in the database?

Set the DateFormatString as {0:d}

25.7 How to open a new window with multiple parameters when clicked on a
hyperlink in a column in a datagrid?

The column should be defined as a TemplateColumn as follows and the NavigateUrl for that hyperlink can be set as

follows to open a new window with parameters varying based on the row in which the hyperlink is present.

<asp:TemplateColumn >
<ItemTemplate>
<asp:Hyperlink ID="Hyperlink2" Runat="Server"
NavigateUrl= <%#"javascript:my_window=window.open('webform2.aspx?id=" +
DataBinder.Eval(Container.DataItem,"productid").ToString() + "&Supplierid=" +
DataBinder.Eval(Container.DataItem,"SupplierID").ToString() +
"','my_window','width=300,height=300');my_window.focus()" %>
text=<%#DataBinder.Eval(Container.DataItem,"ProductName").ToString() %>>
</asp:Hyperlink>
</ItemTemplate>
</asp:TemplateColumn>

The above approach would avoid the problem of showing the screen of [Object] on the parent page

25.8 How to display hierarchical data in a DataGrid?

Check out Denis Bauer's custom control HierarGrid

25.9 How do I conditionally set the text color of a cell in my Datagrid based
on the cell's/fields's value?

In the ItemDataBound event you can access the Cells() collection of the current Datagrid item (or row) and set it's

ForeColor.

<asp:DataGrid OnItemDataBound="ItemDB" id="DataGrid1" runat="server"></asp:DataGrid>

VB.NET

protected Sub ItemDB(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs)


If (e.Item.ItemType = ListItemType.Item Or _
e.Item.ItemType = ListItemType.AlternatingItem) Then
If e.Item.DataItem(6) > 15 Then
e.Item.Cells(6).ForeColor = System.Drawing.Color.Green
Else
e.Item.Cells(6).ForeColor = System.Drawing.Color.Red
End If

35
End If
End Sub

C#

protected void ItemDB(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)


{
if((e.Item.ItemType ==ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem) )
{
if (Convert.ToInt16 (e.Item.Cells[6].Text) >15 )
{
e.Item.Cells[6].ForeColor = System.Drawing.Color.Green;
}
else
{
e.Item.Cells[6].ForeColor = System.Drawing.Color.Red;
}
}
}

In Cells[x]/Cells(x) x=> index number to the list of fields in the row.

25.10 When I open my new window using Javascript, all elements appear
great, but the original window just displays [Object] why?

Check out How to open a new window with multiple parameters using datagrid?

25.11 How to populate a DataGrid using a DataReader?

<asp:DataGrid id="DataGrid1" runat="server"></asp:DataGrid>

Use Namespace System.Data.SqlClient

VB.NET

Dim cn As SqlConnection
Dim cmd As SqlCommand
Dim rdr As SqlDataReader

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load


'Put user code to initialize the page here
Try
cn = New SqlConnection("server=localhost;uid=sa;pwd=;database=northwind")
cmd = New SqlCommand("select * from employees ", cn)
cn.Open()
rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
DataGrid1.DataSource = rdr
DataGrid1.DataBind()
Catch ex As Exception
Response.Write(ex.Message.ToString())

36
Finally
rdr.Close()
cn.Close()
End Try
End Sub 'Page_Load

C#

SqlConnection cn ;
SqlCommand cmd ;
SqlDataReader rdr ;
private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
try
{
cn = new SqlConnection("server=localhost;uid=sa;pwd=;database=northwind");
cmd = new SqlCommand( "select * from employees ", cn);
cn.Open();
rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection );
DataGrid1.DataSource = rdr;
DataGrid1.DataBind();
}
catch (Exception ex)
{
Response.Write (ex.Message.ToString ());
}
finally
{
rdr.Close();
cn.Close();
}
}

25.12 How to populate a DataGrid using a DataSet?

<asp:DataGrid id="DataGrid1" runat="server"></asp:DataGrid>

Use the namespace System.Data.SqlClient

VB.NET

Dim cn As SqlConnection
Dim da As SqlDataAdapter
Dim ds As DataSet
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
cn = New SqlConnection("Server=localhost;uid=sa;pwd=;database=northwind")
da = New SqlDataAdapter("Select * from products", cn)
ds = New DataSet
da.Fill(ds, "Products")
DataGrid1.DataSource = ds.Tables(0)
'DataGrid1.DataSource = ds
'DataGrid1.DataSource = ds.Tables("Product")

37
DataGrid1.DataBind()
End Sub

C#

SqlConnection cn;
SqlDataAdapter da;
DataSet ds;
private void Page_Load(object sender, System.EventArgs e)
{
cn= new SqlConnection ("Server=localhost;uid=sa;pwd=;database=northwind");
da= new SqlDataAdapter ("SELECT * FROM Products ", cn);
ds= new DataSet ();
da.Fill (ds, "Product");
DataGrid1.DataSource =ds.Tables[0];
//DataGrid1.DataSource= ds;
//DataGrid1.DataSource= ds.Tables["Products"];
DataGrid1.DataBind ();
}

25.13 Why do I get "Could not lock file" and "cannot open file" exceptions
when bound to a mdb file?

You could get this error for the following reasons:

1. When you create a project afresh, add a new OleDbDataAdapter to the form and link to the mdb file, the

connection object created in the process will keep an open connection to the mdb file which is what will

cause the above "Could not lock file" exception during runtime. To workaround this, go to "Server Explorer"

in your IDE, right click on the corresponding "Connection entry" and select Close Connection. This should

fix the problem.

2. The "cannot open file" exception could then occur if you have not provided enough permissions on the mdb

file to allow the .net runtime to lock it. To ensure enough permissions, open it's properties, select the

Security tab and add a "Everyone" account granting "Full Control" to it. This should let the .net runtime lock

the file.

25.14 I am binding the DataGrid to a datasource at runtime. After binding I


want to populate a listbox with the column headers from the datagrid. How
can I reference the column headertext for each column in the datagrid and
then add them to my listbox?

In the ItemDataBound Event write following code VB.NET

Dim i As Integer = 0
If e.Item.ItemType = ListItemType.Header Then

38
For i = 0 To e.Item.Cells.Count -1
Me.ListBox1.Items.Add(e.Item.Cells(i).Text)
Next
End If

C#

if (e.Item.ItemType== ListItemType.Header)
{
for(int i = 0; i <= e.Item.Cells.Count-1 ; i++)
{
this.ListBox1.Items.Add(new ListItem(e.Item.Cells[i].Text));
}
}

25.15 When I try to do an Update from my Datagrid, I keep getting the


old/original values. Why?

This could happen if you are calling .DataBind everytime the Page is loaded

To avoid this call Databind only for the first request and not for subsequent postbacks.

VB.NET

if not Page.IsPostBack then


'Your databinding code
end if

C#

if (!Page.IsPostBack)
{
'Your databinding code
}

25.16 How can I sort a BoundColumn?

Set the SortExpression to the Field Name

25.17 How can I hide the HeaderText of the DataGrid?

Set the ShowHeader property of the DataGrid to false

39
25.18 How to add a mailto link inside a datagrid?

<asp:TemplateColumn HeaderText="Email Address" HeaderStyle-Font-Bold="True">


<ItemTemplate>
<a href="Mailto:<%# DataBinder.Eval(Container.DataItem,"email").ToString() %>">
<%# DataBinder.Eval(Container.DataItem,"email").ToString() %>
</a>
</ItemTemplate>
</asp:TemplateColumn>

25.19 How to do Simple sorting using DataGrid?

<asp:DataGrid id="DataGrid1" AllowSorting =True OnSortCommand ="SortData" runat="server"></asp:DataGrid>

VB.NET

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load


'Put user code to initialize the page here
If Not Page.IsPostBack Then
BindDataGrid("ProductId")
End If
End Sub

Protected Sub SortData(ByVal source As Object, ByVal e As


System.Web.UI.WebControls.DataGridSortCommandEventArgs)
BindDataGrid(e.SortExpression.ToString())
End Sub

Sub BindDataGrid(ByVal sortfield As String)


'Fill the Dataset
'.....
Dim dv As DataView = ds.Tables(0).DefaultView
dv.Sort = sortfield
DataGrid1.DataSource = dv
DataGrid1.DataBind()
End Sub

C#

private void Page_Load(object sender, System.EventArgs e)


{
// Put user code to initialize the page here
if(! Page.IsPostBack )
{
BindDataGrid("ProductId");
}
}

protected void SortData(Object source, System.Web.UI.WebControls.DataGridSortCommandEventArgs e )

40
{
BindDataGrid(e.SortExpression.ToString());
}

void BindDataGrid(string sortfield)


{
//Fill the Dataset
//.....
DataView dv = ds.Tables[0].DefaultView;
dv.Sort = sortfield;
DataGrid1.DataSource = dv;
DataGrid1.DataBind();
}

25.20 How to do Paging using DataGrid?

<asp:DataGrid id="DataGrid1" AllowPaging =true PageSize =5 OnPageIndexChanged ="PageData"


runat="server"></asp:DataGrid>

VB.NET

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load


'Put user code to initialize the page here
If Not Page.IsPostBack Then
Binddata()
End If
End Sub

Protected Sub PageData(ByVal source As Object, ByVal e As


System.Web.UI.WebControls.DataGridPageChangedEventArgs)
DataGrid1.CurrentPageIndex = e.NewPageIndex
Binddata()
End Sub

Sub Binddata()
'Populate the DataGrid using DataSet
End Sub

C#

private void Page_Load(object sender, System.EventArgs e)


{
// Put user code to initialize the page here
if(! Page.IsPostBack )
{
Binddata();
}
}

protected void PageData(Object source , System.Web.UI.WebControls.DataGridPageChangedEventArgs e )


{
DataGrid1.CurrentPageIndex = e.NewPageIndex;
Binddata();

41
}

void Binddata()
{
//Populate the DataGrid using DataSet
}

25.21 How to display an image field in each row of DataGrid?

If the image field is a string representing a image file name, then:

...
<asp:TemplateColumn>
<ItemTemplate>
<img src='<%#DataBinder.Eval (Container.DataItem, "Photo")%>'>
</ItemTemplate>
</asp:TemplateColumn>
...

25.22 How to get the DataField name of a BoundColumn from code-behind?

Try

VB.NET

Dim bc As BoundColumn = CType(Me.DataGrid1.Columns(1), BoundColumn)


Response.Write(bc.DataField)

C# C#

BoundColumn bc = (BoundColumn)this.DataGrid1.Columns[1];
Response.Write(bc.DataField);

25.23 How to confirm delete in DataGrid using PushButton?

<asp:DataGrid id="DataGrid1" AutoGenerateColumns="False" OnDeleteCommand ="DelCmd" OnItemCreated


="ItemCrt" DataKeyField="Employeeid" runat="server">
<Columns>
<asp:ButtonColumn Text="Delete" ButtonType="PushButton" CommandName="Delete"></asp:ButtonColumn>
<asp:BoundColumn DataField="firstname" HeaderText="First Name"></asp:BoundColumn>
</Columns>
</asp:DataGrid>

42
VB.NET

Dim sqlStmt As String


Dim conString As String
Dim cn As SqlConnection = Nothing
Dim da As SqlDataAdapter = Nothing
Dim ds As DataSet

Private Sub Page_Load(sender As Object, e As System.EventArgs)


conString = "server=localhost;database=Northwind;uid=sa;pwd=;"
cn = New SqlConnection(conString)
If Not Page.IsPostBack Then
BindData()
End If
End Sub 'Page_Load

Sub BindData()
sqlStmt = "select * from emp "
ds = New DataSet()
da = New SqlDataAdapter(sqlStmt, cn)
da.Fill(ds, "t1")
DataGrid1.DataSource = ds
DataGrid1.DataBind()
End Sub 'BindData

Protected Sub ItemCrt(sender As Object, e As DataGridItemEventArgs)


Select Case e.Item.ItemType
Case ListItemType.Item, ListItemType.AlternatingItem
Dim btn As Button = CType(e.Item.Cells(0).Controls(0), Button)
btn.Attributes.Add("onclick", "return confirm('are you sure you want to delete this')")
Exit
End Select
End Sub 'ItemCrt

Protected Sub DelCmd(sender As [Object], e As DataGridCommandEventArgs)


DeleteRow(Me.DataGrid1.DataKeys(e.Item.ItemIndex).ToString())
BindData()
End Sub 'DelCmd

Private Sub DeleteRow(empid As String)


Dim cmd As New SqlCommand("DELETE FROM Emp WHERE employeeid =" + empid, cn)
cn.Open()
cmd.ExecuteNonQuery()
cn.Close()
End Sub 'DeleteRow

C#

string sqlStmt ;
string conString ;
SqlConnection cn =null;
SqlDataAdapter da =null;
DataSet ds;

private void Page_Load(object sender, System.EventArgs e)


{

43
conString = "server=localhost;database=Northwind;uid=sa;pwd=;";
cn = new SqlConnection(conString);
if (!Page.IsPostBack )
{
BindData();
}
}

void BindData()
{
sqlStmt = "select * from emp ";
ds= new DataSet ();
da = new SqlDataAdapter (sqlStmt, cn);
da.Fill (ds,"t1");
DataGrid1.DataSource =ds;
DataGrid1.DataBind ();
}

protected void ItemCrt(object sender, DataGridItemEventArgs e)


{
switch(e.Item.ItemType)
{
case ListItemType.Item:
case ListItemType.AlternatingItem:
{
Button btn = (Button)e.Item.Cells[0].Controls[0];
btn.Attributes.Add("onclick",
"return confirm('are you sure you want to delete this')");
break;
}
}
}

protected void DelCmd(Object sender , DataGridCommandEventArgs e )


{
DeleteRow (this.DataGrid1.DataKeys[e.Item.ItemIndex].ToString());
BindData();
}

private void DeleteRow(string empid)


{
SqlCommand cmd = new SqlCommand("DELETE FROM Emp WHERE employeeid ="+ empid ,cn);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}

25.24 How to do Bidirectional Sorting in the DataGrid?

<asp:DataGrid id="DataGrid1" OnSortCommand ="SortDataGrid" runat="server" AllowSorting="True"


EnableViewState="False"></asp:DataGrid>

VB.NET

Protected SQLStmt As String = "Select * from Products "


Dim myconnection As SqlConnection

44
Dim myda As SqlDataAdapter
Dim ds As DataSet
Dim strConn As String
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Put user code to initialize the page here
binddata()
End Sub

Sub binddata()
strConn = "Server=localhost;uid=sa;password=;database=northwind;"
myconnection = New SqlConnection(strConn)
myda = New SqlDataAdapter(SQLStmt, myconnection)
ds = New DataSet
myda.Fill(ds, "AllTables")
DataGrid1.DataSource = ds
DataGrid1.DataBind()
End Sub

Protected Sub SortDataGrid(ByVal source As Object, ByVal e As


System.Web.UI.WebControls.DataGridSortCommandEventArgs)
If ViewState("SortOrder") Is Nothing Then
ViewState("SortOrder") = " ASC"
ElseIf ViewState("SortOrder") = " ASC" Then
ViewState("SortOrder") = " DESC"
Else
ViewState("SortOrder") = " ASC"
End If
SQLStmt = SQLStmt & " ORDER BY " & e.SortExpression & " " & ViewState("SortOrder")
binddata()
End Sub

C#

SqlConnection myconnection ;
SqlDataAdapter myda ;
DataSet ds ;
String strConn ;
string SQLStmt= "Select * from Products ";
private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
binddata();
}

void binddata()
{
strConn = "Server=localhost;uid=sa;password=;database=northwind;";
myconnection =new SqlConnection(strConn);
myda = new SqlDataAdapter(SQLStmt, myconnection);
ds = new DataSet();
myda.Fill(ds, "AllTables");
DataGrid1.DataSource = ds;
DataGrid1.DataBind();
}

protected void SortDataGrid(object source , System.Web.UI.WebControls.DataGridSortCommandEventArgs e )


{
if (ViewState["SortOrder"] ==null)
{
ViewState["SortOrder"] = " ASC";
}
else if (ViewState["SortOrder"].ToString () == " ASC" )

45
{
ViewState["SortOrder"] = " DESC";
}
else
{
ViewState["SortOrder"] = " ASC";
}
SQLStmt = SQLStmt + " ORDER BY " + e.SortExpression.ToString () + " " + ViewState["SortOrder"];
binddata();
}

25.25 How to have mutually exclusive radiobutton controls in a datagrid.

<asp:DataGrid id="DataGrid1" AutoGenerateColumns="False" runat="server">


<Columns>
<asp:TemplateColumn HeaderText="FirstName">
<ItemTemplate>
<input type="radio" name="optSelectedName"
value=<%#DataBinder.Eval(Container.DataItem, "FirstName") %>
onclick="javascript:txtFname.value = this.value;"><%#DataBinder.Eval(Container.DataItem, "FirstName") %>
<br>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
<asp:Button id="Button1" style="Z-INDEX: 101; LEFT: 154px; POSITION: absolute; TOP: 103px" runat="server"
Text="Button"></asp:Button>
<div style="VISIBILITY: hidden">
<asp:TextBox ID="txtFname" Runat="server" />
</div>

VB.NET

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load


'Bind the Datagrid with dataSet
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click


Response.Write("You have selected :" & txtFname.Text)
End Sub

C#

private void Page_Load(object sender, System.EventArgs e)


{
//Bind the datagrid to dataset
}
private void Button1_Click(object sender, System.EventArgs e)
{
Response.Write("You have selected :" + txtFname.Text);
}

46
25.26 How to add a TemplateColumn dynamically to the datagrid?

<asp:DataGrid id="DataGrid1" AutoGenerateColumns=False runat="server"></asp:DataGrid>

VB.NET

Create class

Public Class newLabelColumn


Implements ITemplate

Public Sub New()


End Sub 'New

'Add constructor stuff here


Public Sub InstantiateIn(ByVal container As Control) Implements System.Web.UI.ITemplate.InstantiateIn
Dim label1 As New Label
AddHandler label1.DataBinding, AddressOf Me.BindLabelColumn
container.Controls.Add(label1)
End Sub 'InstantiateIn

Public Sub BindLabelColumn(ByVal sender As Object, ByVal e As EventArgs)


Dim lbl As Label = CType(sender, Label)
Dim container As DataGridItem = CType(lbl.NamingContainer, DataGridItem)
Dim strVals As [String] = Convert.ToString(DataBinder.Eval(CType(container, DataGridItem).DataItem,
"LastName")) + ", " + Convert.ToString(DataBinder.Eval(CType(container, DataGridItem).DataItem, "FirstName"))
lbl.Text = strVals
End Sub 'BindLabelColumn
End Class 'newLabelColumn

'Fill the Dataset


Dim objtc As New TemplateColumn
objtc.HeaderText = "Full Name"
objtc.ItemTemplate = New newLabelColumn
DataGrid1.Columns.Add(objtc)
DataGrid1.DataSource = ds
DataGrid1.DataBind()

C#

Create class

public class newLabelColumn : ITemplate


{
public newLabelColumn()
{
//Add constructor stuff here
}
public void InstantiateIn(Control container)
{
Label label1 = new Label();

47
label1.DataBinding += new EventHandler(this.BindLabelColumn);
container.Controls.Add(label1);
}
public void BindLabelColumn(object sender, EventArgs e)
{
Label lbl = (Label)sender;
DataGridItem container = (DataGridItem)lbl.NamingContainer ;
String strVals =
Convert.ToString(DataBinder.Eval(((DataGridItem)container).DataItem, "LastName")) + ", "
+
Convert.ToString(DataBinder.Eval(((DataGridItem)container).DataItem, "FirstName")) ;
lbl.Text = strVals;
}
}

//Fill the DataSet


TemplateColumn objtc = new TemplateColumn();
objtc.HeaderText = "Full Name";
objtc.ItemTemplate = new newLabelColumn();
DataGrid1.Columns.Add(objtc);
DataGrid1.DataSource =ds;
DataGrid1.DataBind();

25.27 How to edit data in the DataGrid using a TemplateColumn?

<asp:DataGrid id="DataGrid1" AutoGenerateColumns=False OnCancelCommand ="CancelCmd" OnEditCommand


="EditCmd"
OnUpdateCommand ="UpdateCmd" DataKeyField="Employeeid" runat="server">
<Columns>
<asp:TemplateColumn HeaderText ="Employee Information">
<ItemTemplate >
<asp:label ID="lblLastName" Runat=server text=<%#DataBinder.Eval(Container.DataItem,
"Lastname")%>></asp:Label>
, <asp:label ID="lblFirstName" Runat=server text=<%#DataBinder.Eval(Container.DataItem,
"Firstname")%>></asp:Label>
<br>
<asp:label ID="lblTitle" Runat=server text=<%#DataBinder.Eval(Container.DataItem, "Title")%>>
</ItemTemplate>
<EditItemTemplate >
<asp:TextBox runat=server ID="txtLastName" Text=<%#DataBinder.Eval(Container.DataItem,
"lastname")%>></asp:TextBox>
<asp:RequiredFieldValidator id="rqdfldLastName" Display ="Static" Runat =server ErrorMessage ="*"
ControlToValidate ="txtLastName">
<asp:TextBox runat=server ID="txtFirstName" text=<%#DataBinder.Eval(Container.DataItem,
"Firstname")%>></asp:TextBox>
<asp:RequiredFieldValidator id="rqdfldFirstName" Display ="Static" Runat =server ErrorMessage ="*"
ControlToValidate ="txtFirstName">
<asp:TextBox runat=server ID="txtTitle" Text=<%#DataBinder.Eval(Container.DataItem,
"title")%>></asp:TextBox>
</EditItemTemplate>
</asp:TemplateColumn>
<asp:EditCommandColumn ButtonType="PushButton" CancelText="Cancel" EditText="Edit"
UpdateText="Update"></asp:EditCommandColumn>
</Columns>
</asp:DataGrid>

48
VB.NET

Dim sqlStmt As String


Dim conString As String
Dim cn As SqlConnection
Dim cmd As SqlCommand
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
' Put user code to initialize the page here
If Not Page.IsPostBack Then
BindGrid()
End If
End Sub 'Page_Load

Sub BindGrid()
'Bind the Datagrid with dataSet
End Sub 'BindGrid

Protected Sub EditCmd(ByVal sender As Object, ByVal e As DataGridCommandEventArgs)


DataGrid1.EditItemIndex = CInt(e.Item.ItemIndex)
BindGrid()
End Sub 'EditCmd

Public Sub CancelCmd(ByVal sender As Object, ByVal e As DataGridCommandEventArgs)


DataGrid1.EditItemIndex = -1
BindGrid()
End Sub 'CancelCmd

Protected Sub UpdateCmd(ByVal sender As Object, ByVal e As DataGridCommandEventArgs)


If Page.IsValid Then
sqlStmt = "UPDATE Employees SET LastName = @LastName, FirstName=@FirstName,Title=@Title where
EmployeeId = @EmployeeId"
conString = "server=localhost;database=Northwind;uid=sa;pwd=;"
cn = New SqlConnection(conString)
cmd = New SqlCommand(sqlStmt, cn)
Dim LastName, FirstName, Title As String
LastName = CType(e.Item.FindControl("txtLastName"), TextBox).Text
FirstName = CType(e.Item.FindControl("txtFirstName"), TextBox).Text
Title = CType(e.Item.FindControl("txtTitle"), TextBox).Text
Dim EmployeeId As Integer = CInt(DataGrid1.DataKeys(CInt(e.Item.ItemIndex)))

cmd.Parameters.Add(New SqlParameter("@LastName", LastName))


cmd.Parameters.Add(New SqlParameter("@FirstName", FirstName))
cmd.Parameters.Add(New SqlParameter("@Title", Title))
cmd.Parameters.Add(New SqlParameter("@EmployeeId", EmployeeId))
Try
cn.Open()
cmd.ExecuteNonQuery()
DataGrid1.EditItemIndex = -1
Catch ex As Exception
Response.Write(ex.Message.ToString())
End Try
BindGrid()
End If
End Sub 'UpdateCmd

C#

private void Page_Load(object sender, System.EventArgs e)

49
{
// Put user code to initialize the page here
if (!Page.IsPostBack )
{
BindGrid();
}
}

void BindGrid()
{
//Bind the DataGrid with dataset
}

protected void EditCmd(object sender, DataGridCommandEventArgs e)


{
DataGrid1.EditItemIndex = (int)e.Item.ItemIndex;
BindGrid();
}

public void CancelCmd(object sender, DataGridCommandEventArgs e)


{
DataGrid1.EditItemIndex = -1;
BindGrid();
}

string sqlStmt;
string conString;
SqlConnection cn;
SqlCommand cmd;
protected void UpdateCmd(object sender, DataGridCommandEventArgs e)
{
if (Page.IsValid)
{
sqlStmt = "UPDATE Employees SET LastName = @LastName, FirstName=@FirstName,Title=@Title where
EmployeeId = @EmployeeId";
conString = "server=localhost;database=Northwind;uid=sa;pwd=;";
cn = new SqlConnection(conString);
cmd = new SqlCommand(sqlStmt, cn);
string LastName , FirstName , Title;
LastName = ((TextBox )e.Item.FindControl ("txtLastName")).Text ;
FirstName = ((TextBox )e.Item.FindControl ("txtFirstName")).Text ;
Title = ((TextBox )e.Item.FindControl ("txtTitle")).Text ;
int EmployeeId =(int) DataGrid1.DataKeys[(int)e.Item.ItemIndex];

cmd.Parameters.Add(new SqlParameter("@LastName", LastName));


cmd.Parameters.Add(new SqlParameter("@FirstName",FirstName ));
cmd.Parameters.Add(new SqlParameter("@Title", Title ));
cmd.Parameters.Add(new SqlParameter("@EmployeeId",EmployeeId ));
try
{
cn.Open();
cmd.ExecuteNonQuery();
DataGrid1.EditItemIndex = -1;
}
catch(Exception ex)
{
Response.Write (ex.Message.ToString () );
}
BindGrid();
}
}

50
25.28 How do I use Validator controls while editing data in the DataGrid?

Yes, you can use the Asp.Net validation controls inside a Datagrid. You'll need to use a TemplateColumn, and on the

TextBoxes (or other controls) in your EditItemTemplate, be sure to give them an ID. Then specify that ID as the

ControlToValidate for the validation control.

Refer How to edit data in DataGrid using TemplateColumn?

25.29 How to highlight the Column that is sorted in a DataGrid?

<asp:DataGrid id="DataGrid1" OnItemDataBound ="ItemDB" AllowSorting="True" OnSortCommand="SortData"


runat="server"></asp:DataGrid>

VB.NET

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load


'Put user code to initialize the page here
If Not Page.IsPostBack Then
BindDataGrid("ProductId")
End If
End Sub

Protected Sub SortData(ByVal source As Object, ByVal e As


System.Web.UI.WebControls.DataGridSortCommandEventArgs)
BindDataGrid(e.SortExpression.ToString())
End Sub

Sub BindDataGrid(ByVal sortfield As String)


ViewState("SortExpression") = sortfield
'Fill the DataSet
Dim dv As DataView = ds.Tables(0).DefaultView
dv.Sort = sortfield
DataGrid1.DataSource = dv
DataGrid1.DataBind()
End Sub

Protected Sub ItemDB(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs)


Dim dv As DataView = DataGrid1.DataSource
Dim dc As DataColumnCollection = dv.Table.Columns
If e.Item.ItemType = ListItemType.Header Then
If ViewState("SortExpression") <> "" Then
e.Item.Cells(dc.IndexOf(dc(ViewState("SortExpression")))).BackColor = Color.BlueViolet
e.Item.Cells(dc.IndexOf(dc(ViewState("SortExpression")))).ForeColor = Color.AntiqueWhite
End If
End If
End Sub

C#

private void Page_Load(object sender, System.EventArgs e)


{
// Put user code to initialize the page here

51
if(! Page.IsPostBack )
{
BindDataGrid("ProductId");
}
}

protected void SortData(Object source, System.Web.UI.WebControls.DataGridSortCommandEventArgs e )


{
BindDataGrid(e.SortExpression.ToString());
}

void BindDataGrid(string sortfield)


{
ViewState["SortExpression"] = sortfield;
//Fill the dataset
DataView dv = ds.Tables[0].DefaultView;
dv.Sort = sortfield;
DataGrid1.DataSource = dv;
DataGrid1.DataBind();
}

protected void ItemDB(object sender ,System.Web.UI.WebControls.DataGridItemEventArgs e )


{
DataView dv =(DataView) DataGrid1.DataSource;
DataColumnCollection dc = dv.Table.Columns;
if (e.Item.ItemType == ListItemType.Header )
{
if (ViewState["SortExpression"].ToString()!= "")
{
e.Item.Cells[dc.IndexOf( dc[ViewState["SortExpression"].ToString ()])].BackColor = Color.BlueViolet;
e.Item.Cells[dc.IndexOf(dc[ViewState["SortExpression"].ToString ()])].ForeColor = Color.AntiqueWhite;
}
}
}

25.30 How to create a Drilldown DataGrid?

Refer ASP.NET Reports Starter Kit DrillDown Overview

25.31 How to set a Datagrid Column to invisible when that Column is an


AutoGeneratedColumn?

In the DataGrid's declaration, add the following code in OnItemDataBound event

VB.NET

Dim dv As DataView = DataGrid1.DataSource 'Bind you DataGrid1 in Page_Load to DataView


Dim dc As DataColumnCollection = dv.Table.Columns
e.Item.Cells(dc.IndexOf(dc("field_name))).Visible = false

C#

DataView dv = DataGrid1.DataSource ;//Bind you DataGrid1 in Page_Load to DataView


DataColumnCollection dc = dv.Table.Columns;

52
e.Item.Cells[dc.IndexOf(dc["field_name"])].Visible = false;

25.32 How to use the DataFormatString to format DataGrid data dynamically?

In the ItemDataBound Event of DataGrid write following code.

VB.NET

Dim ds As DataSet = CType(DataGrid1.DataSource, DataSet)


Dim dv As DataView = ds.Tables(0).DefaultView
Dim dcCol As DataColumnCollection = dv.Table.Columns
If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then
e.Item.Cells(dcCol.IndexOf(dcCol("UnitPrice"))).Text = DataBinder.Eval(e.Item.DataItem, "UnitPrice", "{0:c}")
End If

C#

DataSet ds = (DataSet)DataGrid1.DataSource ;
DataView dv = ds.Tables[0].DefaultView ;
DataColumnCollection dcCol = dv.Table.Columns ;
if ((e.Item.ItemType == ListItemType.Item )||( e.Item.ItemType == ListItemType.AlternatingItem ))
{
e.Item.Cells[dcCol.IndexOf (dcCol ["UnitPrice"])].Text = DataBinder.Eval(e.Item.DataItem, "UnitPrice", "{0:c}");
}

25.33 How to set the maxlength of a textbox (in the EditTemplate of


DataGrid) based on a field value in the record?

<EditItemTemplate>
<asp:TextBox runat="server" id="txtField" MaxLength='<%# DataBinder.Eval(Container.DataItem, "FieldSize") %>'
/>
</EditItemTemplate>

25.34 How to add an attribute to the Table generated by the DataGrid?

VB.NET

'Bind DataGrid
DataGrid1.Attributes.Add ("Description", "This table displays Product Description" )

53
C#

//Bind DataGrid
DataGrid1.Attributes.Add ("Description", "This table displays Product Description" );

Note : By doing a ViewSource you can find the Attribute Description for the Table that displays the DataGrid data

25.35 Why do I get the error message " CS1502: The best overloaded method
match for 'xxx(string)' has some invalid arguments " when I use Helper
function in DataGrid?

The function xxx() is expecting a string, but DataBinder.Eval() returns an object. So you must cast the result of

DataBinder.Eval() to a string (or, in this case, just use .ToString()).

i.e, in your template do:

<%#xxx(DataBinder.Eval(Container.DataItem, "field_name").ToString()) %>

VB.NET

<%#xxx(DataBinder.Eval (CStr(DataBinder.Eval(Container.DataItem, "field_name")) )%>

C#

<%# xxx((string) DataBinder.Eval(Container.DataItem, "field_name"))%>

Either of these should work.

25.36 How to confirm delete in DataGrid using LinkButton?

<script>
function confirmmsg()
{
if (confirm("Do you want to delete record?")==true)
return true;
else
return false;
}
</script>

<asp:DataGrid id="DataGrid1" AutoGenerateColumns="False" DataKeyField="Employeeid"


OnItemCommand="ItemCmd" OnItemDataBound="ItemDB" runat="server">
<Columns>

54
<asp:BoundColumn DataField="firstname" HeaderText="First Name"></asp:BoundColumn>
<asp:TemplateColumn>
<ItemTemplate>
<asp:LinkButton id="btnDelete" runat="server" Text="Delete" CommandName="Delete"
CausesValidation="false"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>

VB.NET

Dim sqlStmt As String


Dim conString As String
Dim cn As SqlConnection = Nothing
Dim da As SqlDataAdapter = Nothing
Dim ds As DataSet

Private Sub Page_Load(sender As Object, e As System.EventArgs)


conString = "server=localhost;database=Northwind;uid=sa;pwd=;"
cn = New SqlConnection(conString)
If Not Page.IsPostBack Then
BindData()
End If
End Sub 'Page_Load

Sub BindData()
sqlStmt = "select * from emp "
ds = New DataSet()
da = New SqlDataAdapter(sqlStmt, cn)
da.Fill(ds, "t1")
DataGrid1.DataSource = ds
DataGrid1.DataBind()
End Sub 'BindData

Protected Sub ItemDB(sender As Object, e As System.Web.UI.WebControls.DataGridItemEventArgs)


Select Case e.Item.ItemType
Case ListItemType.Item, ListItemType.AlternatingItem
Dim btn As LinkButton = CType(e.Item.FindControl("btnDelete"), LinkButton)
btn.Attributes.Add("onclick", "return confirmmsg();")
Exit
End Select
End Sub 'ItemDB

Protected Sub ItemCmd(sender As Object, e As System.Web.UI.WebControls.DataGridCommandEventArgs)


If e.CommandName = "Delete" Then
Me.DeleteRow(Me.DataGrid1.DataKeys(e.Item.ItemIndex).ToString())
End If
BindData()
End Sub 'ItemCmd

Private Sub DeleteRow(empid As String)


Dim cmd As New SqlCommand("DELETE FROM Emp WHERE employeeid =" + empid, cn)
cn.Open()
cmd.ExecuteNonQuery()
cn.Close()
End Sub 'DeleteRow

C#

55
string sqlStmt ;
string conString ;
SqlConnection cn =null;
SqlDataAdapter da =null;
DataSet ds;
private void Page_Load(object sender, System.EventArgs e)
{
conString = "server=localhost;database=Northwind;uid=sa;pwd=;";
cn = new SqlConnection(conString);
if (!Page.IsPostBack )
{
BindData();
}
}
void BindData()
{
sqlStmt = "select * from emp ";
ds= new DataSet ();
da = new SqlDataAdapter (sqlStmt, cn);
da.Fill (ds,"t1");
DataGrid1.DataSource =ds;
DataGrid1.DataBind ();
}

protected void ItemDB(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)


{
switch(e.Item.ItemType)
{
case ListItemType.Item:
case ListItemType.AlternatingItem:
{
LinkButton btn = (LinkButton)e.Item.FindControl("btnDelete");
btn.Attributes.Add("onclick", "return confirmmsg();");
break;
}
}
}

protected void ItemCmd(object sender, System.Web.UI.WebControls.DataGridCommandEventArgs e)


{
if(e.CommandName == "Delete")
{
this.DeleteRow(this.DataGrid1.DataKeys[e.Item.ItemIndex].ToString());
}
BindData();
}

private void DeleteRow(string empid)


{
SqlCommand cmd = new SqlCommand("DELETE FROM Emp WHERE employeeid ="+ empid ,cn);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}

25.37 How to hide and show a Column based on the authenticated user?

In the DataGrid_ItemDataBound Event write the following code

56
VB.NET

If Not User.Identity.IsAuthenticated Then


e.Item.Cells(1).Visible = False
End If

C#

if ( ! User.Identity.IsAuthenticated )
{
e.Item.Cells[1].Visible =false;
}

25.38 How to use a dropdownlist in a DataGrid?

Step 1: Display the Data in the Datagrid Initially the Datagrid is populated with the records in the db The field

Discontinued is of data type bit in the db i.e 0/1.

To display it as yes/no in the Datagrid a helper function ShowVal(...) is called

Step 2: To Edit the Datagrid ,

When the edit button is clicked it should display field Discontinued as Yes/No

• To update the record the user should get a choice to Select Yes/No using dropdownlist

• By default the dropdownlist should be set to the value in the database

o So the DataSource property of the dropdownlist is set to BindTheDiscontinued()

o and OnPreRender property does the task of setting the value from the db to the dropdownlist

<asp:DataGrid id="DataGrid1" AutoGenerateColumns="False" DataKeyField="ProductID"


OnUpdateCommand="DataGrid1_Update"
OnEditCommand="DataGrid1_Edit" OnCancelCommand="DataGrid1_Cancel" runat="server">
<Columns>
<asp:TemplateColumn HeaderText="Discontinued">
<ItemTemplate>
<asp:Label ID="lblDiscontinued" Text='<%#ShowVal(Convert.ToBoolean( DataBinder.Eval(Container.DataItem,
"Discontinued").ToString()) )%>' Runat="server" />
</ItemTemplate>

<EditItemTemplate>
<asp:Label runat="server" id="lblProductID" Visible="False" Text='<%# DataBinder.Eval(Container.DataItem,
"ProductId") %>'/>
<asp:Label ID="lblEditDiscontinued"
Text='<%#ShowVal(Convert.ToBoolean(DataBinder.Eval(Container.DataItem, "Discontinued").ToString() ))%>'
Runat="server" />
<asp:DropDownList id="ddlDiscontinued" DataSource="<%# BindTheDiscontinued() %>"

57
OnPreRender="SetDropDownIndex" DataTextField="Discontinued" DataValueField="Discontinued" runat="server" />
</EditItemTemplate>
</asp:TemplateColumn>

<asp:EditCommandColumn EditText="Edit" CancelText="Cancel" UpdateText="Update" ItemStyle-Width="100px"


HeaderText="Commands" />
</Columns>
</asp:DataGrid>

Code Behind VB.NET

Dim strDiscontinued As String


Dim obj As GetData
Dim strSql As String
Dim strConn As String
Dim ds As DataSet
Dim dr As SqlDataReader

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load


' Put user code to initialize the page here
strConn = "server=localhost;uid=sa;pwd=;database=northwind"
If Not Page.IsPostBack Then
BindGrid()
End If
End Sub 'Page_Load

'To Bind the DataGrid


Sub BindGrid()
obj = New GetData
strSql = "Select productid, discontinued from Products"
ds = obj.GetDataFromTable(strSql, strConn)
DataGrid1.DataSource = ds
DataGrid1.DataBind()
End Sub 'BindGrid

'To display Yes/No for True/False


Protected Function ShowVal(ByVal blnval As Boolean) As String
If blnval = True Then
Return "Yes"
Else
Return "No"
End If
End Function 'ShowVal

'Bind the Data to the dropdownlist in the EditTemplate


Protected Function BindTheDiscontinued() As SqlDataReader
obj = New GetData
strSql = "SELECT distinct 'Discontinued' ="
strSql += " CASE "
strSql += " WHEN Discontinued = 1 Then 'Yes'"
strSql += " ELSE 'No'"
strSql += " END "
strSql += " From Products "
dr = obj.GetSingleDataUsingReader(strSql, strConn)
Return dr
End Function 'BindTheDiscontinued

'Set the Text of the Dropdownlist to the field value in Database


Protected Sub SetDropDownIndex(ByVal sender As [Object], ByVal e As System.EventArgs)
Dim ed As DropDownList
ed = CType(sender, DropDownList)
ed.SelectedIndex = ed.Items.IndexOf(ed.Items.FindByText(strDiscontinued))

58
End Sub 'SetDropDownIndex

'For Edit Update Cancel


Public Sub DataGrid1_Edit(ByVal sender As [Object], ByVal e As DataGridCommandEventArgs)
strDiscontinued = CType(e.Item.FindControl("lblDiscontinued"), Label).Text
DataGrid1.EditItemIndex = CInt(e.Item.ItemIndex)
BindGrid()
End Sub 'DataGrid1_Edit

Public Sub DataGrid1_Update(ByVal sender As [Object], ByVal e As DataGridCommandEventArgs)


Dim TempList As DropDownList
Dim TempValue As [String]
TempList = CType(e.Item.FindControl("ddlDiscontinued"), DropDownList)
TempValue = TempList.SelectedItem.Value
'Place update code here
Response.Write(TempValue)
DataGrid1.EditItemIndex = -1
BindGrid()
End Sub 'DataGrid1_Update

Public Sub DataGrid1_Cancel(ByVal sender As [Object], ByVal e As DataGridCommandEventArgs)


DataGrid1.EditItemIndex = -1
BindGrid()
End Sub 'DataGrid1_Cancel

'Functions used in Class GetData.cs


Dim mycn As SqlConnection
Dim myda As SqlDataAdapter
Dim mycmd As SqlCommand
Dim ds As DataSet
Dim strConn As String
Dim myReader As SqlDataReader

Public Function GetDataFromTable(ByVal strSQL As String, ByVal strConnString As String) As DataSet


Try
strConn = strConnString
mycn = New SqlConnection(strConn)
myda = New SqlDataAdapter(strSQL, mycn)
ds = New DataSet
myda.Fill(ds, "Table")
Return ds
Catch ex As Exception
Throw New Exception(ex.Message.ToString())
Finally
mycn.Close()
End Try
End Function 'GetDataFromTable

Public Function GetSingleDataUsingReader(ByVal strSQL As String, ByVal strConnString As String) As SqlDataReader


Try
strConn = strConnString
mycn = New SqlConnection(strConn)
mycmd = New SqlCommand(strSQL, mycn)
mycn.Open()
myReader = mycmd.ExecuteReader(CommandBehavior.CloseConnection)
Return myReader
Catch ex As Exception
Throw New Exception(ex.Message.ToString())
Finally
End Try 'mycn.Close ();
End Function 'GetSingleDataUsingReader

C#

59
string strDiscontinued;
GetData obj;
string strSql;
string strConn;
DataSet ds;
SqlDataReader dr;
private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
strConn ="server=localhost;uid=sa;pwd=;database=northwind";
if (!Page.IsPostBack )
{
BindGrid();
}
}

//To Bind the DataGrid


void BindGrid()
{
obj=new GetData ();
strSql = "Select productid, discontinued from Products";
ds=obj.GetDataFromTable (strSql ,strConn);
DataGrid1.DataSource =ds;
DataGrid1.DataBind ();
}

//To display Yes/No for True/False


protected string ShowVal(bool blnval)
{
if (blnval==true)
{
return "Yes";
}
else
{
return "No";
}
}

//Bind the Data to the dropdownlist in the EditTemplate


protected SqlDataReader BindTheDiscontinued()
{
obj=new GetData ();
strSql ="SELECT distinct 'Discontinued' =" ;
strSql+=" CASE ";
strSql+=" WHEN Discontinued = 1 Then 'Yes'" ;
strSql+=" ELSE 'No'" ;
strSql+=" END " ;
strSql+=" From Products ";
dr=obj.GetSingleDataUsingReader (strSql ,strConn);
return dr;
}

//Set the Text of the Dropdownlist to the field value in Database

protected void SetDropDownIndex(Object sender ,System.EventArgs e )


{
DropDownList ed ;
ed = (DropDownList) sender;

60
ed.SelectedIndex = ed.Items.IndexOf(ed.Items.FindByText(strDiscontinued));
}

//For Edit Update Cancel


public void DataGrid1_Edit(Object sender, DataGridCommandEventArgs e)
{
strDiscontinued = ((Label )e.Item.FindControl("lblDiscontinued")).Text;
DataGrid1.EditItemIndex = (int)e.Item.ItemIndex;
BindGrid();
}

public void DataGrid1_Update(Object sender, DataGridCommandEventArgs e)


{
DropDownList TempList ;
String TempValue ;
TempList = (DropDownList) e.Item.FindControl("ddlDiscontinued");
TempValue = TempList.SelectedItem.Value;
//Place update code here
Response.Write (TempValue);
DataGrid1.EditItemIndex = -1;
BindGrid();
}
public void DataGrid1_Cancel(Object sender, DataGridCommandEventArgs e)
{
DataGrid1.EditItemIndex = -1;
BindGrid();
}

//Functions used in Class GetData.cs

SqlConnection mycn;
SqlDataAdapter myda;
SqlCommand mycmd;
DataSet ds;
String strConn;
SqlDataReader myReader;
public DataSet GetDataFromTable(string strSQL ,string strConnString)
{
try
{
strConn=strConnString;
mycn = new SqlConnection(strConn);
myda = new SqlDataAdapter (strSQL, mycn);
ds= new DataSet ();
myda.Fill (ds,"Table");
return ds;
}
catch(Exception ex)
{
throw new Exception (ex.Message.ToString ());
}
finally
{
mycn.Close ();
}
}

public SqlDataReader GetSingleDataUsingReader(string strSQL ,string strConnString)


{
try
{
strConn=strConnString;
mycn = new SqlConnection(strConn);

61
mycmd = new SqlCommand (strSQL, mycn);
mycn.Open ();
myReader=mycmd.ExecuteReader(CommandBehavior.CloseConnection );
return myReader;
}
catch(Exception ex)
{
throw new Exception (ex.Message.ToString ());
}
finally
{
//mycn.Close ();
}
}

25.39 How to set a different color for every alternate row of a datagrid?

Use the Tag <AlternatingItemStyle>

25.40 How to add a counter column to a DataGrid?

<asp:Datagrid id="Datagrid1" runat="server">


<Columns>
<asp:TemplateColumn>
<ItemTemplate>
<asp:Label id="Label1" Runat ="server" > <%#getCount%> </asp:Label>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:Datagrid>

Code behind

VB.NET

Dim count As Integer


protected function getCount() As Integer
count = count + 1
Return count
End Function

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load


'Populate the Datagrid populating data from the database
'.....
End Sub

C#

int count =0;


protected int getCount()

62
{
count = count + 1;
return count;
}

private void Page_Load(object sender, System.EventArgs e)


{
//Populate the Datagrid populating data from the database
//....
}

25.41 How to change the HeaderText of the Datagrid?

Method 1 : Set the HeaderText Property of the BoundColumn/TemplateColumn

<asp:DataGrid id="DataGrid1" AutoGenerateColumns="False" runat="server">


<Columns>
<asp:BoundColumn DataField="EmployeeID" HeaderText="Employee ID">
</asp:BoundColumn>
<asp:BoundColumn DataField="FirstName" HeaderText="First Name">
</asp:BoundColumn>
<asp:TemplateColumn HeaderText="LastName">
<ItemTemplate>
<#%DataBinder.Eval(Container.DataItem, "LastName").ToString()%>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>

Method 2 : Dynamically change the HeaderText in the ItemDataBound Event of the DataGrid

<asp:DataGrid id="DataGrid1" OnItemDataBound="ItemDB" runat="server"></asp:DataGrid>

VB.NET

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load


'Populate the DataGrid
End Sub

protected Sub ItemDB(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs)


If e.Item.ItemType = ListItemType.Header Then
e.Item.Cells(0).Text = "Employee ID"
e.Item.Cells(1).Text = "First Name"
e.Item.Cells(2).Text = "Last Name"
End If
End Sub

C#

63
private void Page_Load(object sender, System.EventArgs e)
{
//Populate the DataGrid
}

protected void ItemDB(Object sender ,System.Web.UI.WebControls.DataGridItemEventArgs e )


{
if (e.Item.ItemType == ListItemType.Header)
{
e.Item.Cells[0].Text = "Employee ID";
e.Item.Cells[1].Text = "First Name";
e.Item.Cells[2].Text = "Last Name";
}
}

25.42 How to select a record in the datagrid and start editing/updating the
record using textboxes?

<asp:DataGrid id="DataGrid1" OnItemCommand="ItemCommand"


style="Z-INDEX: 101; LEFT: 15px; POSITION: absolute; TOP: 23px"
runat="server" >
<Columns>
<asp:ButtonColumn Text="Edit" ButtonType="PushButton" CommandName="Edit">
</asp:ButtonColumn>
</Columns>
</asp:DataGrid>
<asp:TextBox id="txtRegionID" style="Z-INDEX: 102; LEFT: 352px; POSITION: absolute; TOP: 24px"
runat="server"></asp:TextBox>
<asp:TextBox id="txtRegionDescription" style="Z-INDEX: 103; LEFT: 352px; POSITION: absolute; TOP: 64px"
runat="server"></asp:TextBox>
<asp:Button id="btnUpdate" style="Z-INDEX: 104; LEFT: 304px; POSITION: absolute; TOP: 128px"
runat="server" Text="Update"></asp:Button>
<asp:Label id="lblMessage" style="Z-INDEX: 105; LEFT: 296px; POSITION: absolute; TOP: 176px"
runat="server"></asp:Label>

VB.NET

Dim cn As SqlConnection
Dim da As SqlDataAdapter
Dim cmd As SqlCommand
Dim strsql As String
Dim ds As DataSet

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load


'Put user code to initialize the page here
cn = New SqlConnection("Server=localhost;uid=sa;pwd=;database=northwind;")
If Not Page.IsPostBack Then
BindData()
End If
End Sub

Sub BindData()
DataGrid1.DataSource = GetData("Select * from Region")
DataGrid1.DataBind()

64
End Sub

Function GetData(ByVal strSql As String) As DataSet


da = New SqlDataAdapter(strSql, cn)
ds = New DataSet()
da.Fill(ds)
Return ds
End Function

Protected Sub ItemCommand(ByVal source As Object, _


ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs)
If e.CommandName = "Edit" Then
'Fill the Textboxes with relevant data
FillTheData(e.Item.Cells(1).Text, e.Item.Cells(2).Text)
End If
End Sub

Sub FillTheData(ByVal RegionID As String, ByVal RegionDescription As String)


txtRegionID.Text = RegionID
txtRegionDescription.Text = RegionDescription
End Sub

Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles


btnUpdate.Click
Try
strsql = "Update Region set RegionDescription=@RegionDescription where RegionId=@RegionId"
cmd = New SqlCommand(strsql, cn)
cmd.Parameters.Add(New SqlParameter("@RegionId", SqlDbType.Int))
cmd.Parameters.Add(New SqlParameter("@RegionDescription", SqlDbType.NVarChar, 40))
cmd.Parameters("@RegionId").Value = Convert.ToInt32(txtRegionID.Text)
cmd.Parameters("@RegionDescription").Value = txtRegionDescription.Text
cn.Open()
cmd.ExecuteNonQuery()
BindData()
lblMessage.Text = "Updated Successfully"
Catch ex As Exception
lblMessage.Text = ex.Message
lblMessage.ForeColor = Color.Red
Finally
cn.Close()
End Try
End Sub

C#

SqlConnection cn;
SqlDataAdapter da ;
SqlCommand cmd ;
string strsql ;
DataSet ds ;
private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
cn = new SqlConnection("Server=localhost;uid=sa;pwd=;database=northwind;");
if(!Page.IsPostBack)
{
//Code to Bind the data to the Datagrid
BindData();
}
}

65
void BindData()
{
DataGrid1.DataSource = GetData("Select * from Region");
DataGrid1.DataBind();
}
DataSet GetData(string strSql)
{
da = new SqlDataAdapter(strSql, cn);
ds = new DataSet();
da.Fill(ds);
return ds;
}

protected void ItemCommand(Object source,System.Web.UI.WebControls.DataGridCommandEventArgs e)


{
if (e.CommandName == "Edit")
{
//'Fill the Textboxes with relevant data
FillTheData(e.Item.Cells[1].Text, e.Item.Cells[2].Text);
lblMessage.Text="";
}
}

void FillTheData(string RegionID,string RegionDescription)


{
txtRegionID.Text = RegionID;
txtRegionDescription.Text = RegionDescription;
}

private void btnUpdate_Click(object sender, System.EventArgs e)


{
try
{
strsql = "Update Region set RegionDescription=@RegionDescription where RegionId=@RegionId";
cmd = new SqlCommand(strsql, cn);
cmd.Parameters.Add(new SqlParameter("@RegionId", SqlDbType.Int));
cmd.Parameters.Add(new SqlParameter("@RegionDescription", SqlDbType.NVarChar, 40));
cmd.Parameters["@RegionId"].Value = Convert.ToInt32(txtRegionID.Text);
cmd.Parameters["@RegionDescription"].Value = txtRegionDescription.Text;
cn.Open();
cmd.ExecuteNonQuery();
BindData();
lblMessage.Text = "Updated Successfully";
}
catch (Exception ex)
{
lblMessage.Text = ex.Message;
lblMessage.ForeColor = Color.Red;
}
finally
{
cn.Close();
}
}

25.43 How can I show what page the user is on using in-built paging
functionality. CurrentPageIndex Property Shows Up as 0?

In PageIndexChanged event write

66
VB.NET

Dim pageindex As Integer = DataGrid1.CurrentPageIndex + 1


LblPageInfo.Text = "Page " + pageindex.ToString() + " of " + DataGrid1.PageCount.ToString()

C#

int pageindex = DataGrid1.CurrentPageIndex + 1 ;


LblPageInfo.Text = "Page " + pageindex.ToString() + " of " + DataGrid1.PageCount.ToString() ;

25.44 How to display "No data" when a field value is null?

<asp:DataGrid id="DataGrid1" OnItemDataBound=ItemDB runat="server"></asp:DataGrid>

VB.NET

Private Sub Page_Load(sender As Object, e As System.EventArgs)


' Put user code to initialize the page here
If Not Page.IsPostBack Then
'Populate the DataGrid
End If
End Sub 'Page_Load

Protected Sub ItemDB(ByVal s As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs)


If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then
If e.Item.Cells(1).Text = " " Then
e.Item.Cells(1).Text = "No data"
End If
End If
End Sub 'ItemDB

C#

private void Page_Load(object sender, System.EventArgs e)


{
// Put user code to initialize the page here
if(!Page.IsPostBack )
{
//Populate the DataGrid
}
}

protected void ItemDB (Object s , System.Web.UI.WebControls.DataGridItemEventArgs e )


{
if ((e.Item.ItemType ==ListItemType.Item) ||(e.Item.ItemType ==ListItemType.AlternatingItem))
{

67
if( e.Item.Cells[1].Text == " ")
{
e.Item.Cells[1].Text = "No data";
}
}
}

In Cells[x]/Cells(x) x=> index number

25.45 How to change the value of a field before it gets displayed in the
datagrid?

<asp:DataGrid id="DataGrid1" OnItemDataBound="ItemDB" runat="server"></asp:DataGrid>

VB.NET

Protected Sub ItemDB(ByVal s As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs)


If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then
Select Case Trim(e.Item.Cells(3).Text)
Case "Sales Representative"
e.Item.Cells(3).Text = "SR"
Case "Vice President, Sales"
e.Item.Cells(3).Text = "VP"
Case "Sales Manager"
e.Item.Cells(3).Text = "SM"
Case "Inside Sales Coordinator"
e.Item.Cells(3).Text = "ISC"
Case Else
e.Item.Cells(3).Text = e.Item.Cells(3).Text
End Select
end if
end sub

C#

protected void ItemDB (Object s , System.Web.UI.WebControls.DataGridItemEventArgs e )


{
if ((e.Item.ItemType ==ListItemType.Item) ||(e.Item.ItemType ==ListItemType.AlternatingItem))
{
switch ( e.Item.Cells[3].Text.Trim() )
{
case "Sales Representative":
e.Item.Cells[3].Text = "SR";
break;
case "Vice President, Sales":
e.Item.Cells[3].Text = "VP";
break;
case "Sales Manager":
e.Item.Cells[3].Text = "SM";
break;
case "Inside Sales Coordinator":
e.Item.Cells[3].Text = "ISC";

68
break;
default :
e.Item.Cells[3].Text = e.Item.Cells[3].Text;
break;
}
}
}

25.46 How to use a ButtonColumn in a DataGrid?

<asp:DataGrid id="DataGrid1" OnItemCommand ="ItemCmd" AutoGenerateColumns =False runat="server">


<Columns>
<asp:BoundColumn DataField="ProductID" HeaderText="ProductID"></asp:BoundColumn>
<asp:BoundColumn DataField="Productname" HeaderText="Productname"></asp:BoundColumn>
<asp:ButtonColumn DataTextField="Productid" CommandName="Show" HeaderText="Productid"
ButtonType="PushButton"
Text="Click"></asp:ButtonColumn>
</Columns>
</asp:DataGrid>

VB.NET

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load


'Put user code to initialize the page here
If Not Page.IsPostBack Then
'Populate the DataGrid
End If
End Sub

Protected Sub ItemCmd(ByVal source As Object, ByVal e As


System.Web.UI.WebControls.DataGridCommandEventArgs)
If e.CommandName = "Show" Then
Response.Write(e.Item.Cells(1).Text)
End If
End Sub

C#

private void Page_Load(object sender, System.EventArgs e)


{
// Put user code to initialize the page here
if (!Page.IsPostBack )
{
//Populate the DataGrid
}
}

protected void ItemCmd(Object source , System.Web.UI.WebControls.DataGridCommandEventArgs e )


{
if (e.CommandName.ToString () == "Show")
{
Response.Write(e.Item.Cells[1].Text);
}

69
}

25.47 How to display a Master Detail data using DataGrid?

<asp:datagrid id="DataGrid1" ShowHeader =false AutoGenerateColumns =true runat="server"


DataKeyField="OrderId" OnItemDataBound="ItemDB">
<Columns>
<asp:TemplateColumn >
<ItemTemplate>
<b><%#DataBinder.Eval(Container.DataItem,"OrderId")%></b>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:datagrid>

VB.NET

Dim cn As SqlConnection
Dim da As SqlDataAdapter
Dim ds As DataSet

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load


' Put user code to initialize the page here
cn = New SqlConnection("Server=localhost;uid=sa;pwd=;database=northwind")
If Not Page.IsPostBack Then
da = New SqlDataAdapter("SELECT orderid FROM orders", cn)
ds = New DataSet
da.Fill(ds, "Orders")
DataGrid1.DataSource = ds
DataGrid1.DataBind()
End If
End Sub 'Page_Load

Protected Sub ItemDB(ByVal sender As Object, ByVal e As DataGridItemEventArgs)


If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then
Dim dgDetails As New DataGrid
Dim orderid As Integer = CInt(CType(e.Item.DataItem, DataRowView)("OrderID"))
dgDetails.DataSource = GetOrderDetails(orderid)
dgDetails.DataBind()
e.Item.Cells(1).Controls.Add(dgDetails)
End If
End Sub 'ItemDB

Function GetOrderDetails(ByVal id As Integer) As DataSet


da = New SqlDataAdapter("SELECT * FROM [Order Details] where orderid=" + id.ToString, cn)
ds = New DataSet
da.Fill(ds, "OrderDetails")
Return ds
End Function 'GetOrderDetails

C#

70
SqlConnection cn;
SqlDataAdapter da;
DataSet ds;
private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
cn= new SqlConnection ("Server=localhost;uid=sa;pwd=;database=northwind");
if (!Page.IsPostBack)
{
da= new SqlDataAdapter ("SELECT orderid FROM orders ", cn);
ds= new DataSet ();
da.Fill (ds, "Orders");
DataGrid1.DataSource = ds;
DataGrid1.DataBind ();
}
}

protected void ItemDB(Object sender,DataGridItemEventArgs e )


{
if ((e.Item.ItemType == ListItemType.Item)||(e.Item.ItemType == ListItemType.AlternatingItem ))
{
DataGrid dgDetails = new DataGrid();
int orderid =(int) ((DataRowView)e.Item.DataItem)["OrderID"] ;
dgDetails.DataSource = GetOrderDetails(orderid );
dgDetails.DataBind();
e.Item.Cells[1].Controls.Add(dgDetails);
}
}

DataSet GetOrderDetails(int id )
{
da= new SqlDataAdapter ("SELECT * FROM [Order Details] where orderid= " + id, cn);
ds= new DataSet ();
da.Fill (ds, "OrderDetails");
return ds;
}

25.48 I have set the ItemStyle and the AlternatingItemStyle tags for
DataGrid control but they aren't working correctly , why?

DataGrid generates an HTML Table, with TableRows and Cells. If you already have some display properties set for

<td>,<TR>... make sure to check them in the Stylesheet. Whatever properties you set there will normally override

whatever you add into your DataGrid's Item styles.

25.49 How to display the checkbox checked or unchecked for a bit data type
value in the DataBase?

<asp:DataGrid id="DataGrid1" runat="server">


<Columns>
<asp:TemplateColumn HeaderText="Discontinued">
<ItemTemplate>
<asp:CheckBox id="chk1" Runat =server
checked=<%#DataBinder.Eval(Container.DataItem,"Discontinued")%>></asp:CheckBox>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>

71
</asp:DataGrid>

25.50 How to do alphabetical paging in ASP.NET?

• Step 1: Create linkbuttons to display the alphabets at the footer of the datagrid

• Step 2: Add this buttons in the ItemCreated event . Use the CommandName and CommandArgument

properties of the LinkButton to identify them

• Step 3: To handle the Paging , In the ItemCommand Event respond to action based on the CommandName

and CommandArgument of LinkButton that caused event to be raised.

<asp:DataGrid ShowFooter="True" OnItemCreated="ItemCreated" OnItemCommand="ItemCommand"


id="DataGrid1" runat="server"></asp:DataGrid>

VB.NET

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load


' Put user code to initialize the page here
If Not Page.IsPostBack Then
BindGrid("")
End If
End Sub

Sub BindGrid(ByVal stralpha As String)


Dim cn As SqlConnection
Dim da As SqlDataAdapter
Dim ds As DataSet
cn = New SqlConnection("Server=localhost;uid=sa;pwd=;database=pubs")
Dim strsql As String = "Select * from authors "
If stralpha = "" Then
strsql = strsql
Else
strsql = strsql + " where au_lname like'" + stralpha + "%'"
End If
da = New SqlDataAdapter(strsql, cn)
ds = New DataSet
da.Fill(ds, "Product")
If (ds.Tables(0).Rows.Count = 0) Then
Response.Write("No Data Found")
DataGrid1.DataSource = Nothing
DataGrid1.DataBind()
Else
DataGrid1.DataSource = ds
DataGrid1.DataBind()
End If
End Sub

Protected Sub ItemCreated(ByVal sender As Object, ByVal e As


System.Web.UI.WebControls.DataGridItemEventArgs)
If e.Item.ItemType = ListItemType.Footer Then
e.Item.Cells.Clear()

72
Dim tc As TableCell = New TableCell
tc.ColumnSpan = 2
e.Item.Cells.Add(tc)
Dim lc As LiteralControl
Dim lb As LinkButton
Dim i As Integer
For i = 65 To 65 + 25
lc = New LiteralControl
lb = New LinkButton
lc.Text = " "
lb.Text = Chr(i)
lb.CommandName = "alpha"
lb.CommandArgument = Chr(i)
tc.Controls.Add(lb)
tc.Controls.Add(lc)
Next
End If
End Sub

Protected Sub ItemCommand(ByVal source As Object, ByVal e As


System.Web.UI.WebControls.DataGridCommandEventArgs)
If (e.CommandName = "alpha") Then
BindGrid(e.CommandArgument.ToString())
End If
End Sub

C#

private void Page_Load(object sender, System.EventArgs e)


{
// Put user code to initialize the page here
if (!Page.IsPostBack )
{
BindGrid("");
}
}

void BindGrid(string stralpha)


{
SqlConnection cn;
SqlDataAdapter da;
DataSet ds;
cn = new SqlConnection ("Server=localhost;uid=sa;pwd=;database=pubs");
string strsql ="Select * from authors ";
if (stralpha=="")
{
strsql = strsql ;
}
else
{
strsql = strsql + " where au_lname like'" + stralpha + "%'";
}
da= new SqlDataAdapter (strsql,cn);
ds= new DataSet ();
da.Fill (ds, "Product");
if (ds.Tables [0].Rows.Count ==0)
{
Response.Write ("No Data Found");
DataGrid1.DataSource=null;
DataGrid1.DataBind ();
}
else

73
{
DataGrid1.DataSource =ds;
DataGrid1.DataBind ();
}
}

protected void ItemCreated(Object sender , System.Web.UI.WebControls.DataGridItemEventArgs e )


{
if (e.Item.ItemType == ListItemType.Footer)
{
e.Item.Cells.Clear();
TableCell tc = new TableCell();
tc.ColumnSpan = 2;
e.Item.Cells.Add(tc);
LiteralControl lc;
LinkButton lb;
string s="" ;
for (char c='A' ; c<= 'Z' ; )
{
lc = newLiteralControl ();
lb = new LinkButton ();
s = c.ToString() ;
lc.Text =" ";
lb.CommandName ="alpha";
lb.CommandArgument= s;
lb.Text=s;
c =(char)((int)c +1) ;
tc.Controls.Add(lb);
tc.Controls.Add(lc);
}
}
}
protected void ItemCommand(Object source , System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
if (e.CommandName == "alpha" )
{
BindGrid(e.CommandArgument.ToString ());
}
}

25.51 How to enable or disable the button in the DataGrid based on a bit
value in the database?

<asp:DataGrid id="DataGrid1" runat="server">


<Columns>
<asp:TemplateColumn HeaderText ="Product Information" >
<ItemTemplate >
<asp:Button CommandName="Status" Text ="Status" Runat =server
Enabled =<%#CheckStatus(Convert.ToBoolean(DataBinder.Eval(Container.DataItem,"Discontinued")))%>
ID="Button1" >
</asp:Button>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>

VB.NET

74
Protected Function CheckStatus(ByVal prdStatus As Boolean) As Boolean
If prdStatus = False Then
Return True
Else
Return False
End If
End Function

C#

protected bool CheckStatus(bool prdStatus)


{
//If the Discontinued field is "0"
if (prdStatus==false)
{
return true;
}
//If the Discontinued field is "1"
else
{
return false;
}
}

25.52 How to show data vertically in a datagrid for a particular row?

<asp:DataGrid id="DataGrid1" runat="server"></asp:DataGrid>

VB.NET

Dim cn As SqlConnection
Dim da As SqlDataAdapter
Dim ds As DataSet

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load


' Put user code to initialize the page here
cn = New SqlConnection("server=localhost;uid=sa;pwd=;database=northwind")
da = New SqlDataAdapter("Select * from orders where orderid=10248", cn)
ds = New DataSet()
da.Fill(ds, "Orders")
DataGrid1.DataSource = GoDoReShape(ds)
DataGrid1.DataBind()
End Sub 'Page_Load

Public Function GoDoReShape(ByVal ds As DataSet) As DataSet


Dim NewDs As New DataSet()

NewDs.Tables.Add()

75
'Create Two Columns with names "ColumnName" and "Value"
'ColumnName -> Displays all ColumnNames
'Value -> Displays ColumnData
NewDs.Tables(0).Columns.Add("ColumnName")
NewDs.Tables(0).Columns.Add("Value")

Dim dr As DataRow
For Each dr In ds.Tables(0).Rows
Dim dcol As System.Data.DataColumn
For Each dcol In ds.Tables(0).Columns
'Declare Array
Dim MyArray As String() = {dcol.ColumnName.ToString(), dr(dcol.ColumnName.ToString()).ToString()}
NewDs.Tables(0).Rows.Add(MyArray)
Next
Next
Return NewDs
End Function 'GoDoReShape

C#

SqlConnection cn ;
SqlDataAdapter da;
DataSet ds;

private void Page_Load(object sender, System.EventArgs e)


{
// Put user code to initialize the page here
cn =new SqlConnection("server=localhost;uid=sa;pwd=;database=northwind");
da=new SqlDataAdapter ( "Select * from orders where orderid=10248",cn);
ds = new DataSet();
da.Fill (ds,"Orders");
DataGrid1.DataSource =GoDoReShape (ds);
DataGrid1.DataBind ();
}

public DataSet GoDoReShape(DataSet ds)


{
DataSet NewDs=new DataSet();

NewDs.Tables.Add();
//Create Two Columns with names "ColumnName" and "Value"
//ColumnName -> Displays all ColumnNames
//Value -> Displays ColumnData
NewDs.Tables[0].Columns.Add("ColumnName");
NewDs.Tables[0].Columns.Add("Value");

foreach(DataRow dr in ds.Tables [0].Rows )


{
foreach(System.Data.DataColumn dcol in ds.Tables[0].Columns)
{
//Declare Array
string[] MyArray={dcol.ColumnName.ToString(),dr[dcol.ColumnName.ToString()].ToString()};
NewDs.Tables[0].Rows.Add(MyArray);
}
}
return NewDs;
}

76
25.53 How can I fix error message "Invalid CurrentPageIndex value. It must
be >= 0 and < the PageCount"?

There are two approaches to fix this error:

• Set the CurrentPageIndex = 0 when you bind data in the Page_EventHandler

• Allow the error to occur and then catch it in a try block resetting the index to 0 and rebinding the grid

VB.NET

try
'Bind the Data
catch ex as ArgumentOutOfRangeException
DataGrid1.CurrentPageIndex = 0;
'Bind the Data
end try

C#

try
{
//Bind the Data
}
catch(ArgumentOutOfRangeException ex )
{
DataGrid1.CurrentPageIndex = 0;
//Bind the Data
}

25.54 How to edit a record using DataGrid?

<asp:datagrid id="DataGrid1" runat="server" DataKeyField="OrderID"


OnUpdateCommand="DataGrid1_Update" OnEditCommand="DataGrid1_Edit"
OnCancelCommand="DataGrid1_Cancel">
<Columns>
<asp:EditCommandColumn EditText="Edit" CancelText="Cancel" UpdateText="Update" />
</Columns>
</asp:datagrid>
<asp:Label id="lblError" style="Z-INDEX: 101; LEFT: 16px; POSITION: absolute; TOP: 160px" runat="server"
Visible="False" ForeColor="Red"></asp:Label>

VB.NET

Dim mycn As SqlConnection


Dim myda As SqlDataAdapter
Dim ds As DataSet

77
Dim strConn, strSQL As String

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load


strConn = "server=localhost;uid=sa;database=northwind;pwd=;"
If Not Page.IsPostBack Then
BindGrid()
End If
End Sub 'Page_Load

Sub BindGrid()
mycn = New SqlConnection(strConn)
strSQL = "Select * from [Order Details] where orderid=10249"
myda = New SqlDataAdapter(strSQL, mycn)
ds = New DataSet
myda.Fill(ds, "Table")
DataGrid1.DataSource = ds
DataGrid1.DataBind()
End Sub 'BindGrid

Public Sub DataGrid1_Cancel(ByVal sender As [Object], ByVal e As DataGridCommandEventArgs)


DataGrid1.EditItemIndex = -1
BindGrid()
End Sub 'DataGrid1_Cancel

Public Sub DataGrid1_Edit(ByVal sender As [Object], ByVal e As DataGridCommandEventArgs)


DataGrid1.EditItemIndex = CInt(e.Item.ItemIndex)
BindGrid()
End Sub 'DataGrid1_Edit

Public Sub DataGrid1_Update(ByVal sender As [Object], ByVal e As DataGridCommandEventArgs)


Dim unitprice As String = CType(e.Item.Cells(3).Controls(0), TextBox).Text
Dim quantity As String = CType(e.Item.Cells(4).Controls(0), TextBox).Text
Dim discount As String = CType(e.Item.Cells(5).Controls(0), TextBox).Text
Dim orderid As Integer = CInt(DataGrid1.DataKeys(CInt(e.Item.ItemIndex)))
Dim productid As String = CType(e.Item.Cells(2).Controls(0), TextBox).Text

Try
Dim updateCmd As String = "UPDATE [Order Details] SET UnitPrice = @UnitPrice," + "Quantity = @Quantity,
Discount = @Discount where OrderId =@OrderId and ProductId=@ProductId"
Dim cn As New SqlConnection(strConn)
Dim myCommand As New SqlCommand(updateCmd, cn)
myCommand.Parameters.Add(New SqlParameter("@UnitPrice", Convert.ToDecimal(unitprice)))
myCommand.Parameters.Add(New SqlParameter("@Quantity", Convert.ToInt16(quantity)))
myCommand.Parameters.Add(New SqlParameter("@Discount", Convert.ToInt16(discount)))
myCommand.Parameters.Add(New SqlParameter("@OrderId", orderid))
myCommand.Parameters.Add(New SqlParameter("@ProductId", Convert.ToInt16(productid)))
cn.Open()
myCommand.ExecuteNonQuery()
DataGrid1.EditItemIndex = -1
BindGrid()
Catch ex As Exception
lblError.Visible = True
lblError.Text = ex.Message
End Try
End Sub 'DataGrid1_Update

C#

SqlConnection mycn;
SqlDataAdapter myda;
DataSet ds;
string strConn,strSQL;

78
private void Page_Load(object sender, System.EventArgs e)
{
strConn ="server=localhost;uid=sa;database=northwind;pwd=;";
if (!Page.IsPostBack )
{
BindGrid();
}
}

void BindGrid()
{
mycn = new SqlConnection(strConn);
strSQL = "Select * from [Order Details] where orderid=10249" ;
myda = new SqlDataAdapter (strSQL, mycn);
ds= new DataSet ();
myda.Fill (ds,"Table");
DataGrid1.DataSource =ds;
DataGrid1.DataBind ();
}

public void DataGrid1_Cancel(Object sender, DataGridCommandEventArgs e)


{
DataGrid1.EditItemIndex = -1;
BindGrid();
}

public void DataGrid1_Edit(Object sender, DataGridCommandEventArgs e)


{
DataGrid1.EditItemIndex = (int)e.Item.ItemIndex;
BindGrid();
}

public void DataGrid1_Update(Object sender, DataGridCommandEventArgs e)


{
string unitprice =((TextBox)e.Item.Cells[3].Controls[0] ).Text ;
string quantity =((TextBox)e.Item.Cells[4].Controls[0] ).Text ;
string discount=((TextBox)e.Item.Cells[5].Controls[0] ).Text ;
int orderid = (int)DataGrid1.DataKeys[(int)e.Item.ItemIndex];
string productid= ((TextBox)e.Item.Cells[2].Controls[0] ).Text ;
try
{
string updateCmd = "UPDATE [Order Details] SET UnitPrice = @UnitPrice,"
+ "Quantity = @Quantity, Discount = @Discount where OrderId =@OrderId and ProductId=@ProductId";
SqlConnection cn = new SqlConnection (strConn);
SqlCommand myCommand = new SqlCommand(updateCmd, cn);
myCommand.Parameters.Add(new SqlParameter("@UnitPrice", Convert.ToDecimal(unitprice )));
myCommand.Parameters.Add(new SqlParameter("@Quantity", Convert.ToInt16 (quantity ) ));
myCommand.Parameters.Add(new SqlParameter("@Discount", Convert.ToInt16 ( discount )));
myCommand.Parameters.Add(new SqlParameter("@OrderId", orderid));
myCommand.Parameters.Add(new SqlParameter("@ProductId", Convert.ToInt16 ( productid)));
cn.Open ();
myCommand.ExecuteNonQuery ();
DataGrid1.EditItemIndex = -1;
BindGrid();
}
catch(Exception ex)
{
lblError.Visible =true;
lblError.Text =(ex.Message );
}
}

79
25.55 How to delete a record using DataGrid?

<asp:datagrid id="DataGrid1" runat="server" DataKeyField="Regionid" OnDeleteCommand="DataGrid1_Delete"


OnEditCommand="DataGrid1_Edit" OnCancelCommand="DataGrid1_Cancel">
<Columns>
<asp:ButtonColumn Text="Delete" CommandName="Delete" />
</Columns>
</asp:datagrid>
<asp:Label id="lblError" style="Z-INDEX: 101; LEFT: 16px; POSITION: absolute; TOP: 160px" runat="server"
Visible="False" ForeColor="Red"></asp:Label>

VB.NET

Dim mycn As SqlConnection


Dim myda As SqlDataAdapter
Dim ds As DataSet
Dim strConn, strSQL As String

Private Sub Page_Load(sender As Object, e As System.EventArgs)


strConn = "server=localhost;uid=sa;database=northwind;pwd=;"
If Not Page.IsPostBack Then
BindGrid()
End If
End Sub 'Page_Load

Sub BindGrid()
mycn = New SqlConnection(strConn)
strSQL = "Select * from Region"
myda = New SqlDataAdapter(strSQL, mycn)
ds = New DataSet()
myda.Fill(ds, "Table")
DataGrid1.DataSource = ds
DataGrid1.DataBind()
End Sub 'BindGrid

Public Sub DataGrid1_Cancel(sender As [Object], e As DataGridCommandEventArgs)


DataGrid1.EditItemIndex = - 1
BindGrid()
End Sub 'DataGrid1_Cancel

Public Sub DataGrid1_Edit(sender As [Object], e As DataGridCommandEventArgs)


DataGrid1.EditItemIndex = CInt(e.Item.ItemIndex)
BindGrid()
End Sub 'DataGrid1_Edit

Public Sub DataGrid1_Delete(sender As [Object], e As DataGridCommandEventArgs)


Dim orderid As Integer = CInt(DataGrid1.DataKeys(CInt(e.Item.ItemIndex)))
Dim deleteCmd As [String] = "DELETE from Region where Regionid = @Regionid "
Dim cn As New SqlConnection(strConn)
Dim myCommand As New SqlCommand(deleteCmd, cn)
myCommand.Parameters.Add(New SqlParameter("@Regionid", SqlDbType.Int))
myCommand.Parameters("@Regionid").Value = DataGrid1.DataKeys(CInt(e.Item.ItemIndex))
myCommand.Connection.Open()
Try
myCommand.ExecuteNonQuery()
Catch
lblError.Text = "ERROR: Could not delete record"
End Try
myCommand.Connection.Close()
BindGrid()

80
End Sub 'DataGrid1_Delete

C#

SqlConnection mycn;
SqlDataAdapter myda;
DataSet ds;
string strConn,strSQL;

private void Page_Load(object sender, System.EventArgs e)


{
strConn ="server=localhost;uid=sa;database=northwind;pwd=;";
if (!Page.IsPostBack )
{
BindGrid();
}
}

void BindGrid()
{
mycn = new SqlConnection(strConn);
strSQL = "Select * from Region" ;
myda = new SqlDataAdapter (strSQL, mycn);
ds= new DataSet ();
myda.Fill (ds,"Table");
DataGrid1.DataSource =ds;
DataGrid1.DataBind ();
}

public void DataGrid1_Cancel(Object sender, DataGridCommandEventArgs e)


{
DataGrid1.EditItemIndex = -1;
BindGrid();
}

public void DataGrid1_Edit(Object sender, DataGridCommandEventArgs e)


{
DataGrid1.EditItemIndex = (int)e.Item.ItemIndex;
BindGrid();
}

public void DataGrid1_Delete(Object sender, DataGridCommandEventArgs e)


{
int orderid=(int) DataGrid1.DataKeys[(int)e.Item.ItemIndex];;
String deleteCmd = "DELETE from Region where Regionid = @Regionid ";
SqlConnection cn = new SqlConnection (strConn);
SqlCommand myCommand = new SqlCommand(deleteCmd, cn);
myCommand.Parameters.Add(new SqlParameter("@Regionid", SqlDbType.Int ));
myCommand.Parameters["@Regionid"].Value = DataGrid1.DataKeys[(int)e.Item.ItemIndex];
myCommand.Connection.Open();
try
{
myCommand.ExecuteNonQuery();
}
catch (SqlException)
{
lblError.Text = "ERROR: Could not delete record";
}
myCommand.Connection.Close();
BindGrid();
}

81
25.56 How to use a HyperlinkColumn for a DataGrid?

<asp:DataGrid id="DataGrid1" AutoGenerateColumns="False" runat="server">


<Columns>
<asp:HyperLinkColumn HeaderText="ID" DataNavigateUrlField="ID"
DataNavigateUrlFormatString="page2.aspx?id={0}"
DataTextField="ID"></asp:HyperLinkColumn>
</Columns>
</asp:DataGrid>

25.57 How to use a LinkButton in a DataGrid?

<asp:DataGrid id="DataGrid1" OnItemCommand="ItemCmd" runat="server">


<Columns>
<asp:ButtonColumn DataTextField="ProductID" CommandName="Show" HeaderText="Productid"
ButtonType="LinkButton"
Text="Click"></asp:ButtonColumn>
</Columns>
</asp:DataGrid>

VB.NET

Protected Sub ItemCmd(source As Object, e As System.Web.UI.WebControls.DataGridCommandEventArgs)


If e.CommandName.ToString() = "Show" Then
Response.Write(e.Item.Cells(5).Text)
End If
End Sub 'ItemCmd

C#

protected void ItemCmd(Object source, System.Web.UI.WebControls.DataGridCommandEventArgs e )


{
if (e.CommandName.ToString () == "Show")
{
Response.Write( e.Item.Cells[5].Text );
}
}

25.58 How can I display the field as a link in the DataGrid? If may or may not
be stored in the "http://" format.

82
<asp:DataGrid id="DataGrid1" AutoGenerateColumns="False" runat="server">
<Columns>
<asp:TemplateColumn HeaderText="Link">
<ItemTemplate>
<asp:HyperLink Runat =server NavigateUrl ='<%#GetURL(DataBinder.Eval(Container.DataItem,
"RegionDescription").ToString())%>' ID="Hyperlink1">
<%#DataBinder.Eval(Container.DataItem, "RegionDescription")%>
</asp:HyperLink>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>

VB.NET

Protected Function GetURL(ByVal fldval As String) As String


If fldval.IndexOf("http://", 0, fldval.Length) = 0 Then
Return fldval
Else
Return "http://" + fldval
End If
End Function 'GetURL

C#

protected string GetURL (string fldval )


{
if (fldval.IndexOf ( "http://" , 0, fldval.Length ) ==0)
{
return fldval;
}
else
{
return "http://" + fldval;
}
}

25.59 How to hide a column in a Datagrid if AutoGenerateColumns is set to


True?

<asp:DataGrid id="DataGrid1" onItemDataBound="ItemDB" runat="server"></asp:DataGrid>

VB.NET

protected Sub ItemDB (ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs)


e.Item.Cells(0).Visible = False
End Sub

83
C#

protected void ItemDB (object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)


{
e.Item.Cells[0].Visible = false;
}

25.60 How do I change the width of the Textboxes created for edit-mode of a
Datagrid?

<asp:DataGrid id="DataGrid1" runat="server" AutoGenerateColumns="False">


<Columns>
<asp:TemplateColumn HeaderText="ProductName">
<ItemTemplate>
<%#DataBinder.Eval(Container.DataItem, "ProductName").ToString()%>
</ItemTemplate>
<EditItemTemplate>
<asp:Textbox runat="server" width="450" maxlength="450"/>
</EditItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>

25.61 How to display a Tooltip when hovering over the Header sort link of the
DataGrid?

Protected Sub ItemDB(sender As Object, e As System.Web.UI.WebControls.DataGridItemEventArgs)


Dim i As Integer
For i = 0 To e.Item.Cells.Count - 1
e.Item.Cells(i).ToolTip = "This is Column " + i.ToString()
Next
End Sub 'ItemDB

C#

protected void ItemDB (object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)


{
for(int i=0 ;i<= e.Item.Cells.Count -1;i++)
{
e.Item.Cells[i].ToolTip = "This is Column " + i.ToString();
}
}

84
25.62 How to right align cells in the Datagrid when using BoundColumn?

Commonly used in conjunction with RTL languages, you can do so as follows:

<asp:BoundColumn DataField ="PRoductname" HeaderText ="ProductName" ItemStyle-


HorizontalAlign="Right"></asp:BoundColumn>

25.63 How to hide a row in a DataGrid if one of the Column value is zero?

VB.NET

Protected Sub ItemDB(sender As Object, e As System.Web.UI.WebControls.DataGridItemEventArgs)


If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.Item Then
If e.Item.Cells(8).Text = "0" Then
e.Item.Visible = False
End If
End If
End Sub 'ItemDB

C#

protected void ItemDB (object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)


{
if((e.Item.ItemType == ListItemType.Item ) || (e.Item.ItemType == ListItemType.Item ))
{
if( e.Item.Cells [8].Text == "0")
{
e.Item.Visible = false;
}
}
}

25.64 How can I disable sorting for a specific Column in a DataGrid?

Don't specify the SortExpression for the BoundColumn for which you do not want Sorting. This will only work if you

have AutogenerateColumns= false.

25.65 Why do I get error message "NewPageIndex is not a member of


"System.EventArgs"."?

You probably declared the event handler for OnPageIndexChanged event incorrectly. Make sure that the event

handler looks like the following.

85
<asp:DataGrid id="DataGrid1" runat="server"... OnPageIndexChanged="<EventName>".../>

VB.NET

protected Sub <Eventname>(ByVal source As Object, ByVal e As


System.Web.UI.WebControls.DataGridPageChangedEventArgs)
'...
end sub

C#

protected void <EventName>(object sender , System.Web.UI.WebControls.DataGridPageChangedEventArgs)


{
//...
}

25.66 How to create a Main Header in DataGrid along with the DataGrid
Column Headers?

You have to manually add a row to the table generated by the datagrid as follows.

<asp:DataGrid id="DataGrid1" OnPreRender ="dgPreRender" runat="server"></asp:DataGrid>

VB.NET

protected Sub dgPreRender(ByVal sender As Object, ByVal e As System.EventArgs)


Dim dgItem As New DataGridItem(0, 0, ListItemType.Header)
Dim tbCell As New TableCell
tbCell.ColumnSpan = 3 'Set it to the colspan that you want
tbCell.Text = "Category Information"
tbCell.Attributes.Add("style", "text-align:center")
dgItem.Cells.Add(tbCell)
DataGrid1.Controls(0).Controls.AddAt(0, dgItem)
End Sub

C#

protected void dgPreRender(object sender, System.EventArgs e )


{
DataGridItem dgItem = new DataGridItem (0, 0, ListItemType.Header);
TableCell tbCell = new TableCell();
tbCell.ColumnSpan = 3;// Set it to the colspan that you want
tbCell.Text = "Category Information";
tbCell.Attributes.Add("style", "text-align:center");
dgItem.Cells.Add(tbCell);

86
DataGrid1.Controls[0].Controls.AddAt(0, dgItem);
}

25.67 Is there a way to show more than one datafield in a column when using
a datagrid?

Yes. Use a TemplateColumn in a DataGrid

<asp:DataGrid id="DataGrid1" runat=server AutoGenerateColumns=False>


<Columns>
<asp:TemplateColumn HeaderText="Field">
<ItemTemplate>
<%#DataBinder.Eval(Container.DataItem, "Field1").ToString()%> -
<%#DataBinder.Eval(Container.DataItem, "Field2").ToString()%>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>

25.68 How to databind a textbox in a column template that is inside a


datagrid?

<asp:TextBox runat="server" id="TextBox1" Text=<%#


DataBinder.Eval(Container.DataItem,"theColumName").ToString() %></asp:TextBox>

Same goes true for any other Web Server control

25.69 How can I simulate a scrollbar in a DataGrid?

<div style="width:100%; height:200; overflow:auto;">


<asp:DataGrid id="DataGrid1" runat="server"></asp:DataGrid>
</div>

25.70 How to clear a DataGrid?

VB.NET

DataGrid1.DataSource = Nothing
DataGrid1.DataBind()

87
C#

DataGrid1.DataSource = null;
DataGrid1.DataBind();

25.71 How to trigger the checkChanged event of the checkbox inside a


DataGrid?

<asp:DataGrid id="DataGrid1" runat="server">


<Columns>
<asp:TemplateColumn HeaderText="Boolean Value">
<ItemTemplate>
<asp:CheckBox id=CheckBox1 runat="server" onCheckedChanged="chkChanged" Checked='<%#
DataBinder.Eval(Container.DataItem, "Discontinued") %>' AutoPostBack="True">
</asp:CheckBox>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>

VB.NET

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load


'Put user code to initialize the page here
If Not IsPostBack Then
'Populate the datagrid
End If
End Sub

protected Sub chkChanged(ByVal sender As Object, ByVal e As System.EventArgs)


Response.Write("CheckChanged Event")
End Sub

C#

private void Page_Load(object sender, System.EventArgs e)


{
// Put user code to initialize the page here
if (!Page.IsPostBack )
{
DataGrid1.DataSource =BindDataClass.BindData ();
DataGrid1.DataBind ();
}
}

protected void chkChanged(object sender , System.EventArgs e )


{
Response.Write("CheckChanged Event");
}

88
25.72 How to display "No data exists" within the datagrid rather than just
showing Column Headers with no rows?

<asp:DataGrid id="DataGrid1" OnItemDataBound ="ItemDB" runat="server"></asp:DataGrid>

VB.NET

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load


' Put user code to initialize the page here
If Not Page.IsPostBack Then
'Populate the dataSet
'Bind the dataGrid with the dataView
DataGrid1.DataSource = BindTheDataClass.Binddata().Tables(0).DefaultView
DataGrid1.DataBind()
End If
End Sub 'Page_Load

Protected Sub ItemDB(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs)


Dim dv As DataView = CType(DataGrid1.DataSource, DataView)
Dim drv As DataRowView = CType(e.Item.DataItem, DataRowView)
If dv.Table.Rows.Count = 0 Then
'By default the Datagrid Header is shown in case there is no Data Avaiable
'So in case of No Data found
'Check the ListItemType.Header
If e.Item.ItemType = ListItemType.Header Then
Dim i As Integer = e.Item.Cells.Count

'Assign "No Search result Found" in one of the cells of DataGrid


e.Item.Cells(0).Text = "No Search Results Found"

'Remove Rest of the empty cells from Datagrid


Dim j As Integer
For j = i - 1 To 1 Step -1
e.Item.Cells.RemoveAt(j)
Next
End If
End If
End Sub 'ItemDB

C#

private void Page_Load(object sender, System.EventArgs e)


{
// Put user code to initialize the page here
if (!Page.IsPostBack )
{
//Fill DataSet
//Bind the DataGrid with the DataView
DataGrid1.DataSource =ds.Tables[0].DefaultView ;
DataGrid1.DataBind ();
}
}

89
protected void ItemDB(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{
DataView dv =(DataView)DataGrid1.DataSource ;
DataRowView drv = (DataRowView)e.Item.DataItem ;
if (dv.Table.Rows.Count == 0 )
{
//By default the Datagrid Header is shown in case there is no Data Avaiable
//So in case of No Data found
//Check the ListItemType.Header
if ((e.Item.ItemType == ListItemType.Header))
{
int i= e.Item.Cells.Count;

//Assign "No Search result Found" in one of the cells of DataGrid


e.Item.Cells [0].Text = "No Search Results Found";

//Remove Rest of the empty cells from Datagrid


for (int j=i-1;j>0;j--)
{
e.Item.Cells.RemoveAt(j);
}
}
}
}

25.73 How to fill a DataGrid with an array?

<asp:DataGrid id="DataGrid1" runat="server"></asp:DataGrid>

VB.NET

Dim strArray As String() = {"Tom", "Jerry", "Harry", "Mickey"}


DataGrid1.DataSource = strArray
DataGrid1.DataBind()

C#

string[] strArray = {"Tom","Jerry", "Harry", "Mickey"};


DataGrid1.DataSource = strArray;
DataGrid1.DataBind();

25.74 How to add a Column dynamically to the datagrid to include custom


expressions?

<asp:DataGrid id="DataGrid1" runat="server"></asp:DataGrid>

90
VB.NET

'Fill the DataSet ds with data from database


Dim dc As DataColumn
dc = New DataColumn("Total", Type.GetType("System.Double"))
dc.Expression = "UnitPrice * UnitsInStock"
ds.Tables(0).Columns.Add(dc)

DataGrid1.DataSource = ds
DataGrid1.DataBind()

C#

//Fill the DataSet ds with data from database


DataColumn dc ;
dc = new DataColumn("Total", Type.GetType("System.Double"));
dc.Expression = "UnitPrice * UnitsInStock";
ds.Tables[0].Columns.Add(dc);

DataGrid1.DataSource = ds;
DataGrid1.DataBind();

25.75 How to access the BoundColumn information on SelectedIndexChanged


event of a datagrid?

<asp:Label id="Label1" runat="server">Label</asp:Label>


<asp:DataGrid id="DataGrid1" OnSelectedIndexChanged=SelectedIndexChg AutoGenerateColumns="False"
runat="server">
<Columns>
<asp:ButtonColumn Text ="Select" ButtonType =PushButton CommandName ="Select" ></asp:ButtonColumn>
<asp:BoundColumn Headertext="ProductId" DataField="Productid"></asp:BoundColumn>
<asp:BoundColumn Headertext="ProductName" DataField="ProductName"></asp:BoundColumn>
</Columns>
</asp:DataGrid>

VB.NET

Protected Sub SelectedIndexChg(ByVal sender As Object, ByVal e As System.EventArgs)


Label1.Text = DataGrid1.SelectedItem.Cells(1).Text & DataGrid1.SelectedItem.Cells(2).Text
End Sub

C#

protected void SelectedIndexChg(object sender, System.EventArgs e)


{
Label1.Text = DataGrid1.SelectedItem.Cells[1].Text + DataGrid1.SelectedItem.Cells[2].Text ;

91
}

25.76 How to access the TemplateColumn information on


SelectedIndexChanged event of a datagrid?

<asp:Label id="Label1" runat="server">Label</asp:Label>


<asp:DataGrid id="DataGrid1" OnSelectedIndexChanged="SelectedIndexChg" AutoGenerateColumns="False"
runat="server">
<Columns>
<asp:ButtonColumn Text="Select" ButtonType="PushButton" CommandName="Select"></asp:ButtonColumn>
<asp:TemplateColumn HeaderText="ProductId">
<ItemTemplate>
<%#DataBinder.Eval(Container.DataItem , "Productid")%>
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="ProductName">
<ItemTemplate>
<%#DataBinder.Eval(Container.DataItem , "ProductName")%>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>

VB.NET

Protected Sub SelectedIndexChg(ByVal sender As Object, ByVal e As System.EventArgs)


Label1.Text = CType(DataGrid1.SelectedItem.Cells(1).Controls(0), DataBoundLiteralControl).Text &
CType(DataGrid1.SelectedItem.Cells(2).Controls(0), DataBoundLiteralControl).Text
End Sub

C#

protected void SelectedIndexChg(object sender, System.EventArgs e)


{
Label1.Text = ((DataBoundLiteralControl)DataGrid1.SelectedItem.Cells[1].Controls[0]).Text +
((DataBoundLiteralControl)DataGrid1.SelectedItem.Cells[2].Controls[0]).Text;
}

25.77 How to access information from the controls in the TemplateColumn in


SelectedIndexChanged Event?

<asp:Label id="Label1" runat="server">Label</asp:Label>


<asp:DataGrid id="DataGrid1" OnSelectedIndexChanged="SelectedIndexChg" AutoGenerateColumns="False"
runat="server">
<Columns>
<asp:ButtonColumn Text="Select" ButtonType="PushButton" CommandName="Select"></asp:ButtonColumn>
<asp:TemplateColumn HeaderText="ProductId">

92
<ItemTemplate>
<asp:Label text=<%#DataBinder.Eval(Container.DataItem , "Productid")%> ID="lbl1" Runat=server
></asp:Label>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>

VB.NET

Protected Sub SelectedIndexChg(ByVal sender As Object, ByVal e As System.EventArgs)


Label1.Text = CType(DataGrid1.SelectedItem.FindControl("lbl1"), Label).Text
End Sub

C#

protected void SelectedIndexChg(object sender, System.EventArgs e)


{
Label1.Text = ((Label)DataGrid1.SelectedItem.FindControl ("lbl1")).Text ;
}

25.78 How to display the total of a particular column at the footer of the
DataGrid?

<asp:DataGrid id="DataGrid1" OnItemDataBound="ItemDB" ShowFooter =true runat="server"></asp:DataGrid>

VB.NET

Dim UnitPrice As Double


Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Put user code to initialize the page here
'Bind the Data to datagrid
End Sub

Protected Sub UPTotal(ByVal _unitprice As Double)


UnitPrice += _unitprice
End Sub 'UPTotal

Public Sub ItemDB(ByVal sender As Object, ByVal e As DataGridItemEventArgs)


If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then
UPTotal(Double.Parse(e.Item.Cells(1).Text.ToString))
Else
If e.Item.ItemType = ListItemType.Footer Then
e.Item.Cells(0).Text = " Total "
e.Item.Cells(1).Text = UnitPrice.ToString()
End If
End If
End Sub 'ItemDB

93
C#

double UnitPrice;
private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
if(!Page.IsPostBack )
{
//Bind the DataGrid
}
}

protected void UPTotal(double _unitprice)


{
UnitPrice += _unitprice;
}

public void ItemDB(object sender, DataGridItemEventArgs e)


{
if ((e.Item.ItemType == ListItemType.Item) ||( e.Item.ItemType == ListItemType.AlternatingItem))
{
UPTotal(Double.Parse ( e.Item.Cells[1].Text ));
}
else if (e.Item.ItemType ==ListItemType.Footer )
{
e.Item.Cells [0].Text =" Total ";
e.Item.Cells[1].Text =UnitPrice.ToString ();
}
}

25.79 Why does the DataGrid web server control contents wrap when
ItemStyle Wrap or HeaderStyle Wrap Property is set to False?

The wrap functionality occurs for each cell and not for each row of the DataGrid. Therefore, if you disabled the wrap

functionality for all of the DataGrid, text wrapping functionality is not disabled for every row or column. To resolve

this make sure that every column of the DataGrid has the ItemStyle Wrap property explicitly set to False as follows:

<ItemStyle Wrap="False"></ItemStyle>

For more details refer

• Microsoft Knowledge Base Article - 323169

• Microsoft Knowledge Base Article - 324165

25.80 How can I have an onclick event in the DataGrid for any Column?

94
<asp:DataGrid id="DataGrid1" OnItemDataBound ="ItemDB" DataKeyField ="ProductId"
runat="server"></asp:DataGrid>

VB.NET

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load


'Put user code to initialize the page here
If Not Page.IsPostBack Then
'Bind the dataGrid to DataView
End If
End Sub

Protected Sub ItemDB(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs)


Dim dv As DataView = DataGrid1.DataSource
Dim dcCol As DataColumn
Dim dc As DataColumnCollection = dv.Table.Columns
Dim strID As String
For Each dcCol In dv.Table.Columns
If e.Item.ItemType = ListItemType.AlternatingItem Or _
e.Item.ItemType = ListItemType.Item Then
strID = DataGrid1.DataKeys(e.Item.ItemIndex)
e.Item.Cells(dc.IndexOf(dc(dcCol.ColumnName))).Attributes.Add("style", "cursor:hand")
e.Item.Cells(dc.IndexOf(dc(dcCol.ColumnName))).Attributes.Add("onclick", _
"javascript:window.open('details.aspx?id=" & strID & "'," _
& "'MyPage','height=300,width=300')")
End If
Next
End Sub

C#

private void Page_Load(object sender, System.EventArgs e)


{
// Put user code to initialize the page here
if(!Page.IsPostBack )
{
//Bind Datagrid to DataView
}
}

protected void ItemDB(object sender , System.Web.UI.WebControls.DataGridItemEventArgs e )


{
DataView dv = (DataView)DataGrid1.DataSource;
DataColumnCollection dc = dv.Table.Columns ;
string strID;
foreach (DataColumn dcCol in dv.Table.Columns)
{
if ((e.Item.ItemType == ListItemType.AlternatingItem )||(e.Item.ItemType == ListItemType.Item ))
{
strID = DataGrid1.DataKeys[e.Item.ItemIndex].ToString ();
e.Item.Cells[dc.IndexOf(dc[dcCol.ColumnName])].Attributes.Add("style", "cursor:hand");
e.Item.Cells[dc.IndexOf(dc[dcCol.ColumnName])].Attributes.Add("onclick",
"javascript:window.open('details.aspx?id=" + strID + "'," + "'MyPage','height=300,width=300')");
}
}
}

95
25.81 How should I avoid getting blank page on click of linkbutton inspite of
setting the EnableViewState= true for DataGrid?

You should bind the data each time the page is loaded

25.82 Why do I get a blank page when I click the linkbutton in the Datagrid, I
am also handling PostBack on the page? The ItemCommand Event does not
seem to trigger?

You must have set the EnableViewState property of DataGrid to false

25.83 How to export data in Datagrid on a webform to Microsoft Excel?

Two techniques for exporting the data in the DataGrid:

• Using the Excel MIME Type (or Content Type)

With server-side code, you can bind the DataGrid to your data and have the data open in Excel on a client

computer. To do this, set the ContentType to application/vnd.ms-excel. After the client receives the new

stream, the data appears in Excel as if the content was opened as a new page in the Web browser.

• Using Excel Automation

With client-side code, you can extract the HTML from the DataGrid and then Automate Excel to display the

HTML in a new workbook. With Excel Automation, the data always appears outside the browser in an Excel

application window. One advantage to Automation is that you can programmatically control Excel if you

want to modify the workbook after the data is exported. However, because Excel is not marked as safe for

scripting, your clients must apply security settings in the Web browser that allow Automation.

For more details refer How To Export Data in a DataGrid on an ASP . NET WebForm to Microsoft Excel

25.84 How to export DataGrid data to excel?

Use namespace System.IO

VB.NET

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load


'Put user code to initialize the page here
'Bind the DataGrid to DataSet
DataGridToExcel(DataGrid1, Response)
End Sub

Protected Sub DataGridToExcel(ByVal dGridExport As DataGrid, ByVal httpResp As HttpResponse)


httpResp.Clear()

96
httpResp.Charset = ""
httpResp.ContentType = "application/vnd.ms-excel"
Dim stringWrite As New StringWriter
Dim htmlWrite As New HtmlTextWriter(stringWrite)
Dim dGrid As New DataGrid
dGrid = dGridExport
dGrid.HeaderStyle.Font.Bold = True
dGrid.DataBind()
dGrid.RenderControl(htmlWrite)
httpResp.Write(stringWrite.ToString)
httpResp.End()
End Sub

C#

private void Page_Load(object sender, System.EventArgs e)


{
// Put user code to initialize the page here
//Bind the DataGrid to DataSet
DataGridToExcel (DataGrid1, Response);
}
protected void DataGridToExcel(DataGrid dGridExport , HttpResponse httpResp)
{
httpResp.Clear();
httpResp.Charset = "";
httpResp.ContentType = "application/vnd.ms-excel";
StringWriter stringWrite = new StringWriter();
HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
DataGrid dGrid = new DataGrid();
dGrid = dGridExport;
dGrid.HeaderStyle.Font.Bold = true;
dGrid.DataBind();
dGrid.RenderControl(htmlWrite);
httpResp.Write(stringWrite.ToString());
httpResp.End();
}

13. Custom Controls

27.1 How do I insert custom @ Register tags into the aspx file from my
custom control?

In the custom control's custom designer's Initialize override, do something like this:

[C#]
public override void Initialize(IComponent component)
{

base.Initialize (component);

IDesignerHost host = component.Site.Container as IDesignerHost;


IDesigner designer = host.GetDesigner(host.RootComponent);

// Calling GetHTMLFromWebControlTool with the following custom toolboxitem will insert the
// Register directives for the type associated with that .
MethodInfo mi = designer.GetType.GetMethod("GetHTMLFromWebControlTool", BindingFlags.NonPublic |
BindingFlags.Instance);
if(mi != null)
{

97
// DependantType is a custom type defined in DependantAssembly.dll
mi.Invoke(designer, new object[]{new WebControlToolboxItem(typeof(SomeNamespace.DependantType))});
}
}

C Then when the user drags and drops the item from the toolbox, besides the default @ register entry it makes, it

will also make an entry like this: <%@ Register TagPrefix="cc1" Namespace="SomeNamespace"

Assembly="DependantAssembly, Version=2.0.0.1, Culture=neutral, PublicKeyToken=3d6dfsd1fdsd44c89" %>

The assembly will not be strong named in the above tag if it's not in the GAC.

15. Config files


30.1 What is the best place to store Database connection string?

In Web.Config, you would add a key to the AppSettings Section:

<appSettings>
<add key="MyDBConnection" value="server=<ServerName>;uid=<Username>;pwd=;database=<DBName>" />
</appSettings>

Example :

<add key="ConnectionString" value= "Server=localhost;uid=sa;pwd=;database=northwind" />

Then, in your ASP.Net application - just refer to it like this:

Dim myConnection As SqlConnection = New SqlConnection(ConfigurationSettings.AppSettings("ConnectionString"))

30.2 My web.config gives error "Unrecognized attribute 'verb'."?

Probably you have mispelled the attribute. It should be verbs not verb

30.3 Can I use IIS as an alternative way of configuring Custom error pages?

Yes, you can. But the preferable way would be ASP.NET, as the ASP.NET custom pages are configured in XML based

web.config (application configuration) file, resulting in easy (xcopy) deployment and management.

98
16. ADO.Net

31.2 How to get the count of records in the Database table using the DataSet?

VB.NET

ds.Tables(0).Rows.Count

C#

ds.Tables[0].Rows.Count ;

31.3 How to check if the Dataset has records?

VB.NET

if ds.Tables(0).Rows.Count= 0 then
'No record
else
'Record Found
end if

C#

if (ds.Tables[0].Rows.Count == 0 )
{
//No record
}
else
{
//Record Found
}

31.4 How to retrieve value of a field in a dataset?

VB.NET

ds.Tables("TableName").Rows(0)("ColumnName")

99
C#

ds.Tables["TableName"].Rows[0]["ColumnName"];

where TableName and ColumnName could be also integer (not in quotes then) to indicate you refer to the table's or

column's index position. Rows(0) indicates the first and only row in DataTable's Rows collection

31.5 How to filter the data in the DataView and display it in some
DataControl?

VB.NET

Dim thefilter as string = "fieldname='' "


dbDataView.RowFilter = thefilter
Repeater1.DataSource = dbDataView
Repeater.DataBind()

C#

string thefilter = "fieldname='' ";


dbDataView.RowFilter = thefilter;
Repeater1.DataSource = dbDataView;
Repeater.DataBind();

31.6 How to truncate the data in the column?

VB.NET

Protected function TruncateData( Byval strNotes as string)


If strNotes.Length > 20 then
Return strNotes.Substring(0,20) + "..."
Else
return strnotes
End function

C#

protected string TruncateData( string strNotes )


{
if (strNotes.Length > 20)
{
return strNotes.Substring(0,20) + "...";
}

100
else
{
return strNotes;
}
}

31.7 How to find the null fields in the datareader?

VB.NET

If dbReader("fieldname").Tostring= DBnull.Value.ToString()
'Empty field value
Else
'Display value
End if

C#

if (dbReader["fieldname").ToString() == DBNull.Value.ToString() )
{
//Empty field value
}
else
{
//display Value
}

31.8 How to Implement a DataSet SELECT DISTINCT Helper Class?

VB.NET

Sample code 1

C#

Sample Code 2

31.9 I am running the query SQL="Select name from profile where proID=1";
and I am getting the result in Dataset dsdata. Now how do I read the text
from the dataset and assign it to textbox1.text ?

VB.NET

dsData.Tables(0).Rows(0)("FieldName").ToString()

101
C#

dsData.Tables[0].Rows[0]["FieldName"].ToString()

31.10 How to query the database to get all the Table names?

SELECT * FROM information_schema.tables where Table_type='BASE TABLE'

31.11 How to View one record per page in ASP.NET?

<asp:label id="Label2" style="Z-INDEX: 106; LEFT: 111px; POSITION: absolute; TOP: 83px"
runat="server">Product ID</asp:label>
<asp:label id="Label1" style="Z-INDEX: 105; LEFT: 110px; POSITION: absolute; TOP: 43px"
runat="server">Product Name</asp:label>
<asp:textbox id="txtProductName" style="Z-INDEX: 104; LEFT: 206px; POSITION: absolute; TOP: 83px"
runat="server" OnDataBinding="txtDataBind"></asp:textbox>
<asp:textbox id="txtProductid" style="Z-INDEX: 103; LEFT: 204px; POSITION: absolute; TOP: 43px"
runat="server">
<asp:button id="btnPrevious" style="Z-INDEX: 102; LEFT: 137px; POSITION: absolute; TOP: 126px"
runat="server" Text="Previous" OnClick ="PrevBtn"></asp:button>
<asp:button id="btnNext" style="Z-INDEX: 101; LEFT: 243px; POSITION: absolute; TOP: 126px"
runat="server" Text="Next" OnClick ="NextBtn"></asp:button>

VB.NET

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load


'Put user code to initialize the page here
Try
'Fill the DataSet
If Not Page.IsPostBack Then
ViewState("CurrentPos") = 0
Me.DataBind()
End If
Catch ex As Exception
Response.Write(ex.Message & ex.StackTrace)
End Try
End Sub

protected Sub NextBtn(ByVal sender As System.Object, ByVal e As System.EventArgs)


Try
Dim CurrentPos As Integer = CType(ViewState("CurrentPos"), Integer)
CurrentPos += 1
If CurrentPos > ds.Tables(0).Rows.Count Then
CurrentPos -= 1
End If
ViewState("CurrentPos") = CurrentPos
Me.DataBind()
Catch ex As Exception

102
Response.Write(ex.Message)
End Try
End Sub

protected Sub PrevBtn(ByVal sender As System.Object, ByVal e As System.EventArgs)


Try
Dim CurrentPos As Integer = CType(ViewState("CurrentPos"), Integer)
If CurrentPos > 0 Then
CurrentPos -= 1
End If
ViewState("CurrentPos") = CurrentPos
Me.DataBind()
Catch ex As Exception
Response.Write(ex.Message)
End Try
End Sub

protected Sub txtDataBind(ByVal sender As Object, ByVal e As System.EventArgs)


Try
Dim CurrentPos As Integer = CType(ViewState("CurrentPos"), Integer)
ViewState("CurrentPos") = (CurrentPos)
txtProductid.Text = ds.Tables(0).Rows(CurrentPos).Item("productid")
txtProductName.Text = ds.Tables(0).Rows(CurrentPos).Item("productname")
Catch ex As Exception
Response.Write(ex.Message)
End Try
End Sub

C#

DataSet ds;
private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
//Fill the DataSet
if (!Page.IsPostBack )
{
ViewState["CurrentPos"] = 0 ;
this.DataBind() ;
}
}
protected void PrevBtn(object sender, System.EventArgs e)
{
try
{
int CurrentPos = (int)ViewState["CurrentPos"] ;
if (CurrentPos > 0 )
{
CurrentPos -= 1 ;
}
ViewState["CurrentPos"] = CurrentPos ;
this.DataBind() ;
}
catch (Exception ex)
{
Response.Write(ex.Message) ;
}
}

protected void NextBtn(object sender, System.EventArgs e)


{
try

103
{
int CurrentPos = (int)ViewState["CurrentPos"] ;
CurrentPos += 1 ;
if( CurrentPos > ds.Tables[0].Rows.Count)
{
CurrentPos -= 1 ;
}
ViewState["CurrentPos"] = CurrentPos ;
this.DataBind() ;
}
catch (Exception ex)
{
Response.Write(ex.Message) ;
}
}

protected void txtDataBind(Object sender , System.EventArgs e )


{
try
{
int CurrentPos = (int) ViewState["CurrentPos"];
ViewState["CurrentPos"] = CurrentPos ;
txtProductid.Text = ds.Tables[0].Rows[CurrentPos]["productid"].ToString();
txtProductName.Text = ds.Tables[0].Rows[CurrentPos]["productname"].ToString ();
}
catch (Exception ex)
{
Response.Write(ex.Message) ;
}
}

31.12 How to insert data in database using Textboxes?

<asp:Button id="btnAdd" style="Z-INDEX: 101; LEFT: 104px; POSITION: absolute; TOP: 168px"
runat="server" Text="Add Record"></asp:Button>
<asp:TextBox id="txtFirstName" style="Z-INDEX: 102; LEFT: 168px; POSITION: absolute; TOP: 40px"
runat="server"></asp:TextBox>
<asp:TextBox id="txtLastName" style="Z-INDEX: 103; LEFT: 168px; POSITION: absolute; TOP: 80px"
runat="server"></asp:TextBox>
<asp:TextBox id="txtDate" style="Z-INDEX: 104; LEFT: 168px; POSITION: absolute; TOP: 120px"
runat="server"></asp:TextBox>
<asp:Label id="Label1" style="Z-INDEX: 105; LEFT: 56px; POSITION: absolute; TOP: 240px"
runat="server"></asp:Label>

On Page_Load

VB.NET

if not Page.IsPostBack then


'....
end if

C#

104
if(!Page.IsPostBack )
{
//...
}

Use namespaces System.Data.SqlClient, System.Data.SqlTypes

On Button Click

VB.NET

Dim sqlStmt As String


Dim conString As String
Dim cn As SqlConnection
Dim cmd As SqlCommand
Dim sqldatenull As SqlDateTime
Try
sqlStmt = "insert into Emp (FirstName,LastName,Date) Values (@FirstName,@LastName,@Date) "
conString = "server=localhost;database=Northwind;uid=sa;pwd=;"
cn = New SqlConnection(conString)
cmd = New SqlCommand(sqlStmt, cn)

cmd.Parameters.Add(New SqlParameter("@FirstName", SqlDbType.NVarChar, 11))


cmd.Parameters.Add(New SqlParameter("@LastName", SqlDbType.NVarChar, 40))
cmd.Parameters.Add(New SqlParameter("@Date", SqlDbType.DateTime))

sqldatenull = SqlDateTime.Null

cmd.Parameters("@FirstName").Value = txtFirstName.Text
cmd.Parameters("@LastName").Value = txtLastName.Text
If (txtDate.Text = "") Then
cmd.Parameters("@Date").Value = sqldatenull
'cmd.Parameters("@Date").Value = DBNull.Value
Else
cmd.Parameters("@Date").Value = DateTime.Parse(txtDate.Text)
End If
cn.Open()
cmd.ExecuteNonQuery()
Label1.Text = "Record Inserted Succesfully"

Catch ex As Exception
Label1.Text = ex.Message
Finally
cn.Close()
End Try

On Button Click

C#

string sqlStmt ;
string conString ;
SqlConnection cn =null;
SqlCommand cmd =null;
SqlDateTime sqldatenull ;
try
{

105
sqlStmt = "insert into Employees (FirstName,LastName,HireDate) Values (@FirstName,@LastName,@Date) ";
conString = "server=localhost;database=Northwind;uid=sa;pwd=;";
cn = new SqlConnection(conString);
cmd = new SqlCommand(sqlStmt, cn);
cmd.Parameters.Add(new SqlParameter("@FirstName", SqlDbType.NVarChar, 11));
cmd.Parameters.Add(new SqlParameter("@LastName", SqlDbType.NVarChar, 40));
cmd.Parameters.Add(new SqlParameter("@Date", SqlDbType.DateTime));
sqldatenull = SqlDateTime.Null;
cmd.Parameters["@FirstName"].Value = txtFirstName.Text;
cmd.Parameters["@LastName"].Value = txtLastName.Text;
if (txtDate.Text == "")
{
cmd.Parameters ["@Date"].Value =sqldatenull ;
//cmd.Parameters["@Date"].Value = DBNull.Value;
}
else
{
cmd.Parameters["@Date"].Value = DateTime.Parse(txtDate.Text);
}
cn.Open();
cmd.ExecuteNonQuery();
Label1.Text = "Record Inserted Succesfully";
}
catch (Exception ex)
{
Label1.Text = ex.Message;
}
finally
{
cn.Close();
}

31.13 When I try to enter a null value for DataTime in Database I get error
message "String was not recognized as a valid DateTime" or "Value of type
'System.DBNull' cannot be converted to 'String'"?

Use namespace

System.Data.SqlTypes

VB.NET

Dim sqldatenull As SqlDateTime


sqldatenull = SqlDateTime.Null

If (txtDate.Text = "") Then


cmd.Parameters("@Date").Value = sqldatenull
'cmd.Parameters("@Date").Value = DBNull.Value
Else
cmd.Parameters("@Date").Value = DateTime.Parse(txtDate.Text)
End If

C#

106
if (txtDate.Text == "")
{
cmd.Parameters ["@Date"].Value =sqldatenull ;
//cmd.Parameters["@Date"].Value = DBNull.Value;
}
else
{
cmd.Parameters["@Date"].Value = DateTime.Parse(txtDate.Text);
}

31.14 How to use Parameterized queries in ASP.NET?

The follwoing sample is a good example of parameterized queries: How to insert data in database using Textboxes?

31.15 How to filter distinct records from a normal Select query and display in
a web control?

"Select distinct <field> from <table>".This SELECT statement is used to filter out duplicate results from a query's

output. But sometimes the requirement is to use a Stored Procedure which returns the entire data and dsiplay the

manipulated distinct data in web server control.

To do this use SortedList

For using SortedList import namespace System.Collections

Stored Procedure

Create Procedure GetSuppliers AS

SELECT * FROM Suppliers


GO

<asp:DataList id="DataList1" runat="server">


<ItemTemplate>
<%#Container.DataItem%>
</ItemTemplate>
</asp:DataList>

VB.NET

Dim ds As New DataSet


Dim myda As SqlDataAdapter = New SqlDataAdapter("GetSuppliers",
"server=localhost;database=Northwind;uid=sa;pwd=;")
myda.SelectCommand.CommandType = CommandType.StoredProcedure

107
myda.Fill(ds, "Table")
Dim slist As SortedList = New SortedList
Dim dr As DataRow
For Each dr In ds.Tables(0).Rows
If Not slist.ContainsValue(dr("Country")) Then
slist.Add(dr("Supplierid"), dr("Country"))
End If
Next
DataList1.DataSource = slist.GetValueList
DataList1.DataBind()
'In case of Dropdownlist
'DropDownList1.DataSource = slist.GetValueList
'DropDownList1.DataBind()

C#

DataSet ds = new DataSet();


SqlDataAdapter myda = new SqlDataAdapter("GetSuppliers",
"server=localhost;database=Northwind;uid=sa;pwd=;");
myda.SelectCommand.CommandType = CommandType.StoredProcedure;
myda.Fill(ds, "Table");
SortedList slist = new SortedList();

foreach( DataRow dr in ds.Tables[0].Rows)


{
if (! slist.ContainsValue(dr["Country"]))
{
slist.Add(dr["Supplierid"].ToString (), dr["Country"].ToString ());
}
}
DataList1.DataSource = slist.GetValueList();
DataList1.DataBind();
//In case of DropDownList
//DropDownList1.DataSource = slist.GetValueList
//DropDownList1.DataBind()

31.16 A field with bit data type value when displayed on a web page shows
true/ false how to display a bit value as 1/0?

VB.NET

'Using DataReader
While dr.Read()
Response.Write((dr("ProductName") + " "))
Response.Write((Convert.ToInt16(dr("discontinued")) + "
"))
End While

C#

//Using DataReader
while (dr.Read ())

108
{
Response.Write (dr["ProductName"] + " ");
Response.Write (Convert.ToInt16 ( dr["discontinued"]) + "
");
}

31.17 When I try to enter null value to DateTime field in database it is saved
as 1/1/1900 12:00:00 AM?

Refer When I try to enter null value for DataTime in Database I get error message "String was not recognized as a

valid DateTime" or "Value of type 'System.DBNull' cannot be converted to 'String'"

31.18 How to use Stored Procedures in ASP.NET?

Refer Store Procedure Sample

31.19 How to display multiple records using DataTable.Select?

Use namespace System.Data.OleDb VB.NET

Dim myConnection As New OleDbConnection("Provider=SQLOLEDB.1;Data


Source=localhost;database=northwind;User Id=sa;Password=;")
Dim myda As New OleDbDataAdapter("Select * from Orders", myConnection)
Dim ds = New DataSet
myda.Fill(ds, "table")

Dim dr() As DataRow


Dim id As String = "ROMEY" ' "Field with id ROMEY has more than one records found
Dim sel As String = "customerid='" + id + "'"
dr = ds.Tables(0).Select(sel)
Dim i As Integer
For i = 0 To (dr.GetUpperBound(0)) - 1
Response.Write((dr(i)("Orderid").ToString() + ControlChars.Tab + dr(i)("Customerid").ToString() + ControlChars.Tab
+ dr(i)("Freight").ToString() + "
"))
Next

C#

OleDbConnection myConnection = new OleDbConnection("Provider=SQLOLEDB.1;Data


Source=localhost;database=northwind;User Id=sa;Password=;");
OleDbDataAdapter myda= new OleDbDataAdapter ("Select * from Orders", myConnection);
System.Data.DataSet ds= new DataSet ();
myda.Fill (ds,"table");

DataRow[] dr ;
string id ="ROMEY";// "Field with id ROMEY has more than one records found
string sel ="customerid='"+ id + "'";
dr = ds.Tables [0].Select (sel);
int i;

109
for(i=0;i
{
Response.Write (dr[i]["Orderid"].ToString() + "\t" +
dr[i]["Customerid"].ToString() + "\t" + dr[i]["Freight"].ToString () +
"
");
}

31.20 How to get the count of items in a dataReader?

VB.NET

Dim mycn As New SqlConnection("server=localhost;uid=sa;password=;database=northwind;")


Dim mycmd As New SqlCommand("Select * from Products", mycn)
mycn.Open()
Dim dr As SqlDataReader = mycmd.ExecuteReader
Dim i As Integer
While dr.Read
i += 1
End While
Response.Write("Count of Records : " & i)

C#

SqlConnection mycn =new SqlConnection("server=localhost;uid=sa;password=;database=northwind;");


SqlCommand mycmd = new SqlCommand ("Select * from Products", mycn);
mycn.Open();
SqlDataReader dr = mycmd.ExecuteReader();
int i=0;
while(dr.Read())
{
i+=1;
}
Response.Write("Count of Records : " + i.ToString());

31.21 How to check EOF with SqlDataReader?

If you are using the Framework 1.1 , use HasRows

For Framework < 1.1

VB.NET

Dim myconnection As SqlConnection


Dim mycmd As SqlCommand
Dim strSql As String
Dim myReader As SqlDataReader

myconnection = New SqlConnection("Server=localhost;uid=sa;password=;database=northwind;")

110
strSql = "Select count(*) from employees;Select * from employees"
mycmd = New SqlCommand(strSql, myconnection)
myconnection.Open()
Dim count As Integer = CInt(mycmd.ExecuteScalar())
myReader = mycmd.ExecuteReader(CommandBehavior.CloseConnection)
If count = 0 Then
Response.Write("No records found")
Else
myReader.NextResult()
While myReader.Read()
Response.Write(myReader("Employeeid").ToString() + "<BR>")
End While
End If

C#

SqlConnection myconnection ;
SqlCommand mycmd ;
string strSql ;
SqlDataReader myReader ;

myconnection = new SqlConnection("Server=localhost;uid=sa;password=;database=northwind;");


strSql = "Select count(*) from employees;Select * from employees";
mycmd = new SqlCommand(strSql, myconnection);
myconnection.Open();
int count=(int) mycmd.ExecuteScalar() ;
myReader = mycmd.ExecuteReader(CommandBehavior.CloseConnection);
if (count==0 )
{
Response.Write("No records found");
}
else
{
myReader.NextResult ();
while(myReader.Read ())
{
Response.Write(myReader["Employeeid"].ToString () + "<br>");
}
}

31.22 How to filter xml data and display data in the DataGrid?

<?xml version="1.0" encoding="utf-8" ?>


<products>
<product prodId="product1-00" param1="11" />
<product prodId="product1-00" param1="12" />
<product prodId="product1-01" param1="13" />
<product prodId="product1-02" param1="14" />
<product prodId="product2-00" param1="21" param2="22" />
<product prodId="product2-00" param1="31" param2="32" />
<product prodId="product2-01" param1="41" param2="42" />
</products>

111
VB.NET

Dim ds As New DataSet


ds.ReadXml(Server.MapPath("data1.xml"))
Dim dv As New DataView
dv = ds.Tables(0).DefaultView
dv.RowFilter = "prodId='product2-00'"
Me.DataGrid1.DataSource = dv
Me.DataBind()

C#

DataSet ds = new DataSet();


ds.ReadXml(Server.MapPath("data1.xml"));
DataView dv = new DataView();
dv = ds.Tables[0].DefaultView;
dv.RowFilter = "prodId='product2-00'";
this.DataGrid1.DataSource = dv;
this.DataBind();

31.23 Why do I get the error message "ExecuteReader requires an open and
available Connection. The connection's current state is Closed"?

This error is caused if you have not opened the connection.

Before you read the data using DataReader open the Connection

31.24 Why do I get the error message "The ConnectionString property has
not been initialized"?

Check if you have specified the connection string

VB.NET

dim cn as new SqlConnection("<your connection string>")


'dim cn as new OleDdConnection("<your connection string>")

C#

SqlConnection cn = new SqlConnection("<your connection string>");


OleDbConnection cn = new OleDbConnection("<your connection string>");

31.25 I get the error message "Keyword not supported: 'provider'", when

112
using Sql Server why?

If you are using SqlConnection then the connection string should be as follows:

server=localhost;uid=sa;password=;database=northwind
i.e
server=<yourservername>;uid=<youruid>;password=<yourpassword>;database=<yourdbName>"

For SqlConnection we do not provide a Provider . Provider is used in cases where OleDbConnection is used.

31.26 Why do I get the error message "ExecuteReader: Connection property


has not been initialized"?

This error is caused if there is no Connection object associated with the Command Object. To resolve this

VB.NET

Dim cn as new SqlConnection("<your connection string>")


'Dim cn as new OleDbConnection("<your connection string>")
Dim cmd As new SqlCommand("Select * from Products", cn)
'Dim cmd As new OleDbCommand("Select * from Products", cn)

C#

SqlConnection cn = new SqlConnection ("<your connection string>");


'OleDbConnection cn = new OleDbConnection ("<your connection string>");
SqlCommand cmd = new SqlCommand ("Select * from Products", cn);
'OleDbCommand cmd = new OleDbCommand ("Select * from Products", cn);

31.27 Why do I get the error message "There is already an open DataReader
associated with this Connection which must be closed first."?

This is caused if you are attempting to use the same DataReader more than once in your code without closing the

previous Datareader. Or you might have a DataReader open on the same connection as the DataAdapter/Command

uses. So it is not recommended to share a connection between a DataReader and a DataAdapter/Command

• Either close the first connection or,

• if you must keep it open as you are executing another reader from within it, use another connection object.

31.28 I get the error message "Cast from type DBNull to type String is not
valid." when I try to display DataReader values on form?

113
Try VB.NET

txtCountry.Text = dr("FieldName").ToString()

C#

txtCountry.Text = dr["FieldName"].ToString();

or Try

VB.NET

If dbReader("fieldname").ToString= DBnull.Value.ToString()
'Empty field value
Else
'Display value
End if

C#

if (dbReader["fieldname").ToString() == DBNull.Value.ToString() )
{
//Empty field value
}
else
{
//display Value
}

31.29 What is the significance of CommandBehavior.CloseConnection?

To avoid having to explicitly close the connection associated with the command used to create either a

SqlDataReader or and OleDbDataReader, pass the CommandBehavior.CloseConnection argument to the

ExecuteReader method of the Connection. i.e

VB.NET

dr= cmd.ExecuteReader(CommandBehavior.CloseConnection)

C#

114
dr= cmd.ExecuteReader(CommandBehavior.CloseConnection);

The associated connection will be closed automatically when the Close method of the Datareader is called. This

makes it all the more important to always remember to call Close on your datareaders.

31.30 How to maintain Line feeds when saving data to a database?

Save the data entered in the multiline textbox as

VB.NET

..
cmd.Parameters.Add(new SqlParameter("@Notes" ,SqlDbType.NVarChar ))
cmd.Parameters ("@Notes").Value ="<pre>" + TextBox1.Text + "</pre>"
....
cn.Open()
cmd.ExecuteNonQuery()

C#

...
cmd.Parameters.Add(new SqlParameter("@Notes" ,SqlDbType.NVarChar ));
cmd.Parameters ["@Notes"].Value ="<pre>" + TextBox1.Text + "</pre>";
....
cn.Open();
cmd.ExecuteNonQuery();

To retrieve the Data

VB.NET

Response.Write (ds.Tables(0).Rows(0)("Notes").ToString ())

C#

Response.Write (ds.Tables[0].Rows[0]["Notes"].ToString ());

31.31 How to use the Same DataReader to populate two different ListBoxes?

You cannot use the same DataReader to populate 2 Listboxes.But can try out the below workaround

VB.NET

115
...
cn = New SqlConnection("Server=localhost;uid=sa;database=northwind;pwd=")
cmd = New SqlCommand("select * from products;select * from products", cn)
cn.Open()
dr = cmd.ExecuteReader()
ListBox1.DataSource = dr
ListBox1.DataTextField = "productname"
ListBox1.DataBind()
dr.NextResult()
ListBox2.DataSource = dr
ListBox2.DataTextField = "productname"
ListBox2.DataBind()

C#

...
cn = new SqlConnection("Server=localhost;uid=sa;database=northwind;pwd=");
cmd= new SqlCommand ("select * from products;select * from products", cn);
cn.Open();
dr = cmd.ExecuteReader();
ListBox1.DataSource = dr;
ListBox1.DataTextField = "productname";
ListBox1.DataBind();
dr.NextResult();
ListBox2.DataSource = dr;
ListBox2.DataTextField = "productname";
ListBox2.DataBind();

31.32 How to resolve the error message "Cannot implicitly convert type
'string' to 'System.DateTime' " when using a DataReader?

Try

VB.NET

dim dt as DateTime = ctype( dr("hiredate").ToString(), DateTime)

C#

DateTime dt= ((DateTime) dr["hiredate"]).ToString();

31.33 Why do I get the error message "Value cannot be null. Parameter
name: dataSet "?

The cause of this error may be that you have declared a dataset but have not written the following statement

116
VB.NET

ds= new DataSet()

C#

ds= new DataSet();

31.34 Why do I get the error message "The SelectCommand property has not
been initialized before calling 'Fill'. "?

You have to supply the Sql Statement or Stored Procedure for the DataAdapter as

VB.NET

da.SelectCommand.CommandText = "Select * from "

or

da = new SqlDataAdapter ("Select * from ", cn)

C#

da.SelectCommand.CommandText ="Select * from ";

or

da = new SqlDataAdapter ("Select * from ", cn);

31.35 How to use OleDb DataSet?

Use namespace System.Data.OleDb

VB.NET

Dim strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("nwind.mdb") & ";"


Dim strsql As String = "Select * from Customers"

117
Dim cn As New OleDbConnection(strConn)
Dim ds As DataSet = New DataSet()
Dim da As New OleDbDataAdapter(strsql, cn)
da.Fill(ds, "T1")
DataGrid1.DataSource = ds
DataGrid1.DataBind()

C#

string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("nwind.mdb") + ";";


string strsql = "Select * from Customers";
OleDbConnection cn = new OleDbConnection(strConn);
DataSet ds = new DataSet();
OleDbDataAdapter da = new OleDbDataAdapter(strsql, cn);
da.Fill(ds, "T1");
DataGrid1.DataSource = ds;
DataGrid1.DataBind();

31.36 How to use OleDb DataReader?

VB.NET

Dim strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("nwind.mdb") & ";"


Dim strsql As String = "Select * from Customers"
Dim cn As New OleDbConnection(strConn)
Dim cmd As New OleDbCommand(strsql, cn)
cn.Open()
Dim dr As OleDbDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection)
DataGrid1.DataSource = dr
DataGrid1.DataBind()

C#

string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("nwind.mdb") + ";";


string strsql = "Select * from Customers";
OleDbConnection cn = new OleDbConnection(strConn);
OleDbCommand cmd = new OleDbCommand (strsql, cn);
cn.Open ();
OleDbDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection );
DataGrid1.DataSource = dr;
DataGrid1.DataBind();

31.37 How to loop through a Dataset to display all records?

VB.NET

118
'Fill Dataset
Dim dc As DataColumn
Dim dr As DataRow
For Each dr In ds.Tables(0).Rows
For Each dc In ds.Tables(0).Columns
Response.Write(dr(dc.ColumnName).ToString())
Next
Next

C#

//Fill the DataSet


foreach (DataRow dr in ds.Tables[0].Rows)
{
foreach( DataColumn dc in ds.Tables[0].Columns)
{
Response.Write(dr[dc.ColumnName].ToString());
}
}

17. Sessions

32.1 How to print out all the variables in the Session?

VB.NET

Dim strKey as string


For Each strKey In Session.Keys
Response.Write(strKey + " : " + Session(strKey).ToString() + "<br>")
Next

C#

foreach (string strKey in Session.Keys)


{
Response.Write(strKey + " : " + Session[strKey].ToString() + "<br>");
}

32.2 Why isn't session state available?

• - First, check your web.config, machine.config and your page directive to make sure you have enabled

session state. Reference:

o Session State

119
o @ Page

• - session state is not available just everywhere, anytime. It is available only after the

HttpApplication.AcquireRequestState event is called. For example, it is NOT available in the

Application_OnAuthenticateRequest handler inside global.asax. For details, see: Handling Public Events

• - Lastly, make sure System.Web.SessionState.SessionStateModule is included the in your config files. A

common case is that SharePoint application will remove this module from their web.config files (for

performance reason), and thus session state isn't available.

32.3 Can I share session state between ASP.NET and ASP pages?

No. This MSDN article shows how to work around it: How to Share Session State Between Classic ASP and ASP.NET

32.4 Can I share session state between web applications (i.e. "virtual
directories" or "applications" in IIS)?

No.

32.5 What is the difference between Session.Abandon() and Session.Clear()?

The major difference is that if you call Session.Abandon(), Session_End will be fired (for InProc mode), and in the

next request, Session_Start will be fired. Session.Clear( ) just clears the session data without killing it.

32.6 The SessionID remains the same even after the Session times out or
Session abandons?

The SessionID lasts as long as the browser session lasts even though the session state expires after the indicated

timeout period i.e the same session ID can represent multiple sessions over time where the instance of the browser

remain the same.

32.7 Why are my Session variables lost frequently when using InProc mode?

This can be due to application recycle.

See PRB: Session variables are lost intermittently in ASP.NET applications

In v1, there is also a bug that will cause worker process to restart. It's fixed in SP2 and v1.1. See FIX: ASP.NET

Worker Process (Aspnet_wp.exe) Is Recycled Unexpectedly.

32.8 Does session state have a locking mechanism that serialize the access to

120
state?

Session state implements a reader/writer locking mechanism:

• A page (or frame) that has session state write access (e.g. <%@ Page EnableSessionState="True" %>) will

hold a writer lock on the session until the request finishes.

• A page (or frame) that has session state read access (e.g. <%@ Page EnableSessionState="ReadOnly"

%>) will hold a reader lock on the session until the request finishes.

• Reader lock will block a writer lock; Reader lock will NOT block reader lock; Writer lock will block all reader

and writer lock.

• That's why if two frames both have session state write access, one frame has to wait for the other to finish

first

32.9 Response.Redirect and Server.Transfer is not working in Session_End?

Session_End is fired internally by the server, based on an internal timer. And thus there is no HttpRequest associted

when that happens. That is why Response.Redirect or Server.Transfer does not make sense and will not work.

32.10 Is the session Timeout attribute a sliding timeout value?

The session Timeout is a sliding expiration time, meaning whatever your page access session state, the expiration

time will be moved forward. Note that as long as a page has NOT disabled session state, it will access the session

automatically when requested.

32.11 I am writing my own HttpHandler. Why is session state not working?

Your HttpHandler has to implement the "marker" interface IRequiresSessionState or IReadOnlySessionState in order

to use session state.

32.12 Why isn't Session available in my event handlers in global.asax?

It depends on which event you're handling. Session is available only after AcquireRequestState event

32.13 When I use the Session in component class as Session("CustID"), I get


error message "Session is not declared". Why?

Use HttpContext.Current.Session i.e

121
VB.NET

HttpContext.Current.Session("CustID") = "1"

C#

HttpContext.Current.Session["CustID"] = "1";

32.14 When I create a Session variable if I'm using inproc, where is the
session variable stored?

• In II5, it's stored in the memory of aspnet_wp.exe.

• For IIS6, by default all apps will share the same application pool, i.e. the session state is stored in the

memory of the process w3wp.exe. They are NOT separated per application, but instead per application pool

(w3wp.exe)

32.15 Is the session timeout attribute in minutes or seconds?

The Timeout setting is in minutes, not in seconds. i.e The timeout attribute specifies the number of minutes a

session can be idle before it is abandoned. The default is 20

32.16 Will my session state be saved when my page hit an error? Will my
session state be saved when my page hit an error? In Session_End, I tried to
do some cleanup job using SQL but it failed. Why?

1. Session_End is supported only in InProc mode.

2. Session_End is run using the account which runs the worker process (aspnet_wp.exe), which can be

specified in machine.config. Therefore, in your Session_End, if you connect to SQL using integrated

security, it will use that worker process account credential to connect, and may fail depending on your SQL

security settings.

32.17 Why do I lose my Session variables on redirect when I set "cookieless"


to true?

When using cookieless, you must use relative path (e.g. ..\webform1.aspx) instead of absolute path (e.g.

122
\dir1\subdir1\webform1.aspx). If you use absolute path, ASP.NET cannot preserve your session ID in the URL.

32.18 How to store SortedList in Session or Cache?

VB.NET

Dim x As New SortedList()


x.Add("Key1", "ValueA")
x.Add("Key2", "ValueB")

To store in Session:

Session("SortedList1") = x

and to retrieve

Dim y As SortedList = CType(Session("SortedList1"), SortedList)

C#

SortedList x = new SortedList();


x.Add("Key1", "ValueA");
x.Add("Key2", "ValueB");

To store in Session:

Session["SortedList1"] = x;

and to retrieve

SortedList y = (SortedList) Session["SortedList1"];

32.19 Why do I get the error message "Session state can only be used when
enableSessionState is set to true, either in a configuration file or in the Page
directive"?

This problem may occur after you install Windows Sharepoint Server(WSS) on a server that has Microsoft Visual

123
Studio .NET 2003 installed. The WSS ISAPI filter handles all incoming URLs. When you browse one of the ASP.NET

Web application virtual directories, the ISAPI filter does not locate the URL path of the folder.

To resolve this refer Session state cannot be used in ASP.NET with Windows SharePoint Services

32.20 How to remove a Session variable?

Use HttpSessionState.Remove()

32.21 Is there any way to know how much memory is being used by session
variables in my application?

No

32.22 I have a frameset page which has an HTM extension, and I found out
that each frame it contains displays a different session id on the first request.
Why?

The reason is that your frameset page is an HTM file instead of an ASPX file.

In normal a scenario, if the frameset is an aspx file, when you request the page, it will first send the request to the

web server, receive an asp.net session cookie (which holds the session id), and then the browser will send individual

requests for the frames, and each request will carry the same session id.

However, since your frameset page is an htm file, the first request comes back without any session cookie because

the page was serviced by ASP and not ASP.NET. Then again your browser sends out individual requests for each

frame. But this time each individual request will NOT carry any session id, and so each individual frame will create

its own new session. That's why you will see different session ids in each frame. The last request that comes back

will win by overwriting the cookie written by the previous two requests. If you do a refresh, you will see them having

the same session id.

This behavior is by-design, and the simple solution is to change your frameset page to .aspx.

32.23 Can different apps store their session state in different databases on
the same SQL server?

Yes. Refer FIX: Using one SQL database for all applications for SQL Server session state may cause a bottleneck

32.24 Do I have a valid HttpSessionState object and HttpContext object in


Session_End?

You will have the HttpSessionState object available. Just use 'Session' to access it.

For HttpContext, it is not available because this event is not associated with any request.

124
32.25 Why aren't my sessions expiring, I am using SQLServer mode?

In SQLServer mode, session expiration is carried out by the SQL Agent using a registered job. Make sure your SQL

Agent is running.

32.26 I set EnableSessionState to "ReadOnly", but in InProc mode I can still


modify the session. Why is that?

Even those enableSessionState is marked as ReadOnly, but in InProc state, the user can still modify the session. The

only difference is that the session will not be locked during the request. This limitation is by-design

32.27 How can I avoid specifying a plain password for my sql connection?

Include a sql trusted connection, or put the connection string as encrypted data in the registry. Refer

• FIX: Stronger Credentials for processModel, identity, and sessionState

• How To Use the ASP.NET Utility to Encrypt Credentials and Session State Connection Strings

32.28 How can I use Session variables in a class?

Use HttpContext.Current.Session

VB.NET

HttpContext.Current.Session("Value1") = "1"

C#

HttpContext.Current.Session["Value1"] = "1";

In similar manner you can use Application Variables too.

32.29 What kind of objects can I store in a Session State?

Depends on which mode you are using:

125
• InProc Mode- objects stored in session state are actually live objects, and so you can store whatever object

you have created.

• State Server or SQL Server mode, objects in the session state will be serialized and deserialized when a

request is processed. So make sure your objects are serializable and their classes must be marked as so. If

not, the session state will not be saved successfully. In v1, there is a bug which makes the problem happen

unnoticed in SQLServer mode and will make your request hang. The hanging problem is fixed in v1.1. The

fix for KB 324479: ASP.NET SQL Server Session State Impersonation Is Lost Under Load also contains the

fix for this problem. The problem will be fixed in v1 SP3 too.

For more info: BUG: Session Data Is Not Saved in Out-of-Process Session State

32.30 Why did my request hang after I switch to SQLServer mode?

(Right answer?) Refer What kind of objects can I store in Session State?

32.31 What are the disadvantages of setting cookieless to true?

Setting Cookieless=true implies some restrictions, mainly:

1. You cannot use absolute link in your pages.

2. You have to perform additional steps to switch between http and https pages in your application.

3. If your customer sends a link to a friend, the URL will contain the session ID and both users could be using

the same session ID at the same time.

32.32 Can I store my session state in a database other than tempdb, In


SqlServer mode?

Yes. For more details Refer HOW TO: Configure ASP.NET for Persistent SQL Server Session State Management

126

S-ar putea să vă placă și