|
|
Code Walkthroughs |
|
Datagrid
Formatting the Data
We are
able to format the content of the datagrid cell by one of two simple methods,
dependant upon whether the column is a bound column or whether it is a template
column. In our example we shall format the column to have to digits after the
decimal point , followed by a...
|
|
Datagrid
Highlight a Row With Click Through
It is
relatively easy to add alternating colours to the rows in your datagrid.
However, when we move the mouse over the rows we may want to highlight this
row, and possibly to add the option of a click through based on the row
selected...
|
|
Add
a Delete Button to a Datagrid
To add
a delete button to a datagrid follows a similar process to adding an edit
button. In the datagrid header...
|
|
Add
an Edit Button to a Datagrid
The
datagrid has a predefined editColumn for handling the editing of a datagrid.
Adding this simple column definition to a datagrid adds a powerful feature.
When a row is not in edit mode the column item shows the word...
|
|
Making
a Datagrid Row Editable
Two of
the most popular methods of editing a datagrid in asp.net are to either select
the row and take the user off to a different presentation of the data, or to
change the formatting of the row presented in the database with appropriate
edit text boxes, checkboxes and...
|
|
Adding
Tooltips to Datagrid Rows
Adding
tooltips to datagrid rows is easy, assuming that you have already created the
code for adding row highlighting. In this article I shall assume that you have
already read the article entitled Datagrid Highlight a Row With Click
Through...
|
|
Binding
a Datagrid to an Access Database
This
list covers the full lifecycle of a content management system, from initially
creating the content, through to delivering it to end users...
|
|
Adding
Data to a DropDownList
The aim
of this article is to answer the question 'How do I add items to a
DropDownList?' Initially as part of the declaration for the DropDownList we can
also define a number of items, much in the same way as in classic ASP...
|
|
Getting
Current Date Time
In
classic ASP we had now() which would return the current date and time. For
asp.net this no longer exists. So what should we use...
|
|
Test
if File Exists
Sometimes,
in order to reduce our chance of error, when working with the filesystem in
ASP.NET, we need to determine wether a file exists before performing an action
on it. The following short piece of code will enable us to test whether a file
exists...
|
|
Using
Javascript with ASP.NET Form Elements
Adding
simple pieces of Javascript to an Asp.net page can be acheived by adding to the
attributes of the particular imagebutton or linkbutton. if its normal ASP.Net
Button then you can...
|
|
Regular
Expressions
In the table below we list the characters used in .Net
regular expressions, together with their meaning, But first...
|
|
Authentication
in Asp.net
Forms
authentication in ASP.Net is far more easier and safe than Asp 3. It is
possible to place a web.config file in any directory of a web site.Therefore,
we are able to make most of a web site public, whilst providing authentication
on, say, one directory...
|
|
|
4.1 How to get the currently logged in user?
|

 |
|
To get the user ID of the user who is currently logged in, you would get it
using this: System.Web.HttpContext.Current.User.Identity.Name VB.NET
|
'Displays the currently logged in
user
|
Response.Write(User.Identity.Name.ToString())
|
//Displays the currently logged in
user
|
Response.Write(User.Identity.Name.ToString());
|
4.2 How to specify a line break in a Label's Text?
|

 |
|
Use the "<br>" tag to specify line breaks. For example:
VB.NET
|
Label1.Text = "<sometag1>" +
"<br>" + "<sometag1>"
|
Label1.Text = "<sometag1>" +
"<br>" + "<sometag1>";
|
4.3 How to convert a string to HTML format?
|

 |
|
Use namespace System.Web.HttpUtility
VB.NET
|
Dim mystring as string =”Tom &
Jerry”
|
Response.Write
(HttpUtility.HtmlDecode (mystring))
|
string mystring=”Tom & Jerry”;
|
Response.Write
(HttpUtility.HtmlDecode (mystring));
|
4.4 How do I determine if the user clicked a "Submit" button twice in the page?
|

 |
4.5 How to write date-time values of fields in a dataset into xml in a specific
format?
|

 |
4.6 What does "~" mean in ASP.NET applications?
|

 |
|
The tilde (~) in front of URLs means that these URLs point to the root of your
web application.
Web developers are familiar with using relative paths for all links, including
hyperlinks, images, and stylesheets, to be able to move around web pages
collectively.
In ASP.NET when using User controls the relative paths can be difficult to use.
The typical solution to this is to use web-root absolute paths instead here,
resulting in the hard-coded sub-directories that are common on ASP.NET sites.
The correct solution to this problem is to use app-relative paths instead, which
ASP.NET nicely makes possible through the use of the tilde (~) prefix. Instead
of <a href="/UC/Page.aspx">, use <a href="~/Page.aspx"
runat="server">. The same ~ notation works for images also, as long as you
add runat="server". There is also a ResolveUrl method that allows you to use ~
in your own code, which is one possible way to get stylesheet paths
app-relative. Refer
Tilde: Reference the Application Root
|
4.7 How can I reference simple DLL which contains one class but has no
namespace assigned to it in an .aspx page?
|

 |
|
You don't need a namespace to reference it; anything in the bin folder is
implicitly in the same namespace as the page being compiled. So if your class
looks like this:
|
public Function getTheName(byval
strval as string) as string
|
Response.Write(mc.getTheName)
|
MyClass1 mc = new MyClass1();
|
Response.Write(mc.getTheName);
|
4.8 How do I specify the Japanese locale for the controls in my Japanese
localized page?
|

 |
|
Just set the locale to Japanese in the Page directive.
i. e Set the Culture= "ja-JP" for the Page Directive.
-
ASP.NET pages support Culture and UICulture attributes to support independent
localized pages.
-
Controls on pages can pick the culture of the page and can render
culture-dependent content.
|
4.9 Why do some of the events on my page fire twice?
|

 |
|
This is probably because you explicitly subscribed to the events in code and
also specified the AutoEventWireUp
of Page to true (it's true by default). If so, the Page_Load, for example, will
be fired once for your event subscription and once because the Page subscribed
it for you (by looking for a specific event handler method signature).
To avoid this turn off AutoEventWireUp or remove your subscription code.
|
4.10 How to remove the spaces in a given string?
|

 |
|
Use the Namespace System.Text.RegularExpressions VB.NET
|
Dim strval As String = "Jack and
Jill"
|
Dim strnewval As String =
Regex.Replace(strval, " ", "")
|
Response.Write(strnewval)
|
string strval = "Jack and Jill";
|
string strnewval =
Regex.Replace(strval, " ", "");
|
Response.Write(strnewval) ;
|
4.11 I get the error System.__ComObject when using recordset?
|

 |
|
This error occurs if you are trying to fetch the recordset value as follows
|
|
To avoid this error try VB.NET
|
rs.Fields("productname").Value.ToString()
|
rs.Fields["productname").Value.ToString()
;
|
4.12 Why do I get error "A generic error occurred in GDI+." when trying to save
the bitmap file?
|

 |
|
May be the path of the file you are giving is wrong or you do not have write
permissions on the specific folder.
|
4.13 How can I force a Save As dialog box from an ASP.NET Web page.
|

 |
Response.AppendHeader("content-disposition",
"attachment; filename=document1.doc")
|
Response.ContentType = "text/plain"
|
Response.WriteFile(Server.MapPath("document1.doc"))
|
Response.AppendHeader("content-disposition",
"attachment; filename=document1.doc");
|
Response.ContentType = "text/plain";
|
Response.WriteFile(Server.MapPath("document1.doc"));
|
4.14 In ASP.NET is there a control similar to Combobox in Windows forms?
|

 |
4.15 How to do text encryption and decryption?
|

 |
|
Here are some interesting articles that talk about encryption and decryption:
|
4.16 How can I trigger a submit on my form when the enter key is pressed?
|

 |
|
Add this to the body element:
|
<body MS_POSITIONING=
"GridLayout"onkeypress="if(window.event.keyCode==13){
document.Form1.submit();}">
|
|
Also check out Andy Smith's
DefaultButton Control which triggers submit selectively on one of many
buttons based on the context.
|
4.17 How to get list of all files in the directory?
|

 |
|
To get the list of aspx files under your app directory:
Use namespace System.IO
VB.NET
|
Dim dirInfo As New
DirectoryInfo(Server.MapPath(""))
|
DataGrid1.DataSource =
dirInfo.GetFiles("*.aspx")
|
DirectoryInfo dirInfo = new
DirectoryInfo(Server.MapPath(""));
|
DataGrid1.DataSource =
dirInfo.GetFiles("*.aspx");
|
|
The following aspx code will display the resultant files list in the DataGrid in
a proper format:
|
<asp:DataGrid runat="server"
id="DataGrid1" AutoGenerateColumns="False">
|
<asp:HyperLinkColumn
DataNavigateUrlField="Name" DataTextField="Name" HeaderText="File
Name"></asp:HyperLinkColumn>
|
<asp:BoundColumn
DataField="LastWriteTime" HeaderText="Last Write Time"
DataFormatString="{0:d}"></asp:BoundColumn>
|
<asp:BoundColumn
DataField="Length" HeaderText="File Size" DataFormatString="{0:#,###
bytes}"></asp:BoundColumn>
|
4.18 What is HttpHandler?
|

 |
|
An HttpHandler is a class that handles HTTP requests. In ASP.Net a Page class,
for example, is the default HttpHandler for files with a .aspx extension. You
can map different file extensions to different HttpHandlers in ASP.Net. When
the web server receives a request for a file, it looks in its configuration to
find out whether a special HttpHandler has been designated for that file
extension. ASP.Net provides the HttpHandler class to extend the functionality
of ASP.net to be able to handle requests for other file types (extensions). In
IIS, you make ASP.Net the HttpHandler for the type of file that you desire, and
use the web.config file for your web to identify what DLL (Class Library) is
used to handle specific file extensions.
The HttpHandler is a class that handles the request. It has access to the same
HttpContext (Request, Response, Cookies, Session, Application, Server, etc)
that the Page class does. For more detailed information, see: HttpHandlers
|
4.19 How to get the size of a byte array?
|

 |
4.20 How to know the width and height in pixels of a given image
programmatically?
|

 |
|
You will have to create a Bitmap instance from the image file and then query
the Width and Height as follows:
VB.NET
|
Dim bm As Bitmap = New
Bitmap(Server.MapPath("b2346.jpg"))
|
Response.Write("Height :" +
bm.Height.ToString())
|
Response.Write("<br> Width :"
+ bm.Width.ToString())
|
Bitmap bm = new Bitmap(
Server.MapPath("b2346.jpg"));
|
Response.Write ("Height :" +
bm.Height.ToString() );
|
Response.Write ("<br> Width :"
+bm.Width.ToString() );
|
4.21 When using FormsAuthentication, how can I redirect a user to a different
page other than the default page?
|

 |
|
When FormsAuthentication is used in ASP.NET, by default, it gets redirected to
the default.aspx page.
To redirect it to some other page other than default.aspx you have to use the
code below.
VB.NET
|
FormsAuthentication.SetAuthCookie(txtUsername.Text,false)
|
Response.Redirect("someotherpage.aspx")
|
FormsAuthentication.SetAuthCookie(txtUsername.Text,false);
|
Response.Redirect("someotherpage.aspx");
|
4.22 Is there a control in ASP.NET for geting HTML like the ASPHTTP for the
classic asp.
|

 |
|
Use System.Net.HttpWebRequest
|
4.23 Why do I get error message "System.Web.HttpException: Request is not
available in this context" " when using Cookies?
|

 |
|
Try using "System.Web.HttpContext.Current.Request.Cookies" instead of
"Request.Cookies" in your code.
|
4.24 How to save the Output of ASP.NET to HTML?
|

 |
|
Use the namespaces
-
System.Net which have classes WebRequest and WebResponse.
-
WebRequest is the abstact base class for the .NET Framework's request/response
model for accessing data from the internet and
-
WebResponse is the abstract base class from which protocol specific response
classes are derived.
-
System.IO which have classes StreamReader and StreamWriter.
-
StreamReader designed for character input in a particular encoding.
-
StreamWriter designed for character output in a particular encoding.
VB.NET
|
Dim mywebReq As WebRequest
|
Dim mywebResp As WebResponse
|
Private Sub Page_Load(ByVal sender
As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
|
'Give
the Appropriate URL for .aspx page. in this case its
"http://www.syncfusion.com/faq.asp"
|
mywebReq
= WebRequest.Create("http://www.syncfusion.com/faq.asp")
|
mywebResp
= mywebReq.GetResponse()
|
sr =
New StreamReader(mywebResp.GetResponseStream)
|
sw =
File.CreateText(Server.MapPath("temp.html"))
|
Response.WriteFile(Server.MapPath("temp.html"))
|
private void Page_Load(object
sender, System.EventArgs e)
|
// Put
user code to initialize the page here
|
mywebReq
= WebRequest.Create("http://www.syncfusion.com/faq.asp");
|
mywebResp
= mywebReq.GetResponse();
|
sr =
new StreamReader(mywebResp.GetResponseStream());
|
strHTML
= sr.ReadToEnd();
|
sw =
File.CreateText(Server.MapPath("temp.html"));
|
Response.WriteFile(Server.MapPath("temp.html"));
|
|
Note:For creating the file (in above case "temp.html") give appropriate rights
(modify and write) to the ASPNET user.
To specify the Encoding specify the second parameter of the StreamReader
accordingly
VB.NET
|
sr = New
StreamReader(mywebResp.GetResponseStream, System.Text.Encoding.ASCII)
|
sr = new
StreamReader(mywebResp.GetResponseStream(), System.Text.Encoding.ASCII);
|
4.25 Why do I get ViewState error when upgrading my application from a single
web server to a web farm?
|

 |
|
This usually happens when encryption is enabled for ViewState in all your pages
but the different server machines use different Validation Keys for encrypting.
Ensure that all the machines has the same validation key specified in their
machine.config file. For example, add the following key:
|
<machinekey validation='3DES'>
|
4.26 How to convert Color to it's corresponding Hexadecimal value?
|

 |
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
|
Response.Write(ToHexColor(Color.Blue))
|
Function ToHexColor(ByVal c As
Color) As String
|
Return
"#" + c.ToArgb().ToString("x").Substring(2)
|
private void Page_Load(object
sender, System.EventArgs e)
|
// Put
user code to initialize the page here
|
Response.Write(ToHexColor(Color.Blue));
|
string ToHexColor(Color c )
|
return
"#" + c.ToArgb().ToString("x").Substring(2);
|
4.27 How to Select a record using Listbox and edit/update it's fields using
textboxes?
|

 |
<TABLE class="cdb-AltRow2"
id="Table1" style="Z-INDEX: 101; LEFT: 189px; POSITION: absolute; TOP: 20px"
cellSpacing="1" cellPadding="1" width="300" border="0">
|
<TD><asp:textbox
id="txtProductId" runat="server"
Enabled="False"></asp:textbox></TD>
|
<TD>Qunatity
per unit</TD>
|
<TD><asp:textbox
id="txtQuantity" runat="server"></asp:textbox></TD>
|
<TD><asp:textbox
id="txtUnitPrice" runat="server"></asp:textbox></TD>
|
<TD><asp:button
id="btnUpdate" runat="server" Text="Update"></asp:button></TD>
|
<TD><asp:label
id="lblError" runat="server" Visible="False"></asp:label></TD>
|
<asp:listbox id="ListBox1"
style="Z-INDEX: 102; LEFT: 8px; POSITION: absolute; TOP: 12px" runat="server"
AutoPostBack="True"></asp:listbox>
|
Dim dr, dr1 As SqlDataReader
|
Dim mycn As SqlConnection
|
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=;"
|
' Put
user code to initialize the page here
|
If Not
Page.IsPostBack Then
|
mycn
= New SqlConnection(strConn)
|
strSQL = "Select * from Products"
|
mycmd
= New SqlCommand(strSQL, mycn)
|
dr =
mycmd.ExecuteReader(CommandBehavior.CloseConnection)
|
ListBox1.DataTextField = "ProductID"
|
ListBox1.DataValueField = "ProductID"
|
Private Sub btnUpdate_Click(ByVal
sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdate.Click
|
Dim
updateCmd As String = "UPDATE Products SET QuantityPerUnit = @QuantityPerUnit
," + "UnitPrice = @UnitPrice where ProductId=@ProductId"
|
Dim cn
As New SqlConnection(strConn)
|
Dim
myCommand As New SqlCommand(updateCmd, cn)
|
myCommand.Parameters.Add(New
SqlParameter("@QuantityPerUnit", txtQuantity.Text))
|
myCommand.Parameters.Add(New
SqlParameter("@UnitPrice", Convert.ToDouble(txtUnitPrice.Text)))
|
myCommand.Parameters.Add(New
SqlParameter("@ProductId", Convert.ToInt16(txtProductId.Text)))
|
myCommand.ExecuteNonQuery()
|
lblError.Text
= "Record Updated successfully"
|
lblError.Text
= ex.Message
|
Private Sub
ListBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles ListBox1.SelectedIndexChanged
|
productid
= ListBox1.SelectedItem.Value
|
txtProductId.Text
= productid.ToString()
|
strSQL
= "Select * from Products where productid =" + productid
|
mycn =
New SqlConnection(strConn)
|
mycmd
= New SqlCommand(strSQL, mycn)
|
dr1 =
mycmd.ExecuteReader(CommandBehavior.CloseConnection)
|
txtProductId.Text = dr1("ProductId").ToString()
|
txtQuantity.Text = dr1("QuantityPerUnit").ToString()
|
txtUnitPrice.Text = dr1("UnitPrice").ToString()
|
Response.Write("No data found")
|
End Sub
'ListBox1_SelectedIndexChanged
|
private void Page_Load(object
sender, System.EventArgs e)
|
strConn="server=localhost;uid=sa;database=northwind;pwd=;";
|
// Put
user code to initialize the page here
|
mycn
= new SqlConnection(strConn);
|
strSQL
="Select * from Products";
|
mycmd
= new SqlCommand (strSQL, mycn);
|
dr=mycmd.ExecuteReader(CommandBehavior.CloseConnection
);
|
ListBox1.DataSource
= dr;
|
ListBox1.DataTextField
="ProductID";
|
ListBox1.DataValueField
="ProductID";
|
private void btnUpdate_Click(object
sender, System.EventArgs e)
|
string
updateCmd = "UPDATE Products SET QuantityPerUnit = @QuantityPerUnit ,"
|
+
"UnitPrice = @UnitPrice where ProductId=@ProductId";
|
SqlConnection
cn = new SqlConnection (strConn);
|
SqlCommand
myCommand = new SqlCommand(updateCmd, cn);
|
myCommand.Parameters.Add(new
SqlParameter("@QuantityPerUnit", txtQuantity.Text ));
|
myCommand.Parameters.Add(new
SqlParameter("@UnitPrice", Convert.ToDouble( txtUnitPrice.Text )));
|
myCommand.Parameters.Add(new
SqlParameter("@ProductId", Convert.ToInt16 ( txtProductId.Text)));
|
myCommand.ExecuteNonQuery
();
|
lblError.Text
="Record Updated successfully";
|
lblError.Text
=(ex.Message );
|
private void
ListBox1_SelectedIndexChanged(object sender, System.EventArgs e)
|
productid
= ListBox1.SelectedItem.Value ;
|
txtProductId.Text
=productid.ToString ();
|
strSQL
= "Select * from Products where productid =" + productid ;
|
mycn =
new SqlConnection(strConn);
|
mycmd
= new SqlCommand (strSQL, mycn);
|
dr1=mycmd.ExecuteReader(CommandBehavior.CloseConnection
);
|
txtProductId.Text
= dr1["ProductId"].ToString ();
|
txtQuantity.Text
= dr1["QuantityPerUnit"].ToString ();
|
txtUnitPrice.Text
= dr1["UnitPrice"].ToString ();
|
Response.Write
("No data found");
|
4.28 How to select a value from a child form and send it to parent form?
|

 |
<asp:TextBox id="txtSelect"
style="Z-INDEX: 101; LEFT: 186px; POSITION: absolute; TOP: 19px"
|
runat="server"></asp:TextBox>
|
<ahref="javascript:my_window=window.open('page2.aspx?formname=Form1.txtSelect','my_window','width=300,height=300');my_window.focus()">
|
<asp:DropDownList
id="DropDownList1" style="Z-INDEX: 101; LEFT: 180px; POSITION: absolute; TOP:
66px"
|
runat="server"
AutoPostBack="True">
|
<asp:Label id="Label1"
style="Z-INDEX: 102; LEFT: 16px; POSITION: absolute; TOP: 66px"
runat="server">Select Category Name
|
<asp:Literal id="Literal1"
runat="server">
|
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
|
DropDownList1.DataSource = ds.Tables(0)
|
DropDownList1.DataTextField = "CategoryName"
|
DropDownList1.DataValueField = "CategoryId"
|
Private Sub
DropDownList1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles DropDownList1.SelectedIndexChanged
|
Dim
strjscript As String = "<script language=""javascript"">"
|
strjscript = strjscript & "window.opener." &
HttpContext.Current.Request.QueryString("formname") & ".value = '" &
DropDownList1.SelectedItem.Text & "';window.close();"
|
strjscript = strjscript & "</script>"
|
Literal1.Text = strjscript
|
Response.Write(ex.Message)
|
private void Page_Load(object
sender, System.EventArgs e)
|
// Put
user code to initialize the page here
|
DropDownList1.DataSource =
ds.Tables[0];
|
DropDownList1.DataTextField = "CategoryName";
|
DropDownList1.DataValueField = "CategoryId";
|
DropDownList1.DataBind();
|
private void
DropDownList1_SelectedIndexChanged(object sender, System.EventArgs e)
|
string strjscript = @"<script language=""javascript"">";
|
strjscript = strjscript + "window.opener." +
HttpContext.Current.Request.QueryString["formname"].ToString () + ".value = '"
+ DropDownList1.SelectedItem.Text + "';window.close();";
|
strjscript = strjscript + "</script>";
|
Literal1.Text = strjscript;
|
Response.Write (ex.Message );
|
4.29 How to read the comma seperated values from a string?
|

 |
Dim myString As String = "A, B, C,
D"
|
Dim delimStr As String = " ,"
|
Dim delimiter As Char() =
delimStr.ToCharArray()
|
For Each s In
myString.Split(delimiter)
|
Response.Write((s.ToString()
+ "<br>"))
|
string myString = "A, B, C, D";
|
char[] delimiter =
delimStr.ToCharArray();
|
foreach (string s in
myString.Split(delimiter))
|
Response.Write
(s.ToString ()+ "<br>");
|
4.30 How do I make my TextBox positioned below a DataGrid move up or down in
position as the height of the DataGrid changes?
|

 |
|
Specify the pageLayout of the Document from GridLayout to FlowLayout, this will
position the controls automatically and optimally.
|
4.31 How to stamp Date-Time on all the pages in an application when requested?
|

 |
|
Use the global.asax file and listen to the PostRequestHandlerExecute event of
the Global object.
In the handler Global_PostRequestHandlerExecute write the following code
VB.NET
|
Response.Write("This page is updated
on " & DateTime.Now.ToString())
|
Response.Write("This page is updated
on " + DateTime.Now.ToString());
|
4.32 How can I have multiple command buttons map to the same event or function?
|

 |
|
Simply use the same handler for the different button Click events.
|
<asp:Button id="Button1"
runat="server" Text="Button"></asp:Button>
|
<asp:Button id="Button2"
style="Z-INDEX: 103; LEFT: 8px; POSITION: absolute; TOP: 80px" runat="server"
|
Text="Button"></asp:Button>
|
Private Sub Button1_Click(ByVal
sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click,
Button2.Click
|
Response.Write("hi
you clicked " + CType(sender, Button).ID)
|
// In InitializeComponent
|
this.Button1.Click += new
System.EventHandler(this.Button1_Click);
|
this.Button2.Click += new
System.EventHandler(this.Button1_Click);
|
private void Button1_Click(object
sender, System.EventArgs e)
|
Response.Write("hi you clicked " +
((Button)sender).ID );
|
4.33 How to use a RangeValidator to select Colors from a specific range?
|

 |
<asp:dropdownlist
id="DropDownList1" runat="server">
|
<asp:ListItem
Value ="#000000">#000000</asp:ListItem>
|
<asp:ListItem
Value ="#ff0000">#ff0000</asp:ListItem>
|
<asp:ListItem
Value ="#0000ff">#0000ff</asp:ListItem>
|
<asp:ListItem
Value ="#00aacc">#00aacc</asp:ListItem>
|
<asp:ListItem
Value ="#0000cc">#0000cc</asp:ListItem>
|
<asp:ListItem
Value ="#cc0000">#cc0000</asp:ListItem>
|
<asp:ListItem
Value ="#00ff00">#00ff00</asp:ListItem>
|
<asp:rangevalidator
id="RangeValidator1" runat="server"
|
ErrorMessage="Select
a color between #00ff00 to #ff0000" ControlToValidate="DropDownList1"
|
MaximumValue="#ff0000"
MinimumValue="#00ff00">
|
4.34 How to restore the browser's scroll position after a postback?
|

 |
4.35 Is there something as RecordSet we had in ASP that can be used in ASP.NET?
|

 |
4.36 How to set a <link> tag's href attribute at runtime using a value
specified in the web.config file?
|

 |
<add
key="CSS1" value="StyleSheet1.css" />
|
<link id="link1"
runat="server"/>
|
Dim lnk As New
System.Web.UI.HtmlControls.HtmlGenericControl("lnk")
|
lnk =
CType(Me.Page.FindControl("link1"),
System.Web.UI.HtmlControls.HtmlGenericControl)
|
lnk.Attributes.Add("rel",
"stylesheet")
|
lnk.Attributes.Add("href",
ConfigurationSettings.AppSettings("CSS1").ToString())
|
lnk.Attributes.Add("type",
"text/css")
|
System.Web.UI.HtmlControls.HtmlGenericControl
lnk =new System.Web.UI.HtmlControls.HtmlGenericControl ("lnk") ;
|
lnk
=(System.Web.UI.HtmlControls.HtmlGenericControl ) this.Page.FindControl(
"link1") ;
|
lnk.Attributes.Add ("rel",
"stylesheet");
|
lnk.Attributes.Add ("href",
ConfigurationSettings.AppSettings["CSS1"].ToString()) ;
|
lnk.Attributes.Add
("type","text/css");
|
4.37 How to call the Page_load procedure from any event on the page?
|

 |
Dim strval As String = "a"
|
Call
Page_Load(sender, e)
|
4.38 How to add login user (ASPNET) to MS SQL 2000 Desktop Engine server?
|

 |
|
Go to drive:\Program Files\Microsoft SQL Server\80\Tools\binn
Use OSQL, a command line tool.
|
osql -S servername\instancename -E
-q
|
--Line numbers will appear
|
EXEC sp_grantlogin
'machinename\ASPNET'
|
EXEC sp_grantdbaccess
'machinename\ASPNET'
|
EXEC sp_addrolemember 'db_owner',
'machinename\ASPNET'
|
4.39 How to get the count of rows in a Excel file?
|

 |
|
Add reference -> COM tab ->Microsoft Excel 11.0 Object Library
|
<asp:Label id="Label1"
runat="server"></asp:Label>
|
Dim excelApp As New
Microsoft.Office.Interop.Excel.Application
|
excelApp.Workbooks.Open(Server.MapPath("excel1.xls"))
|
Label1.Text =
excelApp.ActiveSheet.Usedrange.count.ToString
|
excelApp.Workbooks.Close()
|
Microsoft.Office.Interop.Excel.Application
excelApp = new Microsoft.Office.Interop.Excel.Application();
|
excelApp.Workbooks.Open (
Server.MapPath ("excel1.xls"), Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing );
|
Microsoft.Office.Interop.Excel.Worksheet
wks;
|
wks
=(Microsoft.Office.Interop.Excel.Worksheet)excelApp.ActiveSheet;
|
Label1.Text
=wks.UsedRange.Count.ToString();
|
excelApp.Workbooks.Close();
|
4.40 What are the pros and cons of using Session or Cache to save intermediate
state?
|

 |
|
To store in Session:
Pros:
-
It's stored per user session
-
It's just a handle to a live object, if using InProc
-
If you use StateServer or SQLServer mode, you can access your session state
across the webfarm. (can't use InProc mode in webfarm)
Cons:
-
If you use StateServer or SQLServer mode, your object must be serializable, and
you pay the performance cost of network traffic + serialization cost
To use cache:
Pros:
-
It's always stored as just a handle to the live object
-
Can use cache dependencies or other cache features to control its lifetime
-
Can be shared by all users on that web server
Cons:
-
It's per app-domain per web server.
|
4.41 How to mirror (align elements Right to Left) a form or control on a form?
|

 |
|
Process of switching of User Interface between left to right i.e English,
German ...and right to left such as Hebrew/Arabic is called Mirroring.
To mirror a form
|
|
To mirror individual control in a form set dir=rtl for individual controls.
|
4.42 How can I Enable ASPX Compression in IIS?
|

 |
4.43 How to run an exe from a ASP.NET page?
|

 |
|
For security reasons, you can't force a user to run any executable.
Instead give user the option to click on it and download the executable, and
execute it if he wants to. All you can do is put .exe in a directory on your
web site and put a hyperlink to it on some page.
Note : Be sure to secure this directory by deactivating all execution
permissions both in the IIS console and in the directory ACL
For more details refer
INFO: Executing Files by Hyperlink and the File Download Dialog Box
|
4.44 Why does FormsAuthentication.Decrypt crashes when moving to another
Server?
|

 |
|
The reason why the encrypted data couldn't be decrypted on another machine is
because the validation key in the original machine's machine.config is set to
AutoGenerate. This means that the generated keys are unique to each machine. A
better solution will be to specify the validation key, so you can decrypt it
across any machine with the same validation key. For more details on solutioon
refer following article :
|
4.45 Why do I get error message "Login failed for user DOMAIN\USERNAME"?
|

 |
|
You'll have to create an account in SQL Server for the aspnet user.
-
Start enterprise manager-> expand the server-> select
security->Right-click in the right view and select new login,
-
enter the DOMAIN\USERNAME and select your database as the default database of
the user at the bottom of the page,
-
Select last tab Database Access -> select your database, and add the
db_datareader and db_datawriter policies to your user.
|
4.46 How to check if the current User has been Authenticated?
|

 |
If User.Identity.IsAuthenticated
Then
|
if (User.Identity.IsAuthenticated )
|
4.47 How to get the Computer Name on which the code is running?
|

 |
|
This will return the information of the server computer, not the client browser
computer.
Add reference to System.Windows.Forms.dll.
VB.NET
|
Response.Write(System.Windows.Forms.SystemInformation.ComputerName)
|
Response.Write(System.Windows.Forms.SystemInformation.ComputerName);
|
4.48 How to pass argument to accessdatasourcecontrol selectcommand statement?
|

 |
AccessDataSourceControl1.SelectCommand
= "SELECT * FROM <tablename> WHERE <fieldname> = " &
Request("CustID")
|
AccessDataSourceControl1.SelectCommand
= "SELECT * FROM <tablename> WHERE <fieldname> = "+
Request["CustID"]
|
4.49 How to compile CS/VB file and place new DLL in bin subdirectory?
|

 |
|
You can build a dll using the following command line .
Assuming your command window has the appropriate path set to use the following
exes:
VB.NET compiler vbc.exe
|
vbc.exe /out:SyncVB.dll
/target:library SyncVB.vb
|
csc.exe /out:SyncCS.dll
/target:library SyncCS.cs
|
|
To reference it within the .aspx page use the Import directive:
<%@ Import Namespace="SyncVB" %>
or
<%@ Import Namespace="SyncCS" %>
|
4.50 Can I use a src attribute with a Web Service?
|

 |
|
The .aspx pages are the only ones that support the Src attribute, and therefore
it's the only file type that supports JIT compilation of separate source
files.By using the Src attribute in the page directive, you can specify which
file the ASP.NET engine should compile.
It cannot be used with a WebService.
This means that you must precompile the code behind class that is to be used as
the basis for the Web Service, either manually using the Command-line compiler
or by building a Visual Studio.NET Web Service Application.
|
4.51 How to display random images on a web page from a set of images in a
directory?
|

 |
<table id="Table1"
cellspacing="1" cellpadding="1" border="1">
|
<td
id="TD1" width="100" runat="server">
|
|
VB.NET (Add reference to Microsoft Visual Basic .NET Runtime)
|
Dim dirInfo As New
System.IO.DirectoryInfo("c:\inetpub\wwwroot\syncfusion\images") 'This is your
path to the bmp's
|
Dim fileInfo() As IO.FileInfo
|
Dim strRandomImage As String
|
fileInfo = dirInfo.GetFiles("*")
'Gets an array of file info
|
i = CInt(rnd.NextDouble *
UBound(fileInfo)) ' gets a random index
|
strRandomImage = "images/" +
fileInfo(i).Name ' Returns the random string
|
TD1.Attributes.Add("background",
strRandomImage)
|
System.IO.DirectoryInfo dirInfo =new
System.IO.DirectoryInfo(@"c:\inetpub\wwwroot\SyncnewCsharp\images") ;//This is
your path to the bmp's
|
System.IO.FileInfo[] fileInfo ;
|
fileInfo = dirInfo.GetFiles("*");
//Gets an array of file info
|
Microsoft.VisualBasic.VBMath.Randomize
();
|
i = Convert.ToInt32
(rnd.NextDouble() * fileInfo.GetUpperBound(0));// gets a random index
|
strRandomImage = "Images/" +
fileInfo[i].Name ;// Returns the random string
|
TD1.Attributes.Add ("background",
strRandomImage);
|
4.52 How can I scan a string to determine if it contains DBCS chars?
|

 |
Public Shared Function
IsAsciiString(s As [String]) As Boolean
|
For i = 0 To s.Length - 1
|
If ch < 0 Or ch > 127 Then
|
End Function 'IsAsciiString
|
dim originalString as string = "a±"
|
Response.Write
(IsAsciiString(originalString))
|
public static bool
IsAsciiString(String s)
|
for
(int i = 0; i < s.Length; i++)
|
if
(ch < 0 || ch > 127) return false;
|
String originalString = "a±" ;
|
Response.Write
(IsAsciiString(originalString));
|
4.53 Request.ServerVariables("LOGON_USER") always returns empty string in
Framework 1.1 . Why? It worked fine in ASP?
|

 |
|
If Request.ServerVariables("LOGON_USER") is returning an empty string, the
problem is probably that your app allows anonymous users. To change this:
-
Open IIS manager
-
right-click on your app name and choose properties
-
Click on directory security tab
-
Edit Authentication and Access Control
-
Uncheck 'Enable anonymous'.
|
4.54 Is there a way to specify CSS only if the browser is IE?
|

 |
|
You can examine the Request.UserAgent to check if the browser was IE, define a
custom HtmlGenericControl type representing your stylesheet link and set the
href property on it depending on if the browser was IE.
|
<LINK rel=stylesheet
runat="server" id="lnkStyle">
|
|
Where LINK is a HtmlGenericControl. You could then do something like this:
VB.NET
|
lnkStyle.Attributes("href") =
"ie/styles.css"
|
lnkStyle.Attributes["href"] =
"ie/styles.css" ;
|
4.55 How to create Custom Application Settings in the web.config?
|

 |
|
In the web.config file add a key-value pair as follows:
|
<add
key="PageSize" value="10">
|
|
Then you can access the settings as follows in code:
VB.NET
|
Response.Write
(ConfigurationSettings.AppSettings("PageSize"))
|
Response.Write
(ConfigurationSettings.AppSettings["PageSize"] );
|
4.56 Why do I get "do not have permissions" error when accessing a Access mdb
file in my local system?
|

 |
|
This could be because of security concerns. Please check this KB for
resolutions:
KB
316675
|
4.57 How can I access an MS Access database in my ASPX page, if the db is on a
remote server?
|

 |
|
To access an MS Access database from your ASP.Net page, you must use the UNC
format in the path, like:
\\Servername\yourpath\your.mdb
To fully use the database, grant permissions to the ASPNet user account equal to
'modify', for the folder/directory where the database exists.
|
|
|
|