jump to navigation

Set the focus on an asp.net server control March 3, 2010

Posted by fofo in asp.net, C#, Visual Studio 2008, Visual Studio 2010.
Tags: ,
add a comment

It is a very common request when designing an asp.net application, to set the focus on an asp.net control.

We can set the focus on an asp.net control

  • dynamically
  • declaratively

Some of the most common asp.net server controls we can set the focus on are:

  • TextBox
  • ListBox
  • RadioButton
  • CheckBox
  • Hyperlink

Let’s create an asp.net application with Visual studio

1) We fire the Visual Studio 2008-2010

2) We create an asp.net web site, from the available templates

3) We choose C# as a programming language

4) We drag and drop on the empty default.aspx the following controls

  • TextBox
  • HyperLink
  • Button

5) Leave the default names ( Button1, Hyperlink1, TextBox1 )

6) If we want to set the focus on the Hyperlink control

7) In the Page_Load event handler routine we can type the following

protected void Page_Load(object sender, EventArgs e)
{
if (HyperLink1 != null) HyperLink1.Focus();
}

8) So we just use the Focus method of the Hyperlink control
9) We can also set the focus on a web server control, by using the SetFocus() method of the Page control, by passing as a parameter in the SetFocus() method, the control ID.

This is how we transform the code snippet above

protected void Page_Load(object sender, EventArgs e)
{
if (HyperLink1 != null) Page.SetFocus(HyperLink1);
}

10 ) Another way to set the focus on a control (TextBox1) is to do so declaratively. In the default.aspx page we can write in the form tag

<form id=”form1″ runat=”server” defaultfocus=”TextBox1″>

11) Now we can add another page, Validation.aspx , and this can be a page where, someone can log in to our web site. have a look at the screenshot below. We have textboxes, radio buttons and a button.

12) We also add RequiredFieldValidator controls on the page and we associate them with the controls.

13) So if the validation fails, the focus will be set on the control that failed in the validation process ( e.g email ).

14) Have a look at the code below. The important property to look for is SetFocusOnError=”true”

<asp:requiredfieldvalidator id=”_firstNameValidator” runat=”server” width=”100%” InitialValue=”” ErrorMessage=”First name must be filled in.” SetFocusOnError=”true”
Display=”Dynamic” ControlToValidate=”_firstname” ValidationGroup=”SignUp”><img id=”Img1″ runat=”server” enableviewstate=”False” src=’~/images/oops.jpg’ />

Important Note:In order for the set focus on the controls to operate as above , the client side scripting on the browsers must be enabled.

If you need the source code, please email me at “info@nksolutions.gr”

Hope it helps!!!

Using the ASP.Net Calendar Control September 21, 2009

Posted by fofo in asp.net, C#, Visual Studio 2005, Visual Studio 2008.
Tags: , , , ,
1 comment so far

I have been using my blog to talk primarily about new things and enhancements in the .Net Framework. I have been talking about C# new features,VB new features, LINQ,Entity framework and the new Visual Studio 2010. The other day during a seminar I was asked about a very important ASP.NET 2.0 web server control, the calendar control. So I thought to write a post and look into this very useful control, presenting its basic functionality but also looking into the more advanced functionality it has.

So what is the calendar control.

A simple but powerful definition could be:

It allows the users to select a date or a range of dates withing an application

I will be using VS 2008 and C# to create a simple asp.net application.

1) Launch Visual Studio 2005 or 2008.

2) Create a new website and name it with a meaningful name, e.g CalendarSite

3) Drag and drop a Calendar control from the toolbox into the default.aspx page.Leave the default name

4) Let’s examine some of the most used properties.

SelectedDate: By setting this property to a value, you have this value-date selected in the calendar control. Set the value to a date and run your application

VisibleDate:Whenever we want to use a different month or year, when the control initially loads, we can set the VisibleDate property to a date

If you want to select any particular day just click on the hyperlink on the bottom of each day.

5) But what if we wanted to select all of the days of a particular week or all the days of a particulat month.

Then we need to look into another useful property of the Calendar control, the SelectionMode. For selecting all the days of the week, you can set its value to DayWeek.

For selecting all the days in a month, you can set its value to DayWeekMonth.

