Windows Phone Developers

Thursday, September 22, 2011

Threading in .NET/C# - How to get Thread Details

How to Execute a process in separate thread in VB.NET/C#

This was one of my favorites - Threading; but somehow I ignored for long. Now let us delve into it

Let us execute some small piece of code (a definite loop) through normal method and with the help of threading. Normal methid

private void ThreadExampleSync()
        {
            for (int iCnt = 0; iCnt < 3; iCnt++)
            {
                for (int j = 0; j < 100; j++)
                {

                    for (int j1 = 0; j1 < 9000000; j1++)
                    {

                    }
                }
                Console.WriteLine("Iteration {0} is executed by {1} at {2}", iCnt.ToString(), Thread.CurrentThread.ManagedThreadId.ToString(), DateTime.Now.ToString());
            }
        }
When we move to threading let us take the looping part into a separate method and call the method using different Threads
private void ThreadExampleAsync()
        {
            for (int iCnt = 0; iCnt < 3; iCnt++)
            {
                var t1 = new Thread(ExecuteTasks);
                t1.Start(iCnt);
            }
        }


        private  static void ExecuteTasks(object iInput)
        {
            for (int j = 0; j < 100; j++)
            {

                for (int j1 = 0; j1 < 9000000; j1++)
                {
                    //nothing

                }
            }
            Console.WriteLine("Iteration {0} is executed by {1} at {2}", iInput.ToString(), Thread.CurrentThread.ManagedThreadId.ToString(), DateTime.Now.ToString());
        }

Since we are calling new thread for each iteration - ExecuteTasks gets executed by different threads as shown below

The time taken when we use different threads is faster than the synchronous way. However, care must be taken in Threading to avoid excess memory usage/leakages Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

Tuesday, September 20, 2011

Argument 1: cannot convert from 'method group' to 'System.Threading.ThreadStart'

The best overloaded method match for 'System.Threading.Thread.Thread(System.Threading.ThreadStart)' has some invalid arguments

These errors occur when the Method that is called has parameters other than object. The compiler expects the signature to take object

var t1 = new Thread(ExecuteTasks);

will throw an error if the method signature is like this

private  static void ExecuteTasks(int iInput)

The following one is acceptable

private  static void ExecuteTasks(object iInput)
Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

Friday, September 16, 2011

VB.NET / C# - How to Check if OS is 64-Bit or 32-Bit

The following snippet gives a hint :

        private void GetOSConfig()
        {
            string sProcess;
            if (Environment.Is64BitOperatingSystem  == true )
            {
                sProcess = "64 Bit";
            }
            {
                sProcess = "32 Bit";
            }
            Console.WriteLine("OS is {0}", sProcess  );
        } Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

How to Pass Multiple/Variable Parameters to a Function/Method in C#/.NET

C#/VB.NET Function with dynamic parameters / How to make a function accept infinite number of arguments

Normally a method has a definite number of parameters and they are passed from the calling method. What if you are not sure of the number of parameters or want to be flexible in that. A Simple example can be a Adding machine - which adds any numbers sent .

It is possible to achieve that with params keyword -

private void AddAsManyNumbersAsUCan(params int[] numbers)

{

int iTotal = 0;

foreach (int i1 in numbers)

{

iTotal += i1;

}

Console.WriteLine("Sum of {0} numbers added to {1}",numbers.Length ,iTotal);

}

The above method accepts any number of arguments (provided they are of the same type). The method can be called like:

AddAsManyNumbersAsUCan();

AddAsManyNumbersAsUCan(1,2,3);

AddAsManyNumbersAsUCan(100,-1,23,2121,4562);
Will give the following output




You can change the type of the parameter to a generic one - List etc to have a broader use 
Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

Thursday, September 15, 2011

VB.NET FindControl in Windows forms application

