Showing posts with label Windows Forms. Show all posts
Showing posts with label Windows Forms. Show all posts

Tuesday, October 25, 2016

Update the GUI From a Different Thread in C#

For .NET 2.0:
private delegate void SetControlPropertyThreadSafeDelegate(
    Control control, 
    string propertyName, 
    object propertyValue);

public static void SetControlPropertyThreadSafe(
    Control control, 
    string propertyName, 
    object propertyValue)
{
  if (control.InvokeRequired)
  {
    control.Invoke(new SetControlPropertyThreadSafeDelegate               
    (SetControlPropertyThreadSafe), 
    new object[] { control, propertyName, propertyValue });
  }
  else
  {
    control.GetType().InvokeMember(
        propertyName, 
        BindingFlags.SetProperty, 
        null, 
        control, 
        new object[] { propertyValue });
  }
}
Call it like this:
// thread-safe equivalent of
// myLabel.Text = status;
SetControlPropertyThreadSafe(myLabel, "Text", status);
If you're using .NET 3.0 or above, you could rewrite the above method as an extension method of the Control class, which would then simplify the call to:
myLabel.SetPropertyThreadSafe("Text", status);
For .NET 3.0 you should use this code:
private delegate void SetPropertyThreadSafeDelegate<TResult>(
    Control @this, 
    Expression<Func<TResult>> property, 
    TResult value);

public static void SetPropertyThreadSafe<TResult>(
    this Control @this, 
    Expression<Func<TResult>> property, 
    TResult value)
{
  var propertyInfo = (property.Body as MemberExpression).Member 
      as PropertyInfo;

  if (propertyInfo == null ||
      !@this.GetType().IsSubclassOf(propertyInfo.ReflectedType) ||
      @this.GetType().GetProperty(
          propertyInfo.Name, 
          propertyInfo.PropertyType) == null)
  {
    throw new ArgumentException("The lambda expression 'property' must reference a valid property on this Control.");
  }

  if (@this.InvokeRequired)
  {
      @this.Invoke(new SetPropertyThreadSafeDelegate<TResult> 
      (SetPropertyThreadSafe), 
      new object[] { @this, property, value });
  }
  else
  {
      @this.GetType().InvokeMember(
          propertyInfo.Name, 
          BindingFlags.SetProperty, 
          null, 
          @this, 
          new object[] { value });
  }
}
which uses LINQ and lambda expressions to allow much cleaner, simpler and safer syntax:
myLabel.SetPropertyThreadSafe(() => myLabel.Text, status); // status has to be a string or this will fail to compile
Not only is the property name now checked at compile time, the property's type is as well, so it's impossible to (for example) assign a string value to a boolean property, and hence cause a runtime exception.
Unfortunately, this doesn't stop anyone from doing stupid things such as passing in another Control's property and value, so the following will happily compile:
myLabel.SetPropertyThreadSafe(() => aForm.ShowIcon, false);
Hence I added the runtime checks to ensure that the passed-in property does actually belong to the Control that the method's being called on. Not perfect, but still a lot better than the .NET 2.0 version.

Tuesday, August 2, 2016

Using Extension Methods in C#


Following is an example use of an Extension method in C#.

Imagine you have a class written by someone else and you are not allowed to do any modification to the class.

   public class Class1
    {
        public int MyProperty { get; set; }
    }

You have come up with the following calculation and want to have it in the Class1, so that others could use it without rewriting the calculation.

int sum = p.MyProperty * 5;

Now, incomes the extension method.

public static class myextention
    {
        public static int test(this Class1 p)
        {
           
            return p.MyProperty * 5;
        }
    }

After creating the extension method, you can now call the test function as it’s defined in the Class1 itself.

Class1 c = new Class1();

int extensionSum = c.test();

Saturday, March 16, 2013

Rename Files in C#.NET

There is no separate method for renaming files in .NET. For the purpose of renaming files we can use MOVE() method as in below example
string path = "~/Tiles/";
string FromFile = path+"old.jpg";
string ToFile = path + "new.jpg";
if (File.Exists(Server.MapPath(FromFile)))
File.Move(Server.MapPath(FromFile), Server.MapPath(ToFile));

Thursday, January 31, 2013

Convert DataTable into a String

Following method will convert a DataTable into a string in the format of:

Column Header Name:-:Cell Value##Column Header Name:-:Cell Value##Column Header Name:-:Cell Value.....