Run your application and you will see more selectors (arrows) in the calendar control. By clicking on them you will be able to select a whole week or month.

Some other very important properties are:

  • DayNameFormat , which allow us to change the number of letters the header day text contains
  • FirstDayOfWeek, which allow us to set the first day of the week to Monday if we want to

We have so many options to style the control by setting the values of properties like BorderColor,BordeWidth,BorderStyle,BackColor to the values we want. We can also set the values of various font properties. We can always use the smart tag(little arrow on the top right hand corner) to use one of the many predefined formatting styles for our calendar control.

Now that I have covered some of the basic stuff, I would like to mention

  • Calendar click events
  • Control Calendar cell’s rendering

6) Every time the user selects a date in you calendar control, you capture this selection by the SelectionChanged event.

Add a literal control to the default.aspx page. Name it SelectedDatesLiteral

Just double click on a day in the calendar control. In the event handling routine, type the following

foreach (DateTime selectedDate in Calendar1.SelectedDates)
{
SelectedDatesLiteral.Text = string.Format(“You selected: {0:d}<br/>{1}”, selectedDate, SelectedDatesLiteral.Text);
}

Here, I just loop through the selected dates and append their values to a literal control.Run your application and see for yourself.

7) If we want to add content in a day in the calendar, we must use  the DayRender event. This event is invoked once for every day in the calendar. The table cell and the date are passed to the event handler and can be used to render custom content or look up data in a database etc. We will pull event data from an xml file.Add an xml file to your project and call it events.xml. Place this file in the App_Data special folder. The contents of this file could be something like this

<?xml version=”1.0″ encoding=”utf-8″ ?>
<Events>
<Event Month=”1″ Day=”1″>Happy New Year.</Event>
<Event Month=”2″ Day=”29″>Happy leap day.</Event>
<Event Month=”12″ Day=”25″><![CDATA[Merry Christmas.]]></Event>
<Event Month=”12″ Day=”7″><![CDATA[Bob's Birthday!]]></Event>
<Event Month=”12″ Day=”28″><![CDATA[16th anniverary]]></Event>
</Events>

Add a XMLDataSource control in to your default.aspx page and configure it so it reads the contents of your xml file.

Then in the DayRender Event type the following

protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
string xpath = string.Format(“//Event[@Month={0} and @Day={1}]/text()”, e.Day.Date.Month, e.Day.Date.Day);
XmlDocument doc = XmlDataSource1.GetXmlDocument();

StringBuilder content = new StringBuilder(e.Day.DayNumberText);
foreach (XmlNode node in doc.SelectNodes(xpath))
{
content.Append(“<br/>”);
content.Append(node.Value);
}

e.Cell.Text = content.ToString();
}

Make sure you have added these namespaces in the Default.aspx.cs file

using System.Xml;
using System.Text;

I am using an XPath to filter out only the nodes in our xml document that have content.

Then I am opening the xml document and then I am building a string with values that will be displayed in the calendar cell for the current day.

Then I loop through all the items that were returned back from the XML document and append those values together in order to create a string of all of events that happend in this specific day.

Run your application and see the content that is passed from the xml file to the specific dates, e.g Christmas day.

If you need the full code, just email me.

Hope it helps!!!

Add to FacebookAdd to NewsvineAdd to DiggAdd to Del.icio.usAdd to StumbleuponAdd to RedditAdd to BlinklistAdd to TwitterAdd to TechnoratiAdd to Furl

Working with DAL (data access layer), BLL(Business Logic Layer) in asp.net web applications November 26, 2008

Posted by fofo in asp.net 2.0, C#, Sql Server, Sql Server 2005, SQL Server 2008, Visual Studio 2005, Visual Studio 2008.
Tags: , , , , , , , ,
14 comments

In this post I would like to show you step by step how to create a DAL and BLL for an ASP.NET web application.

Well, DAL stands for Data Access Layer and BLL, stands for Business Logic Layer.

We will use strongly Typed DataSets to create the DAL and class files to implement the BLL, which enforces the business rules of our application.

Many developers get puzzled when they come across these terms. I will try to explain these concepts to the best of my ability and I will show how easy is to implement these sort of layers with the tools we have in our disposal. I will also try to explain why we need to implement these layers when we develop a n-tier project that accesses a database.

The most common thing in web/windows development is to store data in a database. We write code to save the data in the database and write code to manipulate the data e.g to insert, update,delete data in the database.

Obviously for this example we will need a database. I will use the Pubs database. This is a well known database and many people are familiar with its schema.

In order to follow this example you need to download this database and attach it in your local instance of the SQL Server. You can download the Pubs database from this link.

If you need some help on how to install the database have a look here

You can download Visual Studio 2008 from here and SQL Server 2008 Express from this link.

It is for free!!! So I assume that by this point you have all the tools downloaded and installed. At this point you must have the Pubs database in the local instance of your SQL Server.

We will create the DAL first. But why we need a DAL? It is not a good idea-strategy (especially if we deal with a big-complex application) to have the data-specific logic put into the presentation layer.So it is wrong to write the ADO.NET code in the .aspx pages of our application. All the data related code should be in the DAL. From the presentation layer we should only make calls to the DAL for all data requests.

Let’s get started then…

1) Fire up Visual studio 2008/2005

2) Create a new ASP.Net web application using C# as the development language