How to loop through windows form controls by name (C# / VB.NET)

ASP.NET dev have the advantage of FindControl, which does this work quite easily. For Windows forms developers the need to loop through the controls using ForEach in the control collection or can use the Find method as shown below:

foreach (Control ctl in Controls.Find("textBox" + i, false))

{

string stext = ctl.Text ;

};


Here we have used ControlCollection Controls.Find method to refer a Textbox and get the value Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

String Comparison (case sensitive and case-insensitive) in C#/VB.NET

How to IgnoreCase in C#/VB.NET String Comparison

Whether you like or not, life revolves around comparison . Here let us see how to compare two strings using Equals method.

Equals method takes two arguments - the string to be compared and the comparison type (Case Sensitive or Insensitive)

The following snippet gives a hint of both:


        private static void StringCompExample()
        {
            string s1 = "MulTIpleCASE";
            string s2 = "MultipleCase";

            bool compare_result = false;

            //case sensitive comparison
            compare_result = s1.Equals(s2);
            Console.WriteLine(compare_result.ToString ());
           
            //case insensitive comparison
            compare_result = s1.Equals(s2, StringComparison.InvariantCultureIgnoreCase);
            Console.WriteLine(compare_result.ToString());
           
        }
Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

How to Remove Alternate/Extra Text (Text within Parenthesis) using VB.NET/C#

How to Remove Text within Brackets/ Braces using VB.NET/C#

Regular expressions come handy when we have this kind of requirement. Regex.Replace method can be used remove the unwanted text

        private static void RemoveTextWithinParens()
        {
            string pattern = @"\([^\(\)]+\)";
            string interesting_string = "SOMETHING (#2) and some more rhing (#3 inside braces)";
            Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase);
            MatchCollection matches = rgx.Matches(interesting_string);
            string removed_String = rgx.Replace(interesting_string, "");
        }

Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

Wednesday, September 7, 2011

How to Convert Textboxes to Array/List in VB.NET/C#

Array of Textboxes using VB.NET/C# / Loop through Textboxes in VB.NET

Here is a simple code that loops through all the controls on a Windows form and Appends the Array/List with the values

Sub GetTextBoxValues()

        Dim arTextBoxVal() As String
        Dim arTBCnt As Integer = 0
        Dim ListTB As New List(Of String)

        For Each ctlText In Me.Controls
            If TypeOf ctlText Is TextBox Then
                ReDim Preserve arTextBoxVal(arTBCnt)
                arTextBoxVal(arTBCnt) = DirectCast(ctlText, TextBox).Text
                ListTB.Add(DirectCast(ctlText, TextBox).Text)
                arTBCnt += 1
            End If
        Next

    End Sub
Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

How to create DataTable on the fly and add Rows (data) using VB.NET/C#

How to Populate DataGridView on the fly using VB.NET

Not all data come from a database table; at times we need to create in on the fly.

Here is a situation that warrants that - we create a datatable and then create appropriate data columns

Dim oDataTable As New DataTable("BookingInfo")
        
        oDataTable.Columns.Add(New DataColumn("PassengerName"))
        oDataTable.Columns.Add(New DataColumn("JourneyDate"))
      ...
  

Then data row is created and added to the table

oDR = oDataTable.NewRow
        oDR("PassengerName") = "Dhuvaraga Prasath Mohanram"
        oDR("JourneyDate") = Now.ToString()
        oDR("Source") = "Chennai"
        oDR("Destination") = "Nellore"

        oDataTable.Rows.Add(oDR)

This can be continued till all rows are added;

DataGridView is then bound to the datatable using DataSource property

DataGridView_BookingInfo.DataSource = oDataTable
        DataGridView_BookingInfo.AutoResizeColumns()

Which gives you the screen below


