Documente Academic
Documente Profesional
Documente Cultură
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.
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
VB.NET
C#
1
public string source
{
get
{
return ImageButton1.ImageUrl;
}
set
{
ImageButton1.ImageUrl = value;
}
}
Drag and drop User Control and set the source property.
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
C#
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.
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(...)
<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
VB.NET
C#
6.8 How to change the imageurl of the image control that exists in a
usercontrol?
In the .ascx:
In .aspx
VB.NET
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.
• Windows authentication and are browsing an ASP.NET page from server -- ASP.NET/IIS would automatically
• 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).
<authorization>
<deny users="?"/>
</authorization>
<identity impersonate="true"/>
• 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
• Passport : Centralized authentication service provided by Microsoft that offers a single logon and core
<authentication
mode= " [ Windows | Forms | Passport | None ] ">
</authentication>
9.5 How to determine the Windows User from a Web form Application?
VB.NET
C#
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.
6
3. In the right pane, double-click Impersonate a client after authentication.
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"....
The RegisterStartupScript method emits the script just before the closing tag of the Page object's <form runat=
server> element.
VB.NET
C#
Alternatively, use the RegisterClientScriptBlock method which emits the client-side script just after the opening
11.2 How to open a new Window using javascript function from a Link
button?
VB.NET
C#
7
link.Attributes[ "onClick" ] = "window.open( 'url', 'name', 'properties' )";
Here is a JavaScript Quick Reference Guide in Poster Format that you can print out and refer easily. Covers the older
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").
C#
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
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
C#
VB.NET
if Page.Request.Browser.JavaScript then
...
else
...
end if
C#
if (Page.Request.Browser.JavaScript )
{
...
}
else
{
...
}
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?
VB.NET
C#
<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
C#
All Objects in JavaScript implicitly support hash table like syntax by virtue of behaving as Associative Arrays.
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
12
</body>
document.getElementById("<id>").style.visibility="hidden";
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.
<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>
<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
<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();");
VB.NET
C#
15
11.25 How to disable a Dropdownlist once someone has selected an item in
the Dropdownlist?
VB.NET
DropDownList1.Attributes.Add("onChange","this.disabled=true;" )
C#
DropDownList1.Attributes.Add("onChange","this.disabled=true;" );
<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
16
C#
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
• Make sure to add a ListItem with Text="Please Choose" and Value ="".
11.29 Are there any resources regarding the Mozilla specific Browser Objects
and CSS information?
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
C#
12.2 How to read data from an XML file and display it in a DataGrid?
VB.NET
C#
12.3 How to read data from the XML file using FileStream and display it in a
DataGrid?
18
VB.NET
C#
VB.NET
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;
RadioButton control is designed to allow users to choose atleast one option from a list of available options.
19
21.3 How can I enforce that only one radiobutton gets selected among a list
of 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>");
}
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();");
VB.NET
20
C#
HyperLink hpl = new HyperLink();
hpl.Text="Text";
hpl.NavigateUrl="http://www.syncfusion.com";
hpl.ID="theID";
Page.Controls[1].Controls.Add(hpl);
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"
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";
VB.NET
C#
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
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.
to In VB.NET
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.
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
TextBox1.ApplyStyle(textboxStyle)
Button1.ApplyStyle(buttonStyle)
CheckBox1.ApplyStyle(checkboxStyle)
C#
Create a function
24
s.BackColor =_backcolor;
s.Font.Bold = _fontbold;
return s;
}
In Page_Load
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
For solution refer PRB: Access Denied Error When You Make Code Modifications with Index Services Running
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);
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'");
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
C#
27
if (!Page.IsPostBack )
{
Button1.Style.Add("LEFT", "1px");
}
}
22.17 How can I set the maximum and minimum value for RangeValidator
based on two dates?
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();
VB.NET
28
Image1.Attributes.Add("hspace", "50")
Image1.Attributes.Add("vspace", "50")
C#
Image1.Attributes.Add("hspace", "50") ;
Image1.Attributes.Add("vspace", "50") ;
VB.NET
C#
VB.NET
29
End If
Next
Return arrList
End Function 'GetControls
'In Page_Load
DataBind()
C#
//In Page_Load
DataBind();
VB.NET
C#
You can set the EnableViewState property of the control. You should disable viewstate for any control that doesn't
30
23.1 How to create a table control dynamically to populate data?
VB.NET
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);
}
31
Set style property for the table cell as
style="WORD-BREAK:break-all"
VB.NET
C#
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
12. DataGrid
Set the Dataformatstring of the boundcolumn to {0:Nn} where n=> number of decimal points For more details refer
Format Function
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,
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?
VB.NET
C#
25.6 How to display only date part in the Datagrid if the Date is of DateTime
34
datatype in the database?
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.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.
VB.NET
35
End If
End Sub
C#
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?
VB.NET
Dim cn As SqlConnection
Dim cmd As SqlCommand
Dim rdr As SqlDataReader
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();
}
}
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?
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
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.
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));
}
}
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
C#
if (!Page.IsPostBack)
{
'Your databinding code
}
39
25.18 How to add a mailto link inside a datagrid?
VB.NET
C#
40
{
BindDataGrid(e.SortExpression.ToString());
}
VB.NET
Sub Binddata()
'Populate the DataGrid using DataSet
End Sub
C#
41
}
void Binddata()
{
//Populate the DataGrid using DataSet
}
...
<asp:TemplateColumn>
<ItemTemplate>
<img src='<%#DataBinder.Eval (Container.DataItem, "Photo")%>'>
</ItemTemplate>
</asp:TemplateColumn>
...
Try
VB.NET
C# C#
BoundColumn bc = (BoundColumn)this.DataGrid1.Columns[1];
Response.Write(bc.DataField);
42
VB.NET
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
C#
string sqlStmt ;
string conString ;
SqlConnection cn =null;
SqlDataAdapter da =null;
DataSet ds;
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 ();
}
VB.NET
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
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();
}
45
{
ViewState["SortOrder"] = " DESC";
}
else
{
ViewState["SortOrder"] = " ASC";
}
SQLStmt = SQLStmt + " ORDER BY " + e.SortExpression.ToString () + " " + ViewState["SortOrder"];
binddata();
}
VB.NET
C#
46
25.26 How to add a TemplateColumn dynamically to the datagrid?
VB.NET
Create class
C#
Create class
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;
}
}
48
VB.NET
Sub BindGrid()
'Bind the Datagrid with dataSet
End Sub 'BindGrid
C#
49
{
// Put user code to initialize the page here
if (!Page.IsPostBack )
{
BindGrid();
}
}
void BindGrid()
{
//Bind the DataGrid with dataset
}
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];
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
VB.NET
C#
51
if(! Page.IsPostBack )
{
BindDataGrid("ProductId");
}
}
VB.NET
C#
52
e.Item.Cells[dc.IndexOf(dc["field_name"])].Visible = false;
VB.NET
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}");
}
<EditItemTemplate>
<asp:TextBox runat="server" id="txtField" MaxLength='<%# DataBinder.Eval(Container.DataItem, "FieldSize") %>'
/>
</EditItemTemplate>
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
VB.NET
C#
<script>
function confirmmsg()
{
if (confirm("Do you want to delete record?")==true)
return true;
else
return false;
}
</script>
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
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
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 ();
}
25.37 How to hide and show a Column based on the authenticated user?
56
VB.NET
C#
if ( ! User.Identity.IsAuthenticated )
{
e.Item.Cells[1].Visible =false;
}
Step 1: Display the Data in the Datagrid Initially the Datagrid is populated with the records in the db The field
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
o and OnPreRender property does the task of setting the value from the db to the dropdownlist
<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>
58
End Sub 'SetDropDownIndex
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();
}
}
60
ed.SelectedIndex = ed.Items.IndexOf(ed.Items.FindByText(strDiscontinued));
}
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 ();
}
}
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?
Code behind
VB.NET
C#
62
{
count = count + 1;
return count;
}
Method 2 : Dynamically change the HeaderText in the ItemDataBound Event of the DataGrid
VB.NET
C#
63
private void Page_Load(object sender, System.EventArgs e)
{
//Populate the DataGrid
}
25.42 How to select a record in the datagrid and start editing/updating the
record using textboxes?
VB.NET
Dim cn As SqlConnection
Dim da As SqlDataAdapter
Dim cmd As SqlCommand
Dim strsql As String
Dim ds As DataSet
Sub BindData()
DataGrid1.DataSource = GetData("Select * from Region")
DataGrid1.DataBind()
64
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;
}
25.43 How can I show what page the user is on using in-built paging
functionality. CurrentPageIndex Property Shows Up as 0?
66
VB.NET
C#
VB.NET
C#
67
if( e.Item.Cells[1].Text == " ")
{
e.Item.Cells[1].Text = "No data";
}
}
}
25.45 How to change the value of a field before it gets displayed in the
datagrid?
VB.NET
C#
68
break;
default :
e.Item.Cells[3].Text = e.Item.Cells[3].Text;
break;
}
}
}
VB.NET
C#
69
}
VB.NET
Dim cn As SqlConnection
Dim da As SqlDataAdapter
Dim ds As DataSet
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 ();
}
}
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
25.49 How to display the checkbox checked or unchecked for a bit data type
value in the DataBase?
71
</asp:DataGrid>
• 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
• Step 3: To handle the Paging , In the ItemCommand Event respond to action based on the CommandName
VB.NET
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
C#
73
{
DataGrid1.DataSource =ds;
DataGrid1.DataBind ();
}
}
25.51 How to enable or disable the button in the DataGrid based on a bit
value in the database?
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#
VB.NET
Dim cn As SqlConnection
Dim da As SqlDataAdapter
Dim ds As 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;
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");
76
25.53 How can I fix error message "Invalid CurrentPageIndex value. It must
be >= 0 and < the PageCount"?
• 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
}
VB.NET
77
Dim strConn, strSQL As String
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
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 ();
}
79
25.55 How to delete a record using DataGrid?
VB.NET
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
80
End Sub 'DataGrid1_Delete
C#
SqlConnection mycn;
SqlDataAdapter myda;
DataSet ds;
string strConn,strSQL;
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 ();
}
81
25.56 How to use a HyperlinkColumn for a DataGrid?
VB.NET
C#
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
C#
VB.NET
83
C#
25.60 How do I change the width of the Textboxes created for edit-mode of a
Datagrid?
25.61 How to display a Tooltip when hovering over the Header sort link of the
DataGrid?
C#
84
25.62 How to right align cells in the Datagrid when using BoundColumn?
25.63 How to hide a row in a DataGrid if one of the Column value is zero?
VB.NET
C#
Don't specify the SortExpression for the BoundColumn for which you do not want Sorting. This will only work if you
You probably declared the event handler for OnPageIndexChanged event incorrectly. Make sure that the event
85
<asp:DataGrid id="DataGrid1" runat="server"... OnPageIndexChanged="<EventName>".../>
VB.NET
C#
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.
VB.NET
C#
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?
VB.NET
DataGrid1.DataSource = Nothing
DataGrid1.DataBind()
87
C#
DataGrid1.DataSource = null;
DataGrid1.DataBind();
VB.NET
C#
88
25.72 How to display "No data exists" within the datagrid rather than just
showing Column Headers with no rows?
VB.NET
C#
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;
VB.NET
C#
90
VB.NET
DataGrid1.DataSource = ds
DataGrid1.DataBind()
C#
DataGrid1.DataSource = ds;
DataGrid1.DataBind();
VB.NET
C#
91
}
VB.NET
C#
92
<ItemTemplate>
<asp:Label text=<%#DataBinder.Eval(Container.DataItem , "Productid")%> ID="lbl1" Runat=server
></asp:Label>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
VB.NET
C#
25.78 How to display the total of a particular column at the footer of the
DataGrid?
VB.NET
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
}
}
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>
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
C#
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?
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.
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
VB.NET
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#
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);
// 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"
The assembly will not be strong named in the above tag if it's not in the GAC.
<appSettings>
<add key="MyDBConnection" value="server=<ServerName>;uid=<Username>;pwd=;database=<DBName>" />
</appSettings>
Example :
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 ;
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
}
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
C#
VB.NET
C#
100
else
{
return strNotes;
}
}
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
}
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?
<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
102
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) ;
}
}
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) ;
}
}
<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
C#
104
if(!Page.IsPostBack )
{
//...
}
On Button Click
VB.NET
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
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);
}
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
Stored Procedure
VB.NET
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#
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
C#
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 () +
"
");
}
VB.NET
C#
VB.NET
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 ;
31.22 How to filter xml data and display data in the DataGrid?
111
VB.NET
C#
31.23 Why do I get the error message "ExecuteReader requires an open and
available Connection. The connection's current state is Closed"?
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"?
VB.NET
C#
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.
This error is caused if there is no Connection object associated with the Command Object. To resolve this
VB.NET
C#
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
• 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
}
To avoid having to explicitly close the connection associated with the command used to create either a
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.
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();
VB.NET
C#
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
C#
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
C#
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
or
C#
or
VB.NET
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#
VB.NET
C#
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#
17. Sessions
VB.NET
C#
• - First, check your web.config, machine.config and your page directive to make sure you have enabled
o Session State
119
o @ Page
• - session state is not available just everywhere, anytime. It is available only after the
Application_OnAuthenticateRequest handler inside global.asax. For details, see: Handling Public Events
common case is that SharePoint application will remove this module from their web.config files (for
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.
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
32.7 Why are my Session variables lost frequently when using InProc mode?
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
32.8 Does session state have a locking mechanism that serialize the access to
120
state?
• A page (or frame) that has session state write access (e.g. <%@ Page EnableSessionState="True" %>) will
• 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
• That's why if two frames both have session state write access, one frame has to wait for the other to finish
first
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.
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
Your HttpHandler has to implement the "marker" interface IRequiresSessionState or IReadOnlySessionState in order
It depends on which event you're handling. Session is available only after AcquireRequestState event
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?
• 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)
The Timeout setting is in minutes, not in seconds. i.e The timeout attribute specifies the number of minutes a
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?
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.
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.
VB.NET
To store in Session:
Session("SortedList1") = x
and to retrieve
C#
To store in Session:
Session["SortedList1"] = x;
and to retrieve
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
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
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
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.
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
• How To Use the ASP.NET Utility to Encrypt Credentials and Session State Connection Strings
Use HttpContext.Current.Session
VB.NET
HttpContext.Current.Session("Value1") = "1"
C#
HttpContext.Current.Session["Value1"] = "1";
125
• InProc Mode- objects stored in session state are actually live objects, and so you can store whatever object
• 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
(Right answer?) Refer What kind of objects can I store in Session State?
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
Yes. For more details Refer HOW TO: Configure ASP.NET for Persistent SQL Server Session State Management
126