3) Name your project as you wish

4) Go to the Server Explorer in Visual Studio, right-click on the Data Connections node, and choose Add Connection. This will bring up the Add Connection dialog box, where you can specify the server to connect to, the authentication information, and the database name.Have a look at the picture below.

addconnection

Click the OK button. After configuring the database,  the database will be added as a node underneath the Data Connections node. You can expand the node to explore its tables, views, stored procedures of the database.

5) We must add a Typed DataSet to our project. To do this, right-click on the project node in the Solution Explorer and choose Add a New Item. Select the DataSet option from the list of templates and name it Pubs.xsd.

See the  picture below.

add-dataset

Typed DataSets are a set of generated classes (generated by Visual Studio) that inherit directly from the DataSet family of classes.The members of these classes are strongly-typed according to the database schema.

A Typed DataSet is composed of strongly-typed DataTable instances which represents any of the underlying database tables. We need to create a DataTable for the Authors table. Besides having our table properties as objects inside the DataTable object we need to use the TableAdapter class so we can have the necessary methods to access the data from the table.

6) Navigate to the Pubs.xsd, drag and drop a TableAdapter class. The configuration wizard fires up.

See the picture below

wizard-1

7) Save the connection string to the web.config as suggested.

8) Click Next. Have a look at the picture below

wizard-21

In this step we define the query(using the first option-ad hod sql queries) that returns the columns from the table Authors that we want reflected in our DataTable. At the end of the wizard we’ll give a method name to this query.We will use this method to populate the strongly-typed DataSet.

9) Click Next and then from the Query Builder select the Authors table and click Add. We use the Query Builder to graphically construct the query. You must select all the fields from the Authors table. Have a look at the picture below.

wizard-32

10) Click Next. Have a look at the picture below

wizard-4

Rename the Return a DataTable section from GetData to GetAuthors.

We will use this method from our presentation layer to create and fill the DataTable and return it.

11) Click Next and then Finish. The wizard closed. If we go to the DataSet Designer we can see

  • The DataTable we just created, Pubs.authorsDataTable
  • The PubsTableAdapters.AuthorsTableAdapter and the methods (Fill() and GetAuthors())

See the picture below

dataset-designer

12) Switch to the Default.aspx and in the Page_Load event type the following lines of code.

PubsTableAdapters.authorsTableAdapter myadapter = new PubsTableAdapters.authorsTableAdapter();
Pubs.authorsDataTable myauthors;
myauthors = myadapter.GetAuthors();
foreach(Pubs.authorsRow authorrow in myauthors)
Response.Write(“Author: ” + authorrow.au_fname + ”  ” + authorrow.au_lname+  “<br />”);

13) As you can see in the first line we create an instance of our authorsTableAdapter.

Run your application and you will see all the authors.

14) Now we can bind the objects (data) contained in the DataTable to a Gridview web server control.Add a new page by adding a new item in your project.Name it GridviewDataTable.aspx.Set this page as Start Page.

15) Drag and Drop a Gridview control on the page. Leave the default name.

In the Page_Load event of this page type the following code

PubsTableAdapters.authorsTableAdapter myadapter = new PubsTableAdapters.authorsTableAdapter();
GridView1.DataSource = myadapter.GetAuthors();
GridView1.DataBind();

Run your application and you will see the results returned by the Authors table through the DataTable object in the GridView.

16) We need to select a specific row from the table Authors. In order to achieve that we need to create a new method that takes an argument. To create such a method, switch to the DataSet Designer and add a new query. Have a look at the picture below.

addquery

17) Click Next (Leave the first option selected). Click Next again, (Leave the first option selected)

18) Click Next in the wizard and add the following SQL statement

SELECT        au_id, au_lname, au_fname, phone, address, city, state, zip, contract
FROM            authors
where au_id=@au_id

Have a look at the picture below

sql

19) Click Next. In the Return a DataTable, change the name to GetAuthorByID and then click Finish.

20) In the DataSet Designer you will see the new method we just created.

21) Right-Click on this new method (GetAuthorByID) and select Preview Data. In the Preview Data windows type this “172-32-1176″ in the Value fields in the Parameters section. Click Preview.

22) Add a new page to your project. Call it GetAuthorsbyid.aspx.Set it as the Start Page

23) Run your application. In the web page you should see the following result

172-32-1176 White Johnson 408 496-7223 10932 Bigge Rd. Menlo Park CA 94025

24) Obviously we want to insert,update,delete rows in the table. We can do that by using the Insert(), Update(), and Delete() methods of our TableAdapter class that are already created for us.

Have a look at the image below

dataset-methods

25) To insert a new row in the Authors table, we switch to the GridviewDataTable.aspx (make it as a Start Page) and place a button on the page. Change the text property of the button to “Insert” (There is already a gridview in this page). Double click on the button and in the event handler routine type,

PubsTableAdapters.authorsTableAdapter myadapter = new PubsTableAdapters.authorsTableAdapter();
myadapter.Insert(“122-33-5667″, “Austen”, “Jane”, “33216321737”, “12 london street”, “London”, “SO”, “99029”, false);
GridView1.DataSource = myadapter.GetAuthors();
GridView1.DataBind();

Run your application and see the new row is inserted in the gridview and thus in the underlying table

26) Let’s try to update the record we just inserted. Just add a new button on the page. Change the text property of the button to “Update”. Double click on the button and in the event handler routine type,

PubsTableAdapters.authorsTableAdapter myadapter = new PubsTableAdapters.authorsTableAdapter();
myadapter.Update(“122-33-5667″, “Austen”, “Jane”, “33216321737”, “22 london street”, “London”, “SO”, “99029”, false, “122-33-5667″);
GridView1.DataSource = myadapter.GetAuthors();
GridView1.DataBind();

Run your application and see the row updated in the gridview and thus in the underlying table

27) Finally we will try to delete the row we inserted and updated in the previous steps.Just add a new button on the page. Change the text property of the button to “Delete”. Double click on the button and in the event handler routine type,

PubsTableAdapters.authorsTableAdapter myadapter = new PubsTableAdapters.authorsTableAdapter();myadapter.Delete(“122-33-5667″);
GridView1.DataSource = myadapter.GetAuthors();
GridView1.DataBind();

Run your application and see the row is deleted in the gridview and thus in the underlying table.

28) Now we will try to create a new functionality that does a mass update and not just updating a row like the previous example. We will implement the following scenario, for every author that lives in California (state=”CA” ) his contract will be valid (contract=true). Just add a new button on the page. Change the text property of the button to “Update multiple”. Double click on the button and in the event handler routine type,

PubsTableAdapters.authorsTableAdapter myadapter = new PubsTableAdapters.authorsTableAdapter();
Pubs.authorsDataTable myauthors;
myauthors = myadapter.GetAuthors();
foreach (Pubs.authorsRow author in myauthors)
if (author.state == “CA”)
author.contract = true;
myadapter.Update(myauthors);
GridView1.DataSource = myadapter.GetAuthors();
GridView1.DataBind();

29) Now I would like to move on and talk a bit about the BLL. We have covered enough on how to seperate the data access logic from the presentation logic.If we want to have certain business rules that define who is given the authority to do ( e.g delete,update authors) or that for certain states special discounts should be applied, a Business Logic Layer (BLL) that serves as an intermediary for data exchange between the presentation layer and the DAL must be implemented. I will implement the BLL as a  class file because we have one TableAdapter in the DAL. Inside this class we will have methods that map to the data access methods in the DAL.

30 ) Simply right-click in the Solution Explorer and then Add a New Item, and choose the Class template. Name the class BLLAuthors.cs. The first method we will create, is simply a wrapper method for the method GetAuthors() in the DAL and we will call it GetBLLAuthors(). We will create a second method which we will call GetBLLAuthorsByID. This method is still a wrapper method for the GetAuthorsByID in the DAL. In this first example I want to show you how to access the typed datasets of the DAL through BLL. We will see later, methods in the BLL that enforce business rules(which is the point of having a BLL). The code inside the BLLAuthors.cs is as following

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using DAL_BLL.PubsTableAdapters;
[System.ComponentModel.DataObject]
public class BLLAuthors
{
private authorsTableAdapter myAdapter = null;
protected authorsTableAdapter Adapter
{
get {
if (myAdapter == null) myAdapter = new authorsTableAdapter();
return myAdapter;
}
}
[System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Select, true)]
public DAL_BLL.Pubs.authorsDataTable GetBLLAuthors()
{
return Adapter.GetAuthors();
}
[System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Select, true)]
public DAL_BLL.Pubs.authorsDataTable GetBLLAuthorsByID(string authorid)
{
return Adapter.GetAuthorByID(authorid);
}
}

31) Create a new web page and name it GridviewBLL.aspx. Set this page as the Start Page.

Add a Gridview control on the page. In the Page_Load event of this page type,

BLLAuthors authorsall = new BLLAuthors();
GridView1.DataSource = authorsall.GetBLLAuthors();
GridView1.DataBind();

As you can see in the first line we create an instance of our BLLAuthors class which we defined in our BLLAuthors.cs file. It is evident from the code above that from the presentation layer (.aspx page) we access the BLL and then the BLL accesses the DAL, which eventually  “talks” to the database.

32) Let’s see a little example of our second wrapper method in our BLL. Add a button control to the page.Change the text property of the to “SelectSingleAuthor”. Double click the button. In the event handling routine type,

BLLAuthors singleauthor = new BLLAuthors();
GridView1.DataSource = singleauthor.GetBLLAuthorsByID(“172-32-1176″);
GridView1.DataBind();

Run your application. In the web page you should see the following result

172-32-1176 White Johnson 408 496-7223 10932 Bigge Rd. Menlo Park CA 94025

33) Let’s create a third method that applies this business rule (we used the same example in the DAL section),if  the state of the author is California “CA” then the contract should be true.

The code you should put in the BLLAuthors.cs is this

public bool UpdateAuthor()
{
DAL_BLL.Pubs.authorsDataTable authors = Adapter.GetAuthors();
if (authors.Count == 0)
return false;
foreach (DAL_BLL.Pubs.authorsRow authorrow in authors)
if (authorrow.state == “CA”)
authorrow.contract = true;
// Update the author record
int rowsAffected = Adapter.Update(authors);
return rowsAffected == 1;
}

Add a button control to the page.Change the text property of the to “UpDateState”. Double click the button. In the event handling routine type,

BLLAuthors upauthor = new BLLAuthors();
upauthor.UpdateAuthor();
GridView1.DataSource=upauthor.GetBLLAuthors();
GridView1.DataBind();

Run your application. In the web page you should see all records with state=”CA” to have the contract=”True

You could insert the code above in a Try-Catch Statement….

try
{
BLLAuthors upauthor = new BLLAuthors();upauthor.UpdateAuthor();
GridView1.DataSource = upauthor.GetBLLAuthors();
GridView1.DataBind();
}
catch (ArgumentException te)
{
Response.Write(“problem: ” + te.Message);
}

Hope it helps and happy coding!!!

If you need the source code feel free to email me. You can find my email in this page

Add to FacebookAdd to NewsvineAdd to DiggAdd to Del.icio.usAdd to StumbleuponAdd to RedditAdd to BlinklistAdd to Ma.gnoliaAdd to TechnoratiAdd to Furl

Using the wizard control in asp.net pages November 22, 2008

Posted by fofo in asp.net 2.0, C#.
Tags: , ,
1 comment so far

