Live Chat Icon For mobile
Live Chat Icon

ASP.NET FAQ

Find answers for the most frequently asked questions
Expand All Collapse All

page1.aspx


<asp:TextBox id='txtSelect' style='Z-INDEX: 101; LEFT: 186px; POSITION: absolute; TOP: 19px'
	runat='server'></asp:TextBox>
<a href='javascript:my_window = window.open(’page2.aspx?formname=Form1.txtSelect’ , ’my_window’,’width=300,height=300’); my_window.focus()'>
	Select CategoryName</a>

page2.aspx


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

VB.NET


Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
	’Put user code to initialize the page here
	If Not Page.IsPostBack Then
		’Fill DataSet ....	
	            DropDownList1.DataSource = ds.Tables(0)
	            DropDownList1.DataTextField = 'CategoryName'
	            DropDownList1.DataValueField = 'CategoryId'
	            DropDownList1.DataBind()
	End If
End Sub

Private Sub DropDownList1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DropDownList1.SelectedIndexChanged
	Try
	            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
	Catch ex As Exception
	            Response.Write(ex.Message)
	End Try
End Sub

C#


private void Page_Load(object sender, System.EventArgs e)
{
	// Put user code to initialize the page here
	if (!Page.IsPostBack )
	{
	            //Fill DataSet
                            DropDownList1.DataSource = ds.Tables[0];
	            DropDownList1.DataTextField = 'CategoryName';
	            DropDownList1.DataValueField = 'CategoryId';
	            DropDownList1.DataBind();
	}
}

private void DropDownList1_SelectedIndexChanged(object sender, System.EventArgs e)
{
	try
	{
	            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;
	}
	catch(Exception ex)
	{
	           Response.Write (ex.Message );
	}
}
Permalink

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 solution refer following article :

Permalink

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

Permalink

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 webform. (can’t use InProc mode in webform)

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

<TABLE class='cdb-AltRow2' id='Table1' style='Z-INDEX: 101; LEFT: 189px; POSITION: absolute; TOP: 20px' cellSpacing='1' cellPadding='1' width='300' border='0'>
	<TR>
	<TD>ProductID</TD>
	<TD><asp:textbox id='txtProductId' runat='server' Enabled='False'></asp:textbox></TD>
	</TR>
	<TR>
	<TD>Quantity per unit</TD>
	<TD><asp:textbox id='txtQuantity' runat='server'></asp:textbox></TD>
	</TR>
	<TR>
	<TD>UnitPrice</TD>
	<TD><asp:textbox id='txtUnitPrice' runat='server'></asp:textbox></TD>
	</TR>
	<TR>
	<TD></TD>
	<TD><asp:button id='btnUpdate' runat='server' Text='Update'></asp:button></TD>
	</TR>
	<TR>
	<TD></TD>
	<TD><asp:label id='lblError' runat='server' Visible='False'></asp:label></TD>
	</TR>
	</TABLE>
<asp:listbox id='ListBox1' style='Z-INDEX: 102; LEFT: 8px; POSITION: absolute; TOP: 12px' runat='server' AutoPostBack='True'></asp:listbox>

VB.NET


Dim productid As String
Dim strSQL As String
Dim strConn As String
Dim dr, dr1 As SqlDataReader
Dim mycn As SqlConnection
Dim mycmd As SqlCommand

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=;'
	lblError.Visible = False
	’ 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)
	            mycn.Open()
	            dr = mycmd.ExecuteReader(CommandBehavior.CloseConnection)
	            ListBox1.DataSource = dr
	            ListBox1.DataTextField = 'ProductID'
	            ListBox1.DataValueField = 'ProductID'
	            ListBox1.DataBind()
	End If
End Sub ’Page_Load

Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdate.Click
        Try
	lblError.Visible = False
	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)))
	cn.Open()
	myCommand.ExecuteNonQuery()
	lblError.Visible = True
	lblError.Text = 'Record Updated successfully'
        Catch ex As Exception
        	lblError.Visible = True
	lblError.Text = ex.Message
        End Try
End Sub ’btnUpdate_Click


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)
	mycn.Open()
	dr1 = mycmd.ExecuteReader(CommandBehavior.CloseConnection)
	If dr1.Read() Then
	            txtProductId.Text = dr1('ProductId').ToString()
	            txtQuantity.Text = dr1('QuantityPerUnit').ToString()
	            txtUnitPrice.Text = dr1('UnitPrice').ToString()
	Else
	            Response.Write('No data found')
	End If
End Sub ’ListBox1_SelectedIndexChanged 

C#


string productid;
string strSQL;
string strConn;
SqlDataReader dr,dr1;
SqlConnection mycn;
SqlCommand mycmd;

private void Page_Load(object sender, System.EventArgs e)
{
	strConn ='server=localhost;uid=sa;database=northwind;pwd=;';
	lblError.Visible =false;
	// Put user code to initialize the page here
	if (!Page.IsPostBack )
	{
		mycn = new SqlConnection(strConn);
		strSQL ='Select * from Products';
		mycmd = new SqlCommand  (strSQL, mycn);
		mycn.Open ();
		dr=mycmd.ExecuteReader(CommandBehavior.CloseConnection ); 
		ListBox1.DataSource = dr;
		ListBox1.DataTextField ='ProductID';
		ListBox1.DataValueField ='ProductID';
		ListBox1.DataBind ();
	}
}

private void btnUpdate_Click(object sender, System.EventArgs e)
{
	try
	{
		lblError.Visible =false;

		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)));
		cn.Open ();
		myCommand.ExecuteNonQuery ();
		lblError.Visible =true;
		lblError.Text ='Record Updated successfully';
	}
	catch(Exception ex)
	{
		lblError.Visible =true;
		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);
	mycn.Open ();
	dr1=mycmd.ExecuteReader(CommandBehavior.CloseConnection ); 
	if(dr1.Read() )
	{
		txtProductId.Text = dr1['ProductId'].ToString ();
		txtQuantity.Text = dr1['QuantityPerUnit'].ToString ();
		txtUnitPrice.Text = dr1['UnitPrice'].ToString ();
	}
	else
	{
		Response.Write ('No data found');
	}
}
Permalink

Use the namespaces

  • System.Net which have classes WebRequest and WebResponse.
    • WebRequest is the abstract 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
Dim sr As StreamReader
Dim strHTML As String
Dim sw As StreamWriter
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/aspnet'
	mywebReq = WebRequest.Create('http://www.syncfusion.com/faq/aspnet')
	mywebResp = mywebReq.GetResponse()
	sr = New StreamReader(mywebResp.GetResponseStream)
	strHTML = sr.ReadToEnd
	sw = File.CreateText(Server.MapPath('temp.html'))
	sw.WriteLine(strHTML)
	sw.Close()
	Response.WriteFile(Server.MapPath('temp.html'))
End Sub

C#


WebRequest mywebReq ; 
WebResponse mywebResp ; 
StreamReader sr ; 
string strHTML ;
StreamWriter sw;
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/aspnet');
	mywebResp = mywebReq.GetResponse();
	sr = new StreamReader(mywebResp.GetResponseStream());
	strHTML = sr.ReadToEnd();
	sw = File.CreateText(Server.MapPath('temp.html'));
	sw.WriteLine(strHTML);
	sw.Close();
	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)

C#


sr = new StreamReader(mywebResp.GetResponseStream(), System.Text.Encoding.ASCII);
Permalink

Add reference -> COM tab ->Microsoft Excel 11.0 Object Library


<asp:Label id='Label1' runat='server'></asp:Label>

VB.NET


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

C#


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();
Permalink

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')

C#


FormsAuthentication.SetAuthCookie(txtUsername.Text,false);
Response.Redirect('someotherpage.aspx');
Permalink

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.

Permalink

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

C#


//Displays the currently logged in user
Response.Write(User.Identity.Name.ToString());
Permalink

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’
go

use 
go

EXEC sp_grantdbaccess ’machinename\ASPNET’
go

EXEC sp_addrolemember ’db_owner’, ’machinename\ASPNET’
go
Permalink

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>

VB.NET


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)
End Sub

C#


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

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)

C#


Response.Write(System.Windows.Forms.SystemInformation.ComputerName);
Permalink

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

C# compiler csc.exe


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’ %>

Permalink

<table id='Table1' cellspacing='1' cellpadding='1' border='1'>
<tr>
	<td id='TD1' width='100' runat='server'>
	 
	</td>
</tr>
</table>

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
Dim i As Integer
Dim rnd As Random
fileInfo = dirInfo.GetFiles('*') ’Gets an array of file info 
rnd = New Random
Randomize()
i = CInt(rnd.NextDouble * UBound(fileInfo)) ’ gets a random index 
strRandomImage = 'images/' + fileInfo(i).Name ’ Returns the random string 
TD1.Attributes.Add('background', strRandomImage)

C#


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 ;
string strRandomImage; 
int i ;
Random rnd ;  
fileInfo = dirInfo.GetFiles('*'); //Gets an array of file info 
rnd = new Random(); 
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); 
Permalink

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

C#