Sub CreateOnTheFlyDataTable()

        Dim oDataTable As New DataTable("BookingInfo")
        Dim oDR As DataRow

        oDataTable.Columns.Add(New DataColumn("PassengerName"))
        oDataTable.Columns.Add(New DataColumn("JourneyDate"))
        oDataTable.Columns.Add(New DataColumn("Source"))
        oDataTable.Columns.Add(New DataColumn("Destination"))

        oDR = oDataTable.NewRow
        oDR("PassengerName") = "Dhuvaraga Prasath Mohanram"
        oDR("JourneyDate") = Now.ToString()
        oDR("Source") = "Chennai"
        oDR("Destination") = "Nellore"

        oDataTable.Rows.Add(oDR)

        DataGridView_BookingInfo.DataSource = oDataTable
        DataGridView_BookingInfo.AutoResizeColumns()

    End Sub
Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

Tuesday, August 30, 2011

How to count a string within another string in VB.NET/C#

How to get number of given string using C#/VB.NET

After a lull I wanted to start somewhere; here is what I got for now (thanks to Arivuchutarji who initiated this debate).

We have come across many situations where we need to count a string within other.

There are three ways to do (infact two)

1. Linq
2. A Do While loop using IndexOf
3. Regular Expressions

Here is the LINQ one - it applies to characters and not strings (appreciate if someone could post searching a text within a string)

        Dim sCollection As String
        sCollection = "this is a string with some text repeated and some not"
        Dim count As Integer
        count = (From sText In sCollection
                         Where sText = "s"
                         Select sText).Count

The second one appears primitive - but a foolproof method

        Dim cntStr = -1, i1, iStart As Integer
        Dim searchString As String
        searchString = "some"
        Do While i1 <> -1
            i1 = sCollection.IndexOf(searchString, iStart)
            iStart = i1 + 1
        Loop

And finally, my favorite regular expressions - code is clean if you use this

        cntStr = RegularExpressions.Regex.Matches(sCollection, "some").Count

Appreciate your comments on this Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

Tuesday, June 21, 2011

How to Change Permission of Folder in Visual Basic / C#

VB.NET Set Folder Permission / C# Set Folder Permission


In this snippet we create a new directory and set the permission of it to Fullcontrol using ACL.

private static void ChangePermissionOfDir()
        {
            //Folder
            DirectoryInfo NewDir = Directory.CreateDirectory(@"C:\Temp\Te21");

            DirectorySecurity dSecur = NewDir.GetAccessControl();

            FileSystemAccessRule fAccess = new FileSystemAccessRule("Everyone",FileSystemRights.FullControl,AccessControlType.Allow  );


            dSecur.AddAccessRule(fAccess);

            NewDir.SetAccessControl(dSecur);
 
    
        }
Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

How to Convert a String to Array of Characters

The following snippet converts a string to a Character Array using CharArray

private static void String2CharArray()        {
            string s1 = "This is a string";
            Char[] ArrayofChars;
            ArrayofChars = s1.ToCharArray();
            Console.WriteLine(s1);
            foreach (char c1 in ArrayofChars)
                Console.WriteLine(c1);
        }
Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

Thursday, June 9, 2011

Queue in C# / Add and Remove items from Queue in C# (.NET)

Queues are common in real world - Flight checkins to School. Here is the way you can use it in C#

private static void CustomerServiceQueue()
        {
            Queue CSQ = new Queue();

            CSQ.Enqueue("Gautam");
            CSQ.Enqueue("Nargis");
            CSQ.Enqueue("Beth");
            CSQ.Enqueue("Slobodan");

            Console.WriteLine("Peeking Queue: {0}", CSQ.Peek());

            Console.WriteLine("Check if CSQ Contains Beth : {0}", CSQ.Contains("Beth"));

            while (CSQ.Count > 0)
            {
                Console.WriteLine(CSQ.Dequeue());
            }
           

        }

Contains checks for presence of the given object in the queue. Peek returns the first element from the queue

Dequeuue does the same as Peek, however, it also removes the object Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

Tuesday, June 7, 2011

How to Override ToString Method in C# (VB.NET)

Customize ToString Method in C# (VB.NET)

Overriding ToString Method has its own advantages.

For example, the following class has four fields