public string DataTabletoString(DataTable DT)
{
  StringBuilder SB = new StringBuilder();
foreach (DataRow rowItem in DT.Rows)
{
foreach (DataColumn colItem in DT.Columns)
{
  SB.Append(colItem.ToString()+":- :"+rowItem[colItem].ToString()+"##");
}
}
  return SB.ToString();
}

Monday, January 14, 2013

The Exception Class in C#.NET

Every exception class derives from the base class System.Exception. The .NET Framework is full of predefined exception classes, such as NullReferenceException, IOException, SqlException, and so on. The Exception class includes the essential functionality for identifying any type of error. Below is a list of its most important members.

HelpLink 
A link to a help document, which can be a relative or fully qualified URL (uniform resource locator) or URN (uniform resource name), such as file:///C:/ACME/MyApp/help.html#Err42. The .NET Framework doesn’t use this property, but you can set it in your custom exceptions if you want to use it in your web page code.

InnerException 
A nested exception. For example, a method might catch a simple file IO (input/output) error and create a higher-level “operation failed” error. The details about the original error could be retained in the InnerException property of the higher-level error.

Message 
A text description with a significant amount of information describing the problem.

Source 
The name of the application or object where the exception was raised.

StackTrace 
A string that contains a list of all the current method calls on the stack, in order of most to least recent. This is useful for determining where the problem occurred.

TargetSite 
A reflection object (an instance of the System.Reflection.MethodBase class) that provides some information about the method where the error occurred. This information includes generic method details such as the method name and the data types for its parameter and return values. It doesn’t contain any information about the actual parameter values that were used when the problem occurred.

GetBaseException() 
A method useful for nested exceptions that may have more than one layer. It retrieves the original (deepest nested) exception by moving to the base

When you catch an exception in an ASP.NET page, it won’t be an instance of the generic System.Exception class. Instead, it will be an object that represents a specific type of error. This object will be based on one of the many classes that inherit from System.Exception. These include diverse classes such as DivideByZeroException, ArithmeticException, IOException, SecurityException, and many more. Some of these classes provide additional details about the error in additional properties.

Visual Studio provides a useful tool to browse through the exceptions in the .NET class library. Simply select Debug -> Exceptions from the menu (you’ll need to have a project open in order for this to work). The Exceptions dialog box will appear. Expand the Common Language Runtime Exceptions group, which shows a hierarchical tree of .NET exceptions arranged by namespace (see Figure).


The Exceptions dialog box allows you to specify what exceptions should be handled by your code when debugging and what exceptions will cause Visual Studio to enter break mode immediately. That means you don’t need to disable your error-handling code to troubleshoot a problem. For example, you could choose to allow your program to handle a common FileNotFoundException (which could be caused by an invalid user selection) but instruct Visual Studio to pause execution if an unexpected DivideByZero exception occurs.

To set this up, add a check mark in the Thrown column next to the entry for the System.DivideByZero exception. This way, you’ll be alerted as soon as the problem occurs. If you don’t add a check mark to the Thrown column, your code will continue, run any exception handlers it has defined, and try to deal with the problem. You’ll be notified only if an error occurs and no suitable exception handler is available.

Sunday, January 13, 2013

Using Math Class in C#.NET

In the past, every language has had its own set of keywords for common math operations such as rounding and trigonometry. In .NET languages, many of these keywords remain. However, you can also use a centralized Math class that’s part of the .NET Framework. This has the pleasant side effect of ensuring that the code you use to perform mathematical operations can easily be translated into equivalent statements in any .NET language with minimal fuss. To use the math operations, you invoke the methods of the System.Math class. These methods are static, which means they are always available and ready to use. 

The following code snippet shows some sample calculations that you can perform with the Math class:

double myValue;
myValue = Math.Sqrt(81); // myValue = 9.0
myValue = Math.Round(42.889, 2); // myValue = 42.89
myValue = Math.Abs(-10); // myValue = 10.0
myValue = Math.Log(24.212); // myValue = 3.18.. (and so on)
myValue = Math.PI; // myValue = 3.14.. (and so on)

The features of the Math class are too numerous to list here in their entirety. The preceding examples show some common numeric operations. For more information about the trigonometric and logarithmic functions that are available, refer to the Visual Studio Help reference for the Math class.

Saturday, January 12, 2013

Implicit Conversions in C#.NET

Conversions do one thing and one thing alone—allow an expression of one type to be treated as another type. Conversions can take one of two forms:

❑ Implicit. These are conversions that can occur automatically as required within the code.
❑ Explicit. These conversions require a cast to be called.

In this post we will be discussing about implicit conversions.