In this post I would like to talk a bit about a web server control that has been implemented back in the Asp.Net 2.0 Framework but for some reason even if it is very useful, many developers do not know how to use it and when to use it.  This is the Wizard control. Basically this control allow us to create a mechanism that requires the collection of data over a number of steps. You can do that with multiple pages but in this case you need to manage the state and the data between the pages.

This wizard contains a number of steps that are easiy configurable.

We will create a little asp.net application with C# to demonstrate the use of this control

1) Lanch VS and choose C# as your preferred language

2) Choose Asp.Net Web Application from the templates

3) Give your project a name

4) Place a wizard control from the Toolbox on the Default.aspx page. Leave the default name.Select the wizard control and click the smart tag (the arrow in the right-hand upper corner) and choose Auto format.

Choose a format of your choice from the available ones. You can always change the colors and fonts of a pre-decided format from the styles area of the properties window.

5) I know it is a little early but run your application.

You will see that you have Previous,Next and Finish buttons. Just click them and play around.

Close the page and in your default.aspx just select the wizard control.From the properties window, find the wizardsteps, Collection.

Click on the ellipsis and you will see a picture like the one below (in my case it has the complete steps)

wizard

In my example (because I work for a company that organises events on I.T) I have created a step-by step navigation scheme to create a feedback form.

In this window you can create as many steps you want and call them as you wish. Pay more attention to the StepType property.

After you finish adding steps, click the OK button.

Select the wizard control again. Click the smart tag (the arrow in the right-hand upper corner).

Select the step you want and drag and drop the controls you want onto this step. In my example I have a step called Name and i place a textbox control in this step. I follow the same pattern for all the other steps.

If you notice carefully  in the properties window you will see 2 properties CancelDestinationPageUrl, FinishDestinationPageUrl.

You can create 2 new .aspx pages and name them, Cancel.aspx and Finish.aspx.

In the Cancel.aspx write something like “you have chosen to cancel…”

In the Finish.aspx write something like “Thank you”

Then you just set the values of the above properties to the respective pages.

Now you can run your application and see all the steps(and in each step the controls you have added) you have created and click the Next and Previous,Finish,Cancel buttons on the wizard.

Hope everything makes sense and if you need the source code send me an email.

Add to FacebookAdd to NewsvineAdd to DiggAdd to Del.icio.usAdd to StumbleuponAdd to RedditAdd to BlinklistAdd to Ma.gnoliaAdd to TechnoratiAdd to Furl

The AdRotator web server control November 21, 2008

Posted by fofo in asp.net 2.0, C#, Sql Server 2005, VB 2005.
Tags: , ,
9 comments

Hello all,

I had some requests to write a post about the Adrotator control and how it can be used to serve up random banners in our web site.I thought that was a good idea and a great excuse to break away from the LINQ stuff…

I will demonstrate the use of this control with an example (C# version).I will use an XML file that will serve as the source for my banners.

The AdRotator control of course was included in the previous versions of Visual Studio and framework version, ASP.Net 2.0 to be exact.

1) Launch Visual Studio

2) Create a new project. More specifically choose C#, and from the templates ASP.Net Web application

3) Give a name to your project

4) From your toolbox just drag and drop an AdRotator Control in the Default.aspx page

5) Click on your project from the Solution explorer and create an Images folder

6) Place your images (i am going to use images of mine) in the folder above

7) Add a new item to your project. It will be an XML file. Name it “banner.xml”. It is a good idea to place it in the App_Data special folder that is already created in your project structure.

8) Copy and paste the following XML code inside the “bannel.xml” file.

<?xml version=”1.0″ encoding=”utf-8″ ?>
<Advertisements xmlns=”http://schemas.microsoft.com/AspNet/AdRotator-Schedule-File”&gt;

<Ad>
<ImageUrl>~/images/ajax-logo.gif</ImageUrl>
<NavigateUrl>http://www.asp.net/ajax/</NavigateUrl&gt;
<AlternateText>ASP.NET AJAX is a free framework for quickly creating efficient and interactive Web applications that work across all popular browsers</AlternateText>
<Keyword>asp.net ajax</Keyword>
<Impressions>100</Impressions>

</Ad>

