• Home
  • Privacy Policy
  • Terms & Conditions
  • Contact
  • Advertise
Videos, Photos, Wallpapers, Free Download, Movies, Songs, Sports , Live TV, Entertainment
 
  • Home
  • Bollywood
  • Hollywood
  • Box Office
  • Beauty
  • Fashion
  • Celebrity
  • Business
    • Social Media
    • Money Online
    • Category
  • Entertainment
    • Bollywood
  • Video
    • Youtube
    • Video
  • Technology
    • Asp.net
    • C#
    • SQL
    • .Net
Showing posts with label Server Control. Show all posts
ASP.Net AdRotator control can be used to display graphics that are linked to other pages. The list of graphics to be displayed and the associated target links is maintained in a data source such as an XML file or database.

ASP.Net AdRotator Web server control provides a way to display advertisements (ads) on your ASP.NET Web pages. The control displays a .gif file or other graphic image that you provide. When users click the ad, they are redirected to a target URL that you have specified. The control automatically reads advertisement information, such as the graphic file name and the target URL, from a list of ads that you provide using a data source, which is usually an XML file or a database table.

asp:AdRotator control selects ads randomly, changing the displayed ad each time the page is refreshed. Ads can be weighted to control the priority level of banners, making it possible to have certain ads display more often than others.

// XML CODE THAT AS THE DETAILS ABOUT THE ADS
<Advertisements>
<Ad>
<ImageUrl>C:\AdvFolder\AdRotator_Template\Adsense.gif</ImageUrl>
<NavigateUrl>http://www.Adsense.net</NavigateUrl>
<AlternateText>ASP.NET Logo</AlternateText>
<Keyword>A</Keyword>
<Impressions>Technology</Impressions>
<Caption>This is the caption for Ad#1</Caption>
</Ad>

<Ad>
<ImageUrl>C:\AdvFolder\AdRotator_Template\MakeMoney.gif</ImageUrl>
<NavigateUrl>http://www.MakeMoney.net</NavigateUrl>
<AlternateText>www.Sulekha.net</AlternateText>
<Keyword>S</Keyword>
<Impressions>Web Site</Impressions>
<Caption>This is the caption for Ad#2</Caption>
</Ad>

<Ad>
<ImageUrl>C:\AdvFolder\AdRotator_Template\OnlineEarn.swf</ImageUrl>
<NavigateUrl>AdRotator.aspx?ad=Widgets
&target=http://msdn.microsoft.com/widgets/</NavigateUrl>
<AlternateText>www.OnlineEarn.net</AlternateText>
<Keyword>S</Keyword>
<Impressions>Flash Site</Impressions>
<Caption>This is the caption for Ad#3</Caption>
</Ad>
</Advertisements>

<asp:AdRotator id="controlName" runat="server"
AdvertisementFile="demo-ads.xml" Target="_self">
</asp:AdRotator>


AdRotator control presents ad images that, when clicked, navigate to a new Web location. Each time the page is loaded into the browser, an ad is randomly selected from a predefined list. The rotation shedule of the adds is defined in a XML file.

AdRotator control uses a separate XML advertisement file to store the advertisement information, such as the location of the image to display and the URL of the page to link to. The AdvertisementFile property of the AdRotator control specifies the path to this file.
This tutorial, how <asp:CheckBox/> worked in GridView, Repeater and DataList control to provide the user with an intuitive way of selecting multiple rows of the GridView, Repeater and DataList.

<asp:Repeater ID="RepeaterExample" runat="server" DataSourceID="AccessDataSourceExample">
<ItemTemplate>
<div>
<asp:CheckBox ID="CategoryID" runat="server" Text='<%# Eval("CategoryID") %>' />
</div>
</ItemTemplate>
</asp:Repeater>

<asp:GridView ID="GridViewExample" runat="server" AutoGenerateColumns="False" DataKeyNames="CategoryID"
DataSourceID="AccessDataSourceExample">
<Columns>
<asp:TemplateField HeaderText="CategoryID" InsertVisible="False">
<ItemTemplate>
<asp:CheckBox ID="CategoryID" runat="server" Text='<%# Eval("CategoryID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Description" HeaderText="Description" />
<asp:BoundField DataField="CategoryName" HeaderText="CategoryName" />
</Columns>
</asp:GridView>

<asp:DataList ID="DataListExample" runat="server" DataKeyField="CategoryID"
DataSourceID="AccessDataSourceExample">
<ItemTemplate>
CategoryID:
<asp:CheckBox ID="CategoryID" runat="server" Text='<%# Eval("CategoryID") %>' /><br />
Description:
<asp:Label ID="DescriptionLabel" runat="server" Text='<%# Eval("Description") %>' />
<br />
CategoryName:
<asp:Label ID="CategoryNameLabel" runat="server" Text='<%# Eval("CategoryName") %>' />
<br /><br />
</ItemTemplate>
</asp:DataList></div>

<asp:Literal ID="rptLiteralExample" runat="server" /><br />
<asp:Literal ID="grD_listiteralExample" runat="server" /><br />
<asp:Literal ID="dstliteralExample" runat="server" /><br />

<asp:Button ID="ButtonExample" runat="server" Text="Button" />
<asp:AccessDataSource ID="AccessDataSourceExample" runat="server" DataFile="~/App_Data/MyDatabase.mdb"
SelectCommand="SELECT [CategoryID], [Description], [CategoryName] FROM [Categories]" />

GridView Example:

The <asp:GridView /> contains a collection of GridViewRow objects. Once you reference the collection, and iterate through it, you can use the FindControl method of the GridViewRow to access controls:

string Grd = "GridView Items Checked:<br />";
foreach (GridViewRow gvr in GridViewExample.Rows)
{
CheckBox chk = (CheckBox)gvr.FindControl("CategoryID");
if (chk.Checked)
{
Grd += (chk.Text + "<br />");
}
}
grD_listiteralExample.Text = Grd;

Repeater Example:

The <asp:Repeater /> has an Items collection. In this example, the Count property of the Items collection is retrieved and used with a for.. next loop While ... End to iterate the collection. The FindControl method of each Item is used to reference the CheckBox again:

string Rpt = "Repeater Items Checked:<br />";
for (int i = 0; i < RepeaterExample.Items.Count; i++)
{
CheckBox chk = (CheckBox)RepeaterExample.Items[i].FindControl("CategoryID");
if (chk.Checked)
{
Rpt+=(chk.Text + "<br />");
}
}
rptLiteralExample.Text = Rpt;


DataList Example:

The <asp:DataList /> also has an Items collection, but this time, foreach is used to iterate the collection. for... next could just as easily be used as in the Repeater example:

string Dl = "Datalist Items Checked:<br />";
foreach (DataListItem dli in DataListExample.Items)
{
CheckBox chk = (CheckBox)dli.FindControl("CategoryID");
if (chk.Checked)
{
Dl += (chk.Text + "<br />");
}
}
dstliteralExample.Text = Dl;

<asp:XmlDataSource
CacheDuration="string|Infinite"
CacheExpirationPolicy="Absolute|Sliding"
CacheKeyDependency="string"
DataFile="string"
EnableCaching="True|False"
EnableTheming="True|False"
EnableViewState="True|False"
ID="string"
OnDataBinding="DataBinding event handler"
OnDisposed="Disposed event handler"
OnInit="Init event handler"
OnLoad="Load event handler"
OnPreRender="PreRender event handler"
OnTransforming="Transforming event handler"
OnUnload="Unload event handler"
runat="server"
SkinID="string"
TransformArgumentList="string"
TransformFile="string"
Visible="True|False"
XPath="string"
>
<Data>string</Data>
<Transform>string</Transform>
</asp:XmlDataSource>

The XmlDataSource typically loads XML data from an XML file, which is specified by the DataFile property. XML data can also be stored directly by the data source control in string form using the Data property. If you want to transform the XML data before it is displayed by a data-bound control, you can provide an Extensible Stylesheet Language (XSL) style sheet for the transformation. As with the XML data, you typically load the style sheet from a file, indicated by the TransformFile property, but you can also store it in string form directly using the Transform property.

The XmlDataSource control is a data source control that presents XML data to data-bound controls. The XmlDataSource control can be used by data-bound controls to display both hierarchical and tabular data. The XmlDataSource control is typically used to display hierarchical XML data in read-only scenarios. Because the XmlDataSource control extends the HierarchicalDataSourceControl class, it works with hierarchical data. The XmlDataSource control also implements the IDataSource interface and works with tabular, or list-style, data.

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

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

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>ASP.Net XmlDataSource: How to use</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:Teal">XmlDataSource</h2>
<asp:CheckBoxList
ID="CheckBoxListExample"
runat="server"
>
</asp:CheckBoxList>
<asp:XmlDataSource
ID="XmlDataSourceExample"
runat="server"
>
<Data>
<Players>
<Player ID="1" Name="John" />
<Player ID="2" Name="Jim" />
<Player ID="3" Name="Jones" />
<Player ID="4" Name="Jenny" />
<Player ID="5" Name="Ben" />
</Players>
</Data>
</asp:XmlDataSource>
</div>
</form>
</body>
</html>


using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class XmlDataSource : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!this.IsPostBack)
{
CheckBoxListExample.DataSourceID = "XmlDataSourceExample";
CheckBoxListExample.DataTextField = "Name";
CheckBoxListExample.DataValueField = "ID";
CheckBoxListExample.RepeatColumns = 3;
CheckBoxListExample.BorderWidth = 2;
CheckBoxListExample.BorderColor = System.Drawing.Color.DarkGreen;
CheckBoxListExample.BackColor = System.Drawing.Color.Green;
CheckBoxListExample.ForeColor = System.Drawing.Color.White;
}
}
}
<asp:CustomValidator
id="ProgrammaticID"
ControlToValidate="programmatic ID of Server Control to Validate"
ClientValidationFunction="ClientValidateID"
OnServerValidate="ServerValidateID"
ErrorMessage="Message to display in ValidationSummary control"
Text="Message to display in control"
ForeColor="value"
BackColor="value"
runat="server" >
</asp:CustomValidator>

The CustomValidator control allows you to create a validation control with customized validation logic. For example, you can create a validation control that checks whether the value entered into a text box is an even number.

Validation controls always perform validation checking on the server. They also have complete client-side implementation that allows DHTML-supported browsers (such as Microsoft Internet Explorer 4.0 or later) to perform validation on the client. Client-side validation enhances the validation process by checking user input before it is sent to the server. This allows errors to be detected on the client before the form is submitted, avoiding the round-trip of information necessary for server-side validation.


Check the length of the string in the TextBox. This is a very basic example, to show how you may use the CustomValidator.

<asp:TextBox runat="server" id="txtExample" />
<asp:CustomValidator runat="server" id="CustomValidatorExample" controltovalidate="txtExample" onservervalidate="CustomValidatorExample_ServerValidate" errormessage="The text must be exactly 10 characters long!" />

protected void CustomValidatorExample_ServerValidate(object sender, ServerValidateEventArgs e)
{
if(e.Value.Length == 10)
e.IsValid = true;
else
e.IsValid = false;
}
<asp:RangeValidator
id="ProgrammaticID"
ControlToValidate="ProgrammaticID of control to validate"
MinimumValue="value"
MaximumValue="value"
Type="DataType"
ErrorMessage="Message to display in ValidationSummary control"
Text="Message to display in control"
ForeColor="value"
BackColor="value"
runat="server" >
</asp:RangeValidator>

The RangeValidator control allows you to check whether a user's entry is between a specified upper and lower boundary. You can check ranges within pairs of numbers, alphabetic characters, and dates. Boundaries are expressed as constants.

Use the ControlToValidate property to specify the input control to validate. The MinimumValue and MaximumValue properties specify the minimum and maximum values of the valid range, respectively.


<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C/DTD XHTML 1.0 Transitional/EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >

<script runat="server">
protected void ButtonExample_Click(object sender,System.EventArgs e) {
LabelExample.Text = "You entered valid Number.<br>Your Number:" + TextBoxExample.Text.ToString();
}
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>ASP.Net RangeValidator Example</title>
</head>

<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="LabelExample" runat="server"></asp:Label>
<br />
<asp:Label ID="lblTesting" runat="server" Text="Number" AssociatedControlID="TextBoxExample"></asp:Label>
<asp:TextBox ID="TextBoxExample" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidatorExample" runat="server" ControlToValidate="TextBoxExample" ErrorMessage="Number is required!" Text="*">
</asp:RequiredFieldValidator>
<asp:RangeValidator ID="RangeValidatorExample" runat="server" ControlToValidate="TextBoxExample" MaximumValue="200" MinimumValue="100" Type="Integer" ErrorMessage="You must be input between 100 to 200.">
</asp:RangeValidator>
<br />
<asp:Button ID="ButtonExample" runat="server" Text="Validate Number" OnClick="ButtonExample_Click"/>
</div>
</form>
</body>
</html>
<asp:CompareValidator
id="ProgrammaticID"
ControlToValidate="Programmatic ID of Server Control to Validate"
ValueToCompare="value"
ControlToCompare="value"
Type="DataType"
Operator="Operator Value"
ErrorMessage="Message to display in ValidationSummary control"
Text="Message to display in control"
ForeColor="value"
BackColor="value"
runat="server" >
</asp:CompareValidator>


The CompareValidator control allows you to compare the value entered by the user into an input control, such as a TextBox control, with the value entered into another input control, or with a constant value. You can also use the CompareValidator control to determine whether the value entered into an input control can be converted to the data type specified by the Type property.

Specify the input control to validate by setting the ControlToValidate property. If you want to compare a specific input control with another input control, set the ControlToCompare property with the name of the control to compare.


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

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

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>ASP.Net CompareValidator Example</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:Red">CompareValidator</h2>
<asp:Label ID="lbl1Example" runat="server">
</asp:Label>
<br /><br />
<asp:Label ID="lbl2Example" runat="server">
</asp:Label>
<asp:TextBox ID="txtExample" runat="server">
</asp:TextBox>
<asp:CompareValidator ID="CompareValidatorExample" runat="server">
</asp:CompareValidator>
<br />
<asp:Label ID="lbl3Example" runat="server">
</asp:Label>
<asp:TextBox ID="txt2Example" runat="server">
</asp:TextBox>
<asp:RequiredFieldValidator
ID="RequiredFieldValidatorExample"
runat="server"
ControlToValidate="txt2Example"
Text="*"
>
</asp:RequiredFieldValidator>
<br />
<asp:Button ID="ButtonExample" runat="server" Text="Submit Password" OnClick="ButtonExample_Click" />
</div>
</form>
</body>
</html>


using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class CompareValidator : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
lbl1Example.ForeColor = System.Drawing.Color.Green;
lbl1Example.Font.Italic = true;
lbl2Example.Text = "Password";
lbl3Example.Text = "Re-Type Password";
txtExample.TextMode = TextBoxMode.Password;
txt2Example.TextMode = TextBoxMode.Password;
ButtonExample.Font.Bold = true;
ButtonExample.ForeColor = System.Drawing.Color.Green;
CompareValidatorExample.ControlToValidate = "txt2Example";
CompareValidatorExample.ControlToCompare = "txtExample";
CompareValidatorExample.ErrorMessage = "Password do not match!";
}
}

protected void ButtonExample_Click(object sender, EventArgs e) {
lbl1Example.Text = "Password match.";
}
}
<asp:RequiredFieldValidator
id="ProgrammaticID"
ControlToValidate="ProgrammaticID of control to validate"
InitialValue="value"
ErrorMessage="Message to display in ValidationSummary control"
Text="Message to display in control"
ForeColor="value"
BackColor="value"
runat="server" >
</asp:RequiredFieldValidator>


Use the RequiredFieldValidator control to make an input control a mandatory field. The input control fails validation if the value it contains does not change from its initial value when validation is performed. This prevents the user from leaving the associated input control unchanged. By default, the initial value is an empty string (""), which indicates that a value must be entered in the input control for it to pass validation.

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

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

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>ASP.Net RequiredFieldValidator Example</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:Red">RequiredFieldValidator</h2>
<asp:Label ID="lbl1Example" runat="server">
</asp:Label>
<br /><br />
<asp:Label ID="lbl2Example" runat="server">
</asp:Label>
<asp:TextBox ID="txtExample" runat="server">
</asp:TextBox>
<asp:RequiredFieldValidator
ID="RequiredFieldValidatorExample"
runat="server"
>
</asp:RequiredFieldValidator>
<br />
<asp:Button ID="ButtonExample" runat="server" Text="Submit" OnClick="ButtonExample_Click" />
</div>
</form>
</body>
</html>


using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class RequiredFieldValidator : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
lbl1Example.Font.Italic = true;
lbl1Example.ForeColor = System.Drawing.Color.SeaGreen;
lbl2Example.Text = "Name";
txtExample.ForeColor = System.Drawing.Color.SeaGreen;
ButtonExample.Font.Bold = true;
ButtonExample.ForeColor = System.Drawing.Color.SeaGreen;
RequiredFieldValidatorExample.ControlToValidate = "txtExample";
RequiredFieldValidatorExample.ErrorMessage = "input name!";
}
}

protected void ButtonExample_Click(object sender, EventArgs e) {
lbl1Example.Text = "Hello " + txtExample.Text.ToString();
}
}
<asp:ValidationSummary
id="programmaticID"
DisplayMode="BulletList | List | SingleParagraph"
EnableClientScript="true | false"
ShowSummary="true | false"
ShowMessageBox="true | false"
HeaderText="TextToDisplayAsSummaryTitle"
runat="server"/>

The ValidationSummary control allows you to summarize the error messages from all validation controls on a Web page in a single location. The summary can be displayed as a list, a bulleted list, or a single paragraph, based on the value of the DisplayMode property. The error message displayed in the ValidationSummary control for each validation control on the page is specified by the ErrorMessage property of each validation control. If the ErrorMessage property of the validation control is not set, no error message is displayed in the ValidationSummary control for that validation control. You can also specify a custom title in the heading section of the ValidationSummary control by setting the HeaderText property.

You can control whether the ValidationSummary control is displayed or hidden by setting the ShowSummary property. The summary can also be displayed in a message box by setting the ShowMessageBox property to true.

<%@ Page Language="C#" %>

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

<script runat="server">
protected void ButtonExample_Click(object sender, System.EventArgs e) {
lbl1Example.Text = "Your Country: " +
txt1Example.Text.ToString() +
"<br />Region: " +
txt2Example.Text.ToString() +
"<br />City: " +
txt3Example.Text.ToString();

}
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>ASP.Net ValidationSummary Example</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lbl1Example" runat="server" Font-Size="Large" ForeColor="BlueViolet"></asp:Label>
<br /><br />
<asp:Label ID="lbl2Example" runat="server" Text="Country Name" AssociatedControlID="txt1Example"></asp:Label>
<asp:TextBox ID="txt1Example" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator
ID="RequiredFieldValidatorExample"
runat="server"
ControlToValidate="txt1Example"
ErrorMessage='Input Country!'
EnableClientScript="true"
SetFocusOnError="true"
Text="*"
>
</asp:RequiredFieldValidator>
<br />

<asp:Label ID="lbl3Example" runat="server" Text="Region Name" AssociatedControlID="txt2Example"></asp:Label>
<asp:TextBox ID="txt2Example" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator
ID="RequiredFieldValidator2"
runat="server"
ControlToValidate="txt2Example"
ErrorMessage='Input Region!'
EnableClientScript="true"
SetFocusOnError="true"
Text="*"
>
</asp:RequiredFieldValidator>
<br />

<asp:Label ID="lbl4Example" runat="server" Text="City Name" AssociatedControlID="txt3Example"></asp:Label>
<asp:TextBox ID="txt3Example" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator
ID="RequiredFieldValidator3"
runat="server"
ControlToValidate="txt3Example"
ErrorMessage='Input Region!'
EnableClientScript="true"
SetFocusOnError="true"
Text="*"
>
</asp:RequiredFieldValidator>
<br />
<asp:Button ID="ButtonExample" runat="server" Text="Submit" OnClick="ButtonExample_Click" />
<br /><br />
<asp:ValidationSummary ID="ValidationSummaryExample" runat="server" HeaderText="Following error occurs:" ShowMessageBox="false" DisplayMode="BulletList" ShowSummary="true" />
</div>
</form>
</body>
</html>
The FileUpload control enables users to upload files to your web application. After the file is uploaded, you can store the file.

FileUpload control properties :
  • Enabled : Enables you to disable the FileUpload control.
  • FileBytes : Enables you to get the uploaded file contents as a byte array.
  • FileContent : Enables you to get the uploaded file contents as a stream.
  • FileName : Enables you to get the name of the file uploaded.
  • HasFile : Returns True when a file has been uploaded.
  • PostedFile : Enables you to get the uploaded file wrapped in the HttpPostedFile object.
FileUpload control methods:
  • Focus : Enables you to shift the form focus to the FileUpload control.
  • SaveAs : Enables you to save the uploaded file to the file system.
The FileUpload control’s PostedFile property enables you to retrieve the uploaded file wrapped in an HttpPostedFile object. This object exposes additional information about the uploaded file.

The HttpPostedFile class has the following properties :
  • ContentLength : Enables you to get the size of the uploaded file in bytes.
  • ContentType : Enables you to get the MIME type of the uploaded file.
  • FileName : Enables you to get the name of the uploaded file.
  • InputStream : Enables you to retrieve the uploaded file as a stream.
The HttpPostedFile class also supports the following method:
  • SaveAs : Enables you to save the uploaded file to the file system.
File Uploads in ASP.NetYou can save a file by using either the FileUpload.SaveAs() method or the HttpPostedFile.SaveAs() method.

<%@ Page Language=”C#” %>
<%@ Import Namespace=”System.IO” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<script runat=”server”>
protected void btnAdd_Click(object sender, EventArgs e)
{
if (ImageUpload.HasFile)
{
if (CheckFileType(ImageUpload.FileName))
{
String filePath = “~/UploadImages/” + ImageUpload.FileName;
ImageUpload.SaveAs(MapPath(filePath));
}
}
}
bool CheckFileType(string fileName)
{
string ext = Path.GetExtension(fileName);
switch (ext.ToLower())
{
case “.gif”:
return true;
case “.png”:
return true;
case “.jpg”:
return true;
case “.jpeg”:
return true;
default:
return false;
}
}
void Page_PreRender()
{
string upFolder = MapPath(“~/UploadImages/”);
DirectoryInfo dir = new DirectoryInfo(upFolder);
dlstImages.DataSource = dir.GetFiles();
dlstImages.DataBind();
}
</script>

<html xmlns=”http://www.w3.org/1999/xhtml” >
<head id=”Head1” runat=”server”>
<title>FileUpload File</title>
</head>
<body>
<form id=”form1” runat=”server”>
<div>
<asp:Label id=”lblImageFile” Text=”Image File:” AssociatedControlID=”ImageUpload” Runat=”server” />
<asp:FileUpload id=”ImageUpload” Runat=”server” />
<br /><br />
<asp:Button id=”btnAdd” Text=”Add Image” OnClick=”btnAdd_Click” Runat=”server” />
</div>
</form>
</body>
</html>

The page includes a method named CheckFileType(), which prevents users from uploading a file that does not have the .gif, .jpeg, .jpg, or .png extension. The method restricts the type of file that can be uploaded based on the file extension.
Older Posts Home

ASP.NET Examples

 
2012 24x7 Magazine. All rights reserved.
Designed by 24x7 Magazine