All conversions in C# must be static and must either take the type that the conversion is defined on or return that type.

int x = 01234;
long y = x; // this is an implicit conversion, from int to long
int z = (int) y; // this is an explicit conversion, from long to int

In the preceding example, there is a conversion from int to long. This is an implicit conversion, and expressions of the type int can be treated as though they have the type long. However, the reverse, a conversion from long to int, is an explicit conversion, and an explicit cast is needed for this to work.

Implicit Conversions

The following conversions are all considered implicit:

❑ Identity conversions
❑ Implicit numeric conversions
❑ Implicit enumeration conversions
❑ Implicit reference conversions
❑ Boxing conversions
❑ Implicit type parameter conversions
❑ Implicit constant expression conversions
❑ User-defined implicit conversions

There are many situations where an implicit conversion can occur. For example, in:

❑ Assignments
❑ Function member invocations
❑ Cast expressions

Identity Conversions

An identity conversion involves a conversion from one type to the same type. Very little is useful about this. It serves as nothing more than a way of making sure that errors aren’t generated when trying to convert one type to the same type.

Implicit Numeric Conversions

The following are implicit numeric conversions:

❑ From sbyte to decimal, double, float, int, long, and short
❑ From long to double, decimal, or float
❑ From ulong to double, decimal, or float
❑ From char to double, decimal, float, ushort, int, uint, long, or ulong
❑ From float to double
❑ From byte to decimal, double, short, ushort, int, uint, long, ulong, or float
❑ From short to double, decimal, int, long, or float
❑ From ushort to double, decimal, int, uint, long, ulong, or float
❑ From int to double, decimal, long, or float
❑ From uint to double, decimal, long, ulong, or float

Conversions from int, uint, long or ulong to float and from long or ulong to double quite often cause a loss of precision in the resulting value. This should be borne in mind if you’re carrying out highprecision

technical work. However, such conversions will never cause a loss of magnitude of the value (a number that has a magnitude that is 103 will still retain the same magnitude). 

No other implicit numeric conversions cause any loss of precision in the resulting value.

It’s important to bear in mind that no implicit conversion to the char type is possible, and other integral values won’t automatically convert to this type (if you think about it, it wouldn’t make sense if they did, since character strings would make no sense as any other type).

Implicit Enumeration Conversions

Implicit enumeration conversions simply allow the decimal integer literal 0 to be converted to any enum type without causing an error. The enum types are:

❑ byte
❑ sbyte
❑ short
❑ ushort
❑ int
❑ uint
❑ long
❑ ulong

Implicit Reference Conversions

The following are implicit reference conversions:

❑ From any reference type to object
❑ From any class type S to any class type T, provided S is derived from T
❑ From any class type S to any interface type T, provided S implements T
❑ From any interface type S to any interface type T, provided S is derived from T
❑ From any array type to System.Array
❑ From any delegate type to System.Delegate
❑ From any array type to any interface implemented by System.Array
❑ From any delegate type to System.ICloneable
❑ From the null type to any reference type
❑ From an array type S with an element type SE to an array type T with an element type TE, provided all of the following are true:
       ❑ S and T differ only in element type.
       ❑ An implicit reference conversion exists from SE to TE.
❑ From a one-dimensional array type S[] to System.Collections.Generic.IList<S> and base interfaces of this interface

❑ From a one-dimensional array type S[] to System.Collections.Generic.IList<T> and base interfaces of this interface (if there is an implicit reference conversion from S to T)

If the type parameter is known to be a reference type, the following implicit references exist:

❑ From the null type to T
❑ From T to its effective base class C, from T to any base class of C, and from T to any interface implemented by C

❑ From T to an interface type I in T’s effective interface set and from T to any base interface of I
❑ From T to a type parameter U, provided that T depends on U

Boxing Conversions

A boxing conversion allows any value type to be implicitly converted as follows:

❑ To the type object
❑ To System.ValueType
❑ To any interface type implemented by the value type

It also allows any enum type to be implicitly converted to System.Enum.

Boxing a value of a value type consists of:

❑ Allocating an object instance
❑ Copying the value type value into that instance A few additional notes:
❑ An enum can be boxed to the type System.Enum, because it is the direct base class for all enums.
❑ A struct or enum can be boxed to the type System.ValueType, because that is the direct base class for all structs and a base class for all enums.

For any type parameter T that is not a reference type, the following are all considered to be boxing conversions:

❑ From T to its effective base class C, from T to any base class C, and from T to any interface implemented by C
❑ From T to an interface type I in T’s interface set and from T to any base interface of I