Bitmap bm = new Bitmap( Server.MapPath('b2346.jpg'));
Response.Write ('Height  :' + bm.Height.ToString() );
Response.Write ('<br> Width :' +bm.Width.ToString() );
Permalink

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' 

C#


lnkStyle.Attributes['href'] = 'ie/styles.css' ;
Permalink

In the web.config file add a key-value pair as follows:


<configuration>
<appSettings>
	<add key='PageSize' value='10'>
	</add>
</appSettings>
</configuration>

Then you can access the settings as follows in code:

VB.NET


Response.Write (ConfigurationSettings.AppSettings('PageSize'))

C#


Response.Write (ConfigurationSettings.AppSettings['PageSize'] );
Permalink

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.

Permalink

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')
DataGrid1.DataBind()

C#


DirectoryInfo dirInfo = new DirectoryInfo(Server.MapPath(''));
DataGrid1.DataSource = dirInfo.GetFiles('*.aspx');
DataGrid1.DataBind();

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'>
<Columns>
<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>
</Columns>
</asp:DataGrid>
Permalink

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

Permalink

Use namespace System.Web.HttpUtility
VB.NET


Dim mystring as string =”Tom & Jerry”
Response.Write (HttpUtility.HtmlDecode (mystring))

C#


string mystring=”Tom & Jerry”;
Response.Write (HttpUtility.HtmlDecode (mystring));
Permalink

VB.NET


Dim myString As String = 'A, B, C, D'
Dim delimStr As String = ' ,'
Dim delimiter As Char() = delimStr.ToCharArray()
Dim s As String
For Each s In myString.Split(delimiter)
	Response.Write((s.ToString() + '<br>'))
Next

C#


string myString = 'A, B, C, D';
string delimStr = ' ,';
char[] delimiter = delimStr.ToCharArray();
foreach (string s in myString.Split(delimiter))
{
	Response.Write (s.ToString ()+ '<br>');    
}
Permalink

web.config


<configuration>
   	<appSettings>
		<add key='CSS1' value='StyleSheet1.css' />
	</appSettings>
</configuration>

.aspx


<link id='link1' runat='server'/>

VB.NET


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')

C#


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');
Permalink

<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:dropdownlist>
<asp:rangevalidator id='RangeValidator1' runat='server' 
	ErrorMessage='Select a color between #00ff00 to #ff0000' ControlToValidate='DropDownList1'
	MaximumValue='#ff0000' MinimumValue='#00ff00'>
</asp:rangevalidator>

Permalink

VB.NET


Public Shared Function IsAsciiString(s As [String]) As Boolean
   Dim i As Integer
   For i = 0 To s.Length - 1
      Dim ch As Char = s(i)
      If ch < 0 Or ch > 127 Then
         Return False
      End If
   Next  
   Return True
End Function ’IsAsciiString

’In Page_Load
dim originalString  as string = 'a±' 
Response.Write (IsAsciiString(originalString)) 

C#


public static bool IsAsciiString(String s) 
{ 
	for (int i = 0; i < s.Length; i++)
	{
		char ch = s[i];
		if (ch < 0 || ch > 127) return false; 
	} 
	return true; 
} 
//In Page_Load
String originalString = 'a±' ;
Response.Write (IsAsciiString(originalString));
Permalink

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

VB.NET


Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
	’Put user code to initialize the page here
	Response.Write(ToHexColor(Color.Blue))
End Sub

Function ToHexColor(ByVal c As Color) As String
	Return '#' + c.ToArgb().ToString('x').Substring(2)
End Function

C#


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

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

Permalink

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)

C#


string strval    = 'Jack and Jill';
string strnewval    = Regex.Replace(strval, ' ', '');
Response.Write(strnewval)	;

Permalink

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 Class MyClass1
Public Sub New()
End Sub
 
public Function getTheName(byval strval as string) as string
Return 'Hello' + strval
End function
End Class

VB.NET


Dim mc As New MyClass1
Response.Write(mc.getTheName)

C#


MyClass1 mc = new MyClass1();
Response.Write(mc.getTheName);
Permalink

VB.NET


Response.Clear()
Response.AppendHeader('content-disposition', 'attachment; filename=document1.doc')
Response.ContentType = 'text/plain'
Response.WriteFile(Server.MapPath('document1.doc'))
Response.Flush()
Response.End()

C#


Response.Clear();
Response.AppendHeader('content-disposition', 'attachment; filename=document1.doc');
Response.ContentType = 'text/plain';
Response.WriteFile(Server.MapPath('document1.doc'));
Response.Flush();
Response.End();
Permalink

Share with

Share on twitter
Share on facebook
Share on linkedin

Couldn't find the FAQs you're looking for?

Please submit your question and answer.