<Ad>
<ImageUrl>~/images/asp-logo.png</ImageUrl>
<NavigateUrl>http://www.asp.net</NavigateUrl&gt;
<AlternateText>ASP.NET is a free technology that allows anyone to create a modern web site</AlternateText>
<Keyword>Asp.Net</Keyword>
<Impressions>150</Impressions>
</Ad>
<Ad>
<ImageUrl>~/images/NET-logo.png</ImageUrl>
<NavigateUrl>http://www.microsoft.com/NET/</NavigateUrl&gt;
<AlternateText>The .NET Framework is Microsoft’s comprehensive and consistent programming model for building applications </AlternateText>
<Keyword>.NET</Keyword>
<Impressions>250</Impressions>
</Ad>

</Advertisements>

If you want to find more about the attributes of the control and how we include them in the .xml file, have a a look here

Make sure you change the name of the images in the <ImageUrl> attribute to reflect the images you placed in the Images folder in your project.
9) Now select the AdRotaror control and from the properties window in VS select the property called AdvertisementFile .Click on the ellipsis button and navigate until you find the “banners.xml” file.

10) Run your application and hit F5 (refresh) many times from your keyboard to see all the banners specified in the .xml file appearing randomly according to their weight (Impressions attribute).

That is it folks!!! Congrats. you have your dynamic page displaying your feature banners.

If you want to enable some sort of filtering in your ads, you can do so.

If you place a DropDownlist control in your default.aspx page and add as items these names

  • asp.net ajax
  • Asp.Net
  • .NET

Enable AutoPostBack property for this control.By clicking on this control in the Default.aspx.cs,

you will be presented with the event handling routine for the standard event(SelectedIndexChanged).

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
AdRotator1.KeywordFilter = DropDownList1.SelectedItem.Value;
}

We set the property Keywordfilter of the AdRotator control to the value of the selected item from the list, thus selecting only the banners that match the keyword.

Run your application and choose different items from the dropdownlist . In my example there are 3 banners with 3 different keywords so only one banner will be shown every time you choose a different item.

I would like to show you how you can retrieve the ads if we have a Sql Server database as our source file.

1) First we need to create the database . Select the App_Data special folder and add a new item, a Sql Server Database. Call it banners.mdf.We need to create a table and we will call it ads

The definition for this table, for fields and data types could be

Field names Data type

id                    ->      int    -> primary key and identity column

ImageUrl         -> nvarchar(250) -> not null

NavigateUrl     -> nvarchar(250) -> not null

AlternateText  -> nvarchar(250) -> not null

keyword          -> nvarchar(50) -> not null

impressions    -> int -> not null

Populate the table with the following data (for 3 rows)

1st row

ImageUrl = ~/images/asp-logo.png
NavigateUrl=http://www.asp.net
AlternateText=ASP.NET is a free technology that allows anyone to create a modern web site
Keyword=Asp.Net
Impressions=150
2nd row

ImageUrl = ~/images/ajax-logo.gif
NavigateUrl=http://www.asp.net/ajax
AlternateText=ASP.NET AJAX is a free framework for quickly creating efficient and interactive Web applications that work across all popular browsers
Keyword=asp.net ajax
Impressions=100

3rd row

ImageUrl = ~/images/NET-logo.png
NavigateUrl=http://www.microsoft.com/NET
AlternateText=The .NET Framework is Microsoft’s comprehensive and consistent programming model for building applications
Keyword=.Net
Impressions=250

Now create a new .aspx page and make it the Start page.Name it as you want.

Place a new AdRotator control in the newly created page.

Now we must have a datasource control that points to the database we created and tie this datasource control with the rotator control.

Click on the little arrow in the rotator control and choose New Data Source, choose database from the window and then from the Configure DataSource window, select the banner database and click Next.

Then select the ads table and select all the fields from the table. Test the query and click Finish.

Run your application and see the ads to apper now from the database.

You can email me if you want the source code or leave a comment.

Hope it helps!!!!

Add to FacebookAdd to NewsvineAdd to DiggAdd to Del.icio.usAdd to StumbleuponAdd to RedditAdd to BlinklistAdd to Ma.gnoliaAdd to TechnoratiAdd to Furl

Follow

Get every new post delivered to your Inbox.

Join 1,788 other followers