Implicit Type Parameter Conversions

For a type parameter T that is not known to be a reference type, there will be an implicit conversion   from T to a type parameter U, provided that the type parameter T depends on U.

At runtime, if T is a value type and U is a reference type, the conversion will be carried out as though it is a boxing conversion.

At runtime, if both T and U are value types, T and U are necessarily the same type, and no conversion will be carried out on either of the types. At runtime, if T is a reference type, U will also be a reference type, and the conversion is carried out as either an implicit reference conversion or an identity conversion.

Implicit Constant Expression Conversions

An implicit conversion expression allows for the following conversions to be carried out:

❑ Any constant expression of the type int can be converted to byte, sbyte, short, ushort, uint, or ulong as long as the value of the constant expression is within the range of the resulting type.
❑ Any constant expression of the type long can be converted to the type ulong, as long as the value of the constant expression is not negative.

User Defined Implicit Conversions

A user-defined implicit conversion consists of:

❑ An optional standard implicit conversion, followed by
❑ The execution of a user-defined implicit conversion operator, followed by
❑ Another optional standard implicit conversion

Friday, January 11, 2013

.NET Array Types

Formally speaking, an array is a collection of data points, of the same defined data type, that are accessed using a numerical index. Arrays are references types and derive from a common base class
named System.Array. By default, .NET arrays always have a lower bound of zero, although it is possible to create an array with an arbitrary lower bound using the static
System.Array.CreateInstance() method.

C# arrays can be declared in a handful of ways. First of all, if you are creating an array whose values will be specified at a later time (perhaps due to yet-to-be-obtained user input), specify the size of the array using square brackets ([]) at the time of its allocation, for example:

// Assign a string array containing 3 elements {0 - 2}
string[] booksOnCOM;
booksOnCOM = new string[3];
// Initialize a 100 item string array, numbered {0 - 99}
string[] booksOnDotNet = new string[100];

Once you have declared an array, you can make use of the indexer syntax to fill each item with a value:

// Create, populate, and print an array of three strings.

string[] booksOnCOM;
booksOnCOM = new string[3];
booksOnCOM[0] = "Developer's Workshop to COM and ATL 3.0";
booksOnCOM[1] = "Inside COM";
booksOnCOM[2] = "Inside ATL";

foreach (string s in booksOnCOM)
Console.WriteLine(s);

As a shorthand notation, if you know an array’s values at the time of declaration, you may specify these values within curly brackets. Note that in this case, the array size is optional (as it is calculated on the fly), as is the new keyword. Thus, the following declarations are identical:

// Shorthand array declaration (values must be known at time of declaration).

int[] n = new int[] { 20, 22, 23, 0 };
int[] n3 = { 20, 22, 23, 0 };

There is one final manner in which you can create an array type:

int[] n2 = new int[4] { 20, 22, 23, 0 }; // 4 elements, {0 - 3}

In this case, the numeric value specified represents the number of elements in the array, not the value of the upper bound. If there is a mismatch between the declared size and the number of initializers, you are issued a compile time error.

Regardless of how you declare an array, be aware that the elements in a .NET array are automatically
set to their respective default values until you indicate otherwise. Thus, if you have an array of numerical types, each member is set to 0 (or 0.0 in the case of floating-point numbers), objects are set
to null, and Boolean types are set to false.

Using @-prefix in C#.NET

C# introduces the @-prefixed string literal notation termed a verbatim string. Using verbatim strings, you disable the processing of a literal’s escape characters. This can be most useful when working
with strings representing directory and network paths. Therefore, rather than making use of \\ escape
characters, you can simply write the following:

// The following string is printed verbatim
// thus, all escape characters are displayed.

Console.WriteLine(@"C:\MyApp\bin\debug");

Also note that verbatim strings can be used to preserve white space for strings that flow over multiple lines:

// White space is preserved with verbatim strings.

string myLongString = @"This is a very
very
    very
        long string";
Console.WriteLine(myLongString);

You can also insert a double quote into a literal string by doubling the " token, for example:
Console.WriteLine(@"Cerebus said ""Darrr! Pret-ty sun-sets""");

The System.String Data Type in C#.NET

The C# string keyword is a shorthand notation of the System.String type, which provides a number of members you would expect from such a utility class. Below lists are some (but not all) of the interesting members.

Length  - This property returns the length of the current string.

Contains()  - This method is used to determine if the current string object contains a specified string.

Format()  - This static method is used to format a string literal using other primitives