public class ClassExec
    {
        string _Name;
        
        public string Name
        {
            get { return _Name; }
            set { _Name = value ;}
        }

        public string Source
        {
            get;
            set;
        }

        public string Destination
        { get; set; }

        public DateTime  DOT
        {
            get;
            set;
        }

If you try to use the ClassExec.ToString() method it will return the fully qualified Class name as default. This doesn't help us much.

Instead let us override the ToString method to return the four fields in a formatted way

public override string ToString()
        {
            return (Name + ' ' + Source + ' ' + Destination + ' ' + DOT);
        }

The following code will now produce the desired output:

ClassExec cls = new ClassExec();
            cls.Name = "Jackob Johnson";
            cls.Source = "Socchi";
            cls.Destination = "Moscow";
            cls.DOT = DateTime.Parse("12-Jan-2012");

            Console.WriteLine(cls.ToString());

Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

System.Xml.Serialization.XmlSerializer.XmlSerializer() is inaccessible due to its protection level

One reason for this error is if you haven't mentioned the type when you initialize the XmlSerializer object

XmlSerializer Xser = new XmlSerializer()

can be replaced with

XmlSerializer Xser = new XmlSerializer(this.GetType() );
Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

Sunday, June 5, 2011

How to CreateFolder in C# (.NET) / How to Create a Directory in C# (VB.NET)

How to check if a directory exists in C# / How to check if a folder exists in C#

Many times backups are created in a new folder with name as date etc. The following snippet checks if directory exists in the particular path and creates it

private static void CreateFolder()
        {
        //This example creates a new folder under MyDocuments

            string folderName = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            string userName = Environment.UserName;

            folderName = Path.Combine(folderName, userName);

            if (Directory.Exists(folderName) == false)
            {
                Directory.CreateDirectory(folderName);
            }


        }

How to combine two paths in .NET

The example combines two paths using Path.Combine method.

See also:

Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

Sunday, May 29, 2011

ForEach Loop in Array (C# / VB.NET)

How to iterate elements of Array using ForEach in .NET (C#)

Here is a simple example of that:

string[] arString = null;
            arString = new string[2];
            arString[0] = "First Element";
            arString[1] = "Second Element";
            foreach (string s1 in arString)
            {
                Console.WriteLine(s1);
            }
Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

Wednesday, May 25, 2011

How to Write Padded (Formatted) Text File using VB.NET/C#

Writing Equi-Spaced Output using C# and VB.NET

Here is a small code to write a multiplication table.

For i1 As Integer = 1 To 20

Console.WriteLine(i1.ToString & " x 12 = " & (i1 * 12).ToString)

Next i1




Have you ever thought it would be better to have it properly aligned. Then use the Padding options (PadeLeft here) to format the output



Private Sub WritePaddedText()

        ' Write a Padded Multiplication Table
        For i1 As Integer = 1 To 20
            Console.WriteLine(i1.ToString.PadLeft(2) & " x  12 = " & (i1 * 12).ToString.PadLeft(3))
        Next i1
    End Sub


See also :How to Create Equispaced Text File using VBA; Spacing in Text Files Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

Unable to copy file "obj\x86\Debug\*.exe" to "bin\Debug\*.exe". The process cannot access the file 'bin\Debug\*.exe' because it is being used by another process.

To release the file go to the Task Manager and see if the Exe is running in the process Tab. Kill the process and Build the project it should work.

But before that make sure why the Exe was still running in the process even after the application is termninated. It might be due to some malperformance of garbage collection Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

Tuesday, May 24, 2011

VB.NET How to Resize the form along with Controls

Windows Form - Resize Controls Dynamically using VB.NET

There would be many occasions you would have come across the need to resize the form to fit some controls/text etc. In the following example we use the combination of LinkLabel and Panel Control to achieve that

Here is the sample form

This is how it needs to be expanded to accomodate the additonal information

I have used a '+/-' hyperlink (LinkLabel Control) to resize the form. (For more info on Link Label : Hyperlink Control in Windows Forms (VB.NET) Application). You can use >> or << etc to be more clear

The controls for Year Founded and Financial Performance are enclosed in a Panel

Add the following code to the LinkClicked event of the LinkLabel

If Panel1.Height = 0 Then
            Panel1.Height = 110
            Me.Height = Me.Height + 110
        Else
            Panel1.Height = 0
            Me.Height = Me.Height - 110

        End If


The form gets re-sized on clicking the hyperlink (it actually toggles)

See also : How to Get Width and Height of Desktop Screen using C#/VB.NET Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

Sunday, May 15, 2011

Hyperlink Control in Windows Forms (VB.NET) Application

How to use Hyperlinks on WinForms (VB.NET)

Create a small Windows Forms like the one below and add LinkLabel Control on the form:


Add the following code to the LinkLabel's LinkClicked event:

Private Sub LinkLabel1_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles LinkLabel1.LinkClicked
        System.Diagnostics.Process.Start("www.google.com")
    End Sub


This will open the website in a new IE window Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

How to find Difference between two time (Dates) using VB.NET

Difference between two different dates using VB.NET

DATEDIFF function will come handy to find the difference between a set of dates. The snippet given below gets the difference in seconds

Private Sub DateDiffExample()

        Dim dt1 As Date = New Date(2011, 5, 15, 10, 11, 2)
        Dim dt2 As Date = New Date(2011, 5, 15, 10, 12, 22)

        Dim dt3 As Long = DateDiff(DateInterval.Second, dt1, dt2)

    End Sub

You can tweak a bit to get for Minutes or Hours etc by

Private Sub DateDiffExample()

        Dim dt1 As Date = New Date(2011, 5, 15, 10, 11, 2)
        Dim dt2 As Date = New Date(2011, 5, 15, 10, 12, 22)

        Dim dt3 As Long = DateDiff(DateInterval.Minute, dt1, dt2)

    End Sub

Other useful links:

Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

Changes are not allowed while code is running or if the option 'Break all

If you are getting this error while editing the code, check if the Break all process option is enabled.


If Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

Saturday, May 14, 2011

How to get number of Sundays/Saturdays in a given month using (C#/VB.NET)

Retrieve No of Fridays for the Current Month.

If you come across a situation where you need to know the number of Fridays/Sundays etc for a given month you can use the following snippet.

private void NoOfSpecificDaysThisMonth()
        {
            int iDayCnt = 4; // Defaults to four days
            DayOfWeek dw = DayOfWeek.Wednesday;
            
            DateTime firstDay = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
            int iRemainder = DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month) % 7;

            if ((dw >= firstDay.DayOfWeek) & ((dw - firstDay.DayOfWeek) < iRemainder))
                {
                     iDayCnt = iDayCnt+1;
                }
                else
                    if ((dw < firstDay.DayOfWeek) & ((7+ dw - firstDay.DayOfWeek) < iRemainder))
                {

                    iDayCnt = iDayCnt + 1;
                }
            
            MessageBox.Show(iDayCnt.ToString());
        }

The above gives the No Of Wednesdays for the Current month. If you want for any specific month / year you can tweak it a bit like:


DateTime firstDay = new DateTime(2012, DateTime.Now.Month, 1);
            int iRemainder = DateTime.DaysInMonth(2012, DateTime.Now.Month) % 7;

Other links that might be relevant:

Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

Select Case Statement in C# / C-sharp

Switch Case Statement in C# (.NET)

Here is an example of Select Case like construct using C#:

private string ShirtSizes(int ShirtSize)
        {
            switch (ShirtSize)
            {
                case 36:
                    return "Small";
                case 38:
                    return "Medium";
                case 40:
                    return "Large";
                case 42:
                    return "Extra Large";
                case 44:
                    return "XXL";
                default:
                    return "Free Size";
             }

        }

Fall-Thru in Switch Case Statement in C#(Csharp)

Fall through can be achieved as follows:

switch (ShirtSize)
            {
                case 34:
                case 35:
                case 36:
                    return "Small";
                case 38:
                    return "Medium";
... 

The Switch construct requires jump statements like GoTo or Break to transfer control outside the loop. Else it will throw an Error Control cannot fall through from one case label ### to another

To avoid this use break / goto statements. On the other hand if you use more than one jump statement for a case - like the one shown below - you will get Unreachable code detected warning

case 38:
                    return "Medium";
                    break;
             
Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

Wednesday, May 11, 2011

Control cannot fall through from one case label - Switch Statement (C#/CSharp)

This error occurs when there are no jump statement in the switch. Like the following

switch  (sDayName.ToUpper () )
            {
                case"1":
                    MessageBox.Show("One");
                case "2":
                    MessageBox.Show("Two");
        }

A break or goto statement should solve the problem

switch  (sDayName.ToUpper () )
            {
                case"1":
                    MessageBox.Show("One");
                    break;
                case "2":
                    MessageBox.Show("Two");
                    goto default;
...

Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

Tuesday, May 10, 2011

Mod Functon in C# (Csharp)

Mod Operator in C#

Here is the code for Mod function in C#. Have given two ways. The first one is the C % operator

private void ModFunctionCsharpExample()
        {
            int iRemainder = 31 % 3;
            MessageBox.Show("Remainder is " + iRemainder.ToString());

            int iQuotient = Math.DivRem(31, 3, out iRemainder);
            MessageBox.Show("Remainder is " + iRemainder.ToString() + " and the Quotient is " + iQuotient);
        }

Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

Sunday, May 1, 2011

Form's Keydown Event not Firing in VB.NET

How to enable Keydown, Keypress events for Windows forms (.NET)

If the Keydown, Keypress events etc are not fired in WinForms application, check if the KeyPreview is set

Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

How to use Function Keys in VB.NET Windows Application





Capture Function Keys in VB.NET Windows Application

The following snippet might help you in capturing the Function Keys (F1 to F12) in a VB.NET application

Private Sub frmWinSamAppMain_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
        ' -- Sample Code for http://DotNetDud.BlogSpot.com
        Select Case e.KeyCode
            Case Keys.F1
                MessageBox.Show("Help is on the way")
            Case Keys.F5
                RefreshMethod()
            Case Keys.F9
                MessageBox.Show("You have pressed F9")
        End Select
    End Sub
Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

How to Bind an Object to TextBox

Binding Objects to Windows Form Controls

Here is a simple example to bind a object to textbox control

Let us have a small form with two Textboxes, a label and a button



We also have a class that has two properties - Name of Company and the Business they are involved. Here is how the class looks

Public Class ClassDataBind

    Private sPrvName As String
    Private sOfferings As String

    Public Sub New(ByVal sName As String, ByVal sOffer As String)
        Me.Name = sName
        Me.Solutions = sOffer
    End Sub

    Property Name() As String

        Get
            Return sPrvName
        End Get

        Set(ByVal value As String)
            sPrvName = value
        End Set

    End Property


Let us now Bind the class to the text boxes using

Private Sub FormDataBind_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        oDataBind = New ClassDataBind("Accenture", "Consulting")

        TextBox1.DataBindings.Add("Text", oDataBind, "Name", True, DataSourceUpdateMode.OnPropertyChanged)
        TextBox2.DataBindings.Add("Text", oDataBind, "Solutions", True, DataSourceUpdateMode.OnPropertyChanged)
    End Sub


Once the binding is done , run the code to view how it looks :


Since the text boxes are bound to the Objects and we have set the Objects to be refreshed we can change the contents in textboxes and see if the Objects are refreshed.

Private Sub ButtonClicked(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        Label1.Text = oDataBind.Name + " - " + oDataBind.Solutions
    End Sub


You can now save the object back to DB etc if needed. If you don;t want to update certain field. For example, the company name here - you can do the following: Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon