CONTENTS OF THIS SITE

OUR OTHER CONTENTS

RECENT BLOG ENTRIES

Repeating a Try-Catch block

December 3rd, 2007 by comment Kris

Here’s a tip for beginners. You know how a try/catch block works: place some code inside a try, and if it fails, catch it with the catch block. But what do you do if you want to try an operation a set number of times, and then throw an exception if it’s still failing? There’s no such animal that is native in C#, but you can quickly implement one yourself. With a counter and a ref parameter, this can be done quite simply. This brief example will show you how.

Suppose we want to do some FooBar operation, but we know it could fail, due to some external circumstance, but we also know could work after the initial attempt or two. Let’s write the code to do 3 tries, and only then throw the error:

int MaxTries = 3;   //this is the limiter value - set this to the number of tries you want to execute
int NumTries = 0;   //this is our counter that keeps track of how many tries we've executed

//Perform the FooBar operation(we retry 3 times and if we don't succeed, the exception will be caught and handled)
while (NumTries < MaxTries)
               throw (err);           

private void FooBar(int foo, int bar, ref int numTries)
        {
            try
            {
                //count the try
                numTries++;

                //set up & and perform your operation
                Foo(bar);
                Bar(foo);
                DoFinalOp();

                //if we got here, there was no error so set counter to kick us out of loop
                numTries = MaxTries;
            }
            catch (Exception err)
            {
                //only throw error if we've tried enough times
                if (numTries >= MaxTries)
                    throw (err);
            }

        }

Note that our FooBar method takes a ref parameter of numTries. When we change this value in the method, and the method returns, the counter will have been changed, for re-testing in the while loop clause.

Let’s walk through this and see how it works:

  • After setting NumTries and MaxTries (to 0 and 3), we hit the while loop. This first time, NumTries is definitely less than MaxTries, so we execute FooBar().
  • When we enter FooBar(), the first thing we do is increment tries, to count the attempt. Since this is a ref parameter, changing this local variable tries also ends up changing the global variable NumTries.
  • Then we start executing whatever we have to do in FooBar(). If an error is encountered at this point, we’ll fall to the catch block.
  • In the catch block, we test whether or not to throw an error, based on the value of tries. Since at this point, tries = 1, we don’t throw the error, FooBar() finishes executing and we return to the while loop.
  • Back in the while loop, we retest NumTries to see if it’s still less than MaxTries. Since we incremented it in the method, NumTries is now equal to 1, but this is still a true condition, so we call FooBar() again.
  • Once again inside FooBar(), we increment tries by 1 and try our operation. Suppose this time, it succeeded. In that case, we will reach the line: tries = MaxTries and then exit the method.
  • Now, back in the while loop, the test (NumTries &lt MaxTries) is false, so we don’t execute FooBar() again, and we’re done.

Voila! We’ve implemented try/catch/repeat functionality, allowing us multiple tries before throwing an error.

ˆ Back to top

C#.NET Data Binding Basics

October 17th, 2007 by comment Alex

Binding data from windows controls to objects is easy in C#.NET.  Here is a basic introduction: 

Step one:

Create a class named Employee in C# and add a get property for each field you want to bind to a windows control.

public string getLastName {

      get { return mStrLastName; }

} 

Add a set property for any fields that you want two-way binding to occur. For example:

public string firstName {

      get { return mStrFirstName; }

      set { mStrFirstName = value; }

} 

Step two:

Add a form to your project and throw some controls on the form.  For this example, add a list box and a textbox. Also, create an array of objects that you want to bind to this list box.

arrayOfEmployees = new ArrayList();

arrayOfEmpoyees.Add(new Employee(”Doe”,”John”,”SoftwareEngineer”,”ServerTeam”));

arrayOfEmployees.Add(new Employee(”Smith”,”Jane”,”SoftwareEngieer”,”ClientTeam”));

Step three:

Bind the data from the object to the list box and textbox

listBoxLastName.DataSource = arrayOfEmployees;

listBoxLastName.DisplayMember = “getLastName”;

txtBoxForFirstName.DataBindings.Add(”Text”, arrayOfEmployees, “getFirstName”);

Step four:

Run the project and notice that the data is bound to the list box and the textbox. 

First, notice that the textbox is an example of two-way binding.  If a user changes the values in the textbox then the object is updated with a new first name.  To change this to one-way binding, just remove the set property from the object bound to the textbox.

Secondly, simple binding is done to controls like textboxes that only have one possible value.  Complex binding is done to controls like list boxes, that have multiple values to display at once. 

This example shows both simple and complex binding as well as one-way and two-way binding. More advanced data binding topics in C#.Net Visual Studio 2005 would cover the DataGridView class.

Cheers,

alex

ˆ Back to top