Insert()  - This method is used to receive a copy of the current string that contains newly inserted string data.

PadLeft(), PadRight()
 - These methods return copies of the current string that has been padded with specific data.

Remove(), Replace() 
- Use these methods to receive a copy of a string, with modifications
(characters removed or replaced.)

Substring() - This method returns a string that represents a substring of the current string.

ToCharArray()  - This method returns a character array representing the current string.

ToUpper() , ToLower()
- These methods create a copy of a given string in uppercase or lowercase.

System.DateTime and System.TimeSpan

The DateTime type contains data that represents a specific date (month, day, year) and time value, both of which may be formatted in a variety of ways using the supplied members. By way of a simple example, ponder the following statements:

static void Main(string[] args)
{
...
// This constructor takes (year, month, day)
DateTime dt = new DateTime(2004, 10, 17);
// What day of the month is this?
Console.WriteLine("The day of {0} is {1}", dt.Date, dt.DayOfWeek);
dt.AddMonths(2); // Month is now December.
Console.WriteLine("Daylight savings: {0}", dt.IsDaylightSavingTime());
...
}

The TimeSpan structure allows you to easily define and transform units of time using various members, for example:

static void Main(string[] args)
{
...
// This constructor takes (hours, minutes, seconds)
TimeSpan ts = new TimeSpan(4, 30, 0);
Console.WriteLine(ts);
// Subtract 15 minutes from the current TimeSpan and
// print the result.
Console.WriteLine(ts.Subtract(new TimeSpan(0, 15, 0)));
...
}

Figure shows the output of the DateTime and TimeSpan statements


Thursday, January 10, 2013

Converting a String into DateTime format in C#.NET

Recently i was trying to parse string date time value into DateTime format but i was getting the error "String was not recognized as a valid DateTime"

Following is the string format i was trying to convert.

"10/10/2010 12:00:00 A.M"

The issue is with "." character in "A.M". I removed the "." character and it was working.

DateTime result = DateTime.ParseExact("10/10/2010 12:00:00 a.m".Replace(".", ""), "dd/MM/yyyy hh:mm:ss tt", null);

Tuesday, January 8, 2013

Phone Number Validator Class

Below sample class validates phone number for counties USA, UK and Netherland. You can add the validations for other countries to the class.

public class PhoneValidator {

static IDictionary<string, Regex> countryRegex =
new Dictionary<string, Regex>() {
{ "USA", new Regex("^[2-9]\\d{2}-\\d{3}-\\d{4}quot;)},
{ "UK", new
Regex("(^1300\\d{6}$)|(^1800|1900|1902\\d{6}$)|(^0[2|3|7|8]{1}[0-
9]{8}$)|(^13\\d{4}$)|(^04\\d{2,3}\\d{6}$)")},
{ "Netherlands", new Regex("(^\\+[0-9]{2}|^\\+[0-
9]{2}\\(0\\)|^\\(\\+[0-9]{2}\\)\\(0\\)|^00[0-9]{2}|^0)([0-9]{9}$|[0-9\\-
\\s]{10}$)")},
};

public static bool IsValidNumber(string phoneNumber, string country) {
if (country != null && countryRegex.ContainsKey(country))
return countryRegex[country].IsMatch(phoneNumber);
else
return false;
}

public static IEnumerable<string> Countries {
get {
return countryRegex.Keys;
}
}
}

Using the class:

string ContactPhone="465 567 56";
string Country="USA";

if (!PhoneValidator.IsValidNumber(ContactPhone, Country))
{
  //Validation Message
}

Saturday, January 5, 2013

How to Create a Folder in C#.NET

To create a directory in C#.NET use the below code.

string pathToCreate = "~/UserFolder";// "UserFolder" is the folder name to be created

if (!Directory.Exists(pathToCreate)) // Check whether a folder exists in the same name
{
  Directory.CreateDirectory(Server.MapPath(pathToCreate));// Create folder
}

Directory will be created in your application root.

Friday, January 4, 2013

Check Duplicates in a ArrayList

ArrayList list = new ArrayList { 1, 9, 2, 1, 6, 5 };

Above is a array list of integers. We can use below methods to check the duplicates in the array list.

Method 1: Using the Contains method

private void AddItems(object o) 
 { 
  if(!list.Contains(o))
   { 
    list.Add(o); 
   }
 else
  {
   //Duplicate found
  } 
}

Method 2: Using LINQ

var x = from l in list.OfType() 
 group l by l into g 
 where g.Count() > 1 
 select g.Key; 

 if (x.Count() > 0) 
 { 
   // Duplicate found 
 }

Wednesday, January 2, 2013

Convert Class to string

In order to convert a class into a string you need to override the ToString() method.

public class AuthUser
{

   public int UserID { get; set; }
   public string UserNo { get; set; }
   public string UserName { get; set; }
   public string Password { get; set; }

   public override string ToString()
   {
     return UserID + "," + UserNo + "," + UserName + "," + Password;
   }

}

Below code will give you a comma separated string output.

AuthUser au = new AuthUser { UserID=1, UserNo="001", UserName="chamara", Password="123"};
Response.Write(au.ToString());

Output:
1,001,chamara,123

Tuesday, January 1, 2013

Compare string in C#.NET

string first="x";
string second="x";
int res= string.Compare(first, second,true);
Response.Write(res.ToString());

Output:
0

Above code will compare the two strings "first" and "second" if the strings are equal string.Compare method will return 0 if not equal it will return -1.

Third parameter passed in the string.Compare method will ignore the case.

Friday, December 28, 2012

How to get relative file path from full path

Let say you have a Folder called "BookCovers" within your application folder. To get the full path of a file inside the folder use the below code.

string FullPath = Server.MapPath(@"~/BookCovers/") + FileName;

EX: E:\Industry\Soft\Tests\\BookCovers\1.jpg

To get the relative path from full path use the below code.

String RelativePath = FullPath.Replace(Request.ServerVariables["APPL_PHYSICAL_PATH"], String.Empty);
RelativePath = @"~\" + RelativePath;

EX: ~\BookCovers\1.jpg

Wednesday, December 19, 2012

Simple Delegate Example in .NET

.NET delegates are extensively used for notifications.
- Callbackes (eg: for asynchronous completion callbacks)
- Events (eg: OnClick event handler for buttons)

Delegates are like a function pointer in C/C++
- Define a delegate like declaring a function prototype.
- Create a variable whose type is a variable.
- Then point this variable at a real function and call the function through the delegate variable.

See below example.

Create a Calculator class with Add function.

public class Calculator
{
     public int Add(int operand1, int operand2)
      {
          return operand1 + operand2;
       }
}

In the web page add the below code.

public delegate int BinaryOperation(int Operand1, int Operand2);//Delegate definition
protected void Page_Load(object sender, EventArgs e)
{
 if (!Page.IsPostBack)
 {
    Calculator calc = new Calculator();
    BinaryOperation adddel;// Declare a variable of delegate type
    adddel = calc.Add;//point the delegate variable at the add function
    Response.Write("1 + 2 = "+adddel(1,2));// call the function through delegate variable
 }
}

You can assign any method to the delegate BinaryOperation that match the signature and method will be called each time delegate is called.

Output:
1 + 2 = 3

Monday, December 17, 2012

Use of Int32.Parse(), Convert.ToInt32(), and Int32.TryParse()

Int32.Parse (string val)
This method converts string representation of the integer into it's 32-bit signed integer. 
val is null - throw ArgumentNullException.
val is not an integer - throw FormatException.
val is less than MinValue or greater thanMaxValue - throw OverflowException.

string val1 = "356"; 
string val2 = "abc"; 
string val3 = null; 
string val4 = "123456789123456789123456789123456789123456789"; 
int result; 

result = Int32.Parse(val1); //-- 1234 
result = Int32.Parse(val2); //-- FormatException 
result = Int32.Parse(val3); //-- ArgumentNullException 
result = Int32.Parse(val4); //-- OverflowException

Convert.ToInt32(string val)
This method converts string representation of the integer into it's 32-bit signed integer. 
val is null - return 0.
val is not an integer - throw FormatException.
val is less than MinValue or greater thanMaxValue - throw OverflowException.

result = Int32.Parse(val1); //-- 1234 
result = Int32.Parse(val2); //-- FormatException 
result = Int32.Parse(val3); //-- 0
result = Int32.Parse(val4); //-- OverflowException 

Int32.TryParse(string, out int)
This method converts string representation of the integer into it's 32-bit signed integer to a out variable and returns true if parsing succeed.
val is null - return 0.
val is not an integer - return 0.
val is less than MinValue or greater thanMaxValue - return 0.

bool result;
result = Int32.Parse(val1, out result); //-- true, result->1234 
result = Int32.Parse(val2, result); //-- false, result->0
result = Int32.Parse(val3, result); //-- false, result->0
result = Int32.Parse(val4, result); //-- false, result->0

TryParse is the fastest method from above mentioned options.