Thursday, June 19, 2008

Passing viewstates of a page to another page

Download the source code

Sometimes we need to pass information of one page to the next page to do this there are different approaches one of them is that you can pass just a querystring then lookup data in your data source. However sometimes there are no data sources so you need to have all states of one page in another page. So you may use Session object to pass this information. However, this may not be the best way because you are using Session object which is shared between different pages for a user. There is another way which is PostBackUrl.(In next posts I will compare State Management in asp.net)

How to pass viewstate by PostBackURL

After Visualstudio 2005 all our buttons has a nice properties called PostBackUrl which can be assigned to a page then state of this page (the page that has button with PostBackUrl) will be passed to Next page.

Take a look at this:

In this example we have a textbox and a dropdownlist and we need to see state of these two controls in next page. Also we have a button that its PostBackUrl is set to a page. When user click on this button the state is passed to next page to access these states you need to use PreviousPage object. Remember if someone tries to access this page by giving this page address into browser or user is redirected from other redirection method Then PreviousPage object is null. So to be in safe side always check this object. Take a look to this code:

if (PreviousPage != null)

{

DropDownList lst = PreviousPage.FindControl("DropDownList1") as DropDownList;

if (lst != null)

LabelDropdown.Text = lst.Text;

TextBox txt = PreviousPage.FindControl("TextBox1") as TextBox;

if (txt != null)

LabelTextbox.Text = txt.Text;

}

As you see in the code we are checking PreviousPage object so we are sure that previous page state is passed to this page it means that redirection method was PostBackUrl.

Also we have another method to make controls type safe which is defining PreviousPageType Directive (in html code) but the issue with this approach is that you can define one page as your previous page. Also if user access to this page with any other of redirection method then an error will be generated. So I highly recommend you use the previous approach and never user PreviousPageType directive.

Let's see the steps:

1- Define a page with a button which its PostBackUrl is filled with a page ( we call it target page)

2- In Target page Use PreviousPage.FindControl to access controls in previous page.

3- Always check PreviousPage object to be sure it is not null

Download the source code

Wednesday, June 18, 2008

Control structures in C#

These structures are as follows:

if (expression)

{

statement1...[n]

}

elseif (expression)

{

statement1...[n]

}

.

.

else

{

statement1...[n]

}

Please pay attention to logical operators && and while using then as a expression in if structure because as we explain earlier they won't check the second operand if the first one fulfill the condition.

while (expression)

{

statement1...[n]

}

do

{

statement1...[n]

} while (expression);

In comparison between while and do while , do while will execute the statement at least once.

To explain for stucture we can express an example to clarify it.

for (int i = 1; i < 10;i++ )

{

Console.WriteLine(i);

}

Another control structure is for each. But before we go through it, we should know what arrays are. That's because for each is used only with a of collection entities, collection of data types.

Structure of foreach is as bellow.

foreach (collectionDataType varName in collectionName)

{

statement1…[n];

}

It means that each item in collection will be assigned to varName then the code in the block will be run for varName.

Array

Arrays are of those kinds of variables that are placed in heap memory.(go to first lesson, memory management)

Array is a collection of specific data type. Let's have an example to understand both for each control structure and arrays.

int[] nums = new int [3];

nums[0] = 10;

nums[1] = 15;

nums[2] = 20;

int sum = 0;

foreach (int n in nums )

{

sum = sum + n ;

}

Console.WriteLine("The summary is :{0}" ,sum);

In above code each item in nums is assigned to n and then the code in the block will be run for each item.

Break and Continue

It's time now to talk about break and continue. Remember that, these two statements are using in loop structures. Like for, while, do while and …. Let's see the usage of them in an example.

If you run the following code snippet you will see that when i =5 the code will stop. It means although i is less that 100 but the rest of code won't execute.

for (int i = 1; i < 100; i++)

{

if (i%5 == 0)

{

Console.WriteLine("Hope!");

break ;

}

Console.WriteLine(i);

}

The result will be as follow

Figure 4

But if you change the code like this:

for (int i = 1; i < 100; i++)

{

if (i%5 == 0)

{

Console.Write Line("Hope!");

continue ;

}

Console.WriteLine(i);

}

Instead of each number that is dividable to 5 the word "Hope" will be printed. The result of running the above code snippet is shown in figure 5

Figure 5

Note: You are not allowed to change the value of the counter in the foreach control structure. This is a read only value. It means you can not change the value of i in the code above.

GoTo:

Probably no other construct in programming history is as maligned as the goto statement. The problem with using goto is use of it in inappropriate places.

The structure of goto is

goto lableName;

lableName:

Statement1…[n];

It is hardly recommended to use goto because it reduces the performance of the application, except in some cases that it will increase the performance. Using goto in nested loops that break can't help you will be very handy.

Switch case

Another control structure is switch with the following structure

 switch (expression)
{  
   case constant-expression:
        statement
        jump-statement
    case constant-expressionN:
        statementN
    [default]
}

In this structure as you can see if you write even one statement you should have a jump-statement that can be break or got otherwise you as a programmer will face an compile time error indicating that you lost a jump-statement. Don't forget to define break in default case. Let's explain the structure in a sample code.

Console.WriteLine ("Enter 10,20 or 30");

int a = Convert.ToInt32 ( Console.ReadLine());

switch (a)

{

case 10:

case 20:

Console.WriteLine("I have more than {0} books", a);

break;

case 30:

Console.WriteLine("I have {0} books", a);

break;

}

In this case you won't get a compiler error because of not having break in the first case statement. The reason is you don't write any code for that specific case statement. This means compiler will execute codes till it arrives to a break or goto. If a user enters 10 as the value or 20 he will receive similar out puts.

But what if you want the compiler execute first and second statements that are in case 10 and 20 if user_entered_value is 10 and execute statement in second case if user_entered_value is 20. You simply can modify the code as bellow using goto.

Console.WriteLine ("Enter 10,20 or 30");

int a = Convert.ToInt32 ( Console.ReadLine());

switch (a)

{

case 10:

case 20:

Console.WriteLine("I have more than {0} books", a);

break;

case 30:

Console.WriteLine("I have {0} books", a);

break;

}

please pay attention to the out put with different entered_values.

Figure 6- User entered 10

Figure 6- User entered 20

"Thanks To Azadeh for writing this post"