Posts Tagged ‘.Net 4.0’

Sharing a small tip 🙂 If you want to add spaces to the end of a string,C# gives us method PadRight to do that.If the length of string is specified as 16 for eg and incase user enters only three characters and you want to add spaces to create a total length of 16,you can write as below.This example gets input from a textbox and adds spaces to the end of string entered.



It’s been quite some time since I shared anything and today I am going to share something about Enums. When you use Enums, it makes your code easily understandable.

Lets take a small Enum as example

public enum Status


            New = 1,

            Active = 2,

            Inactive = 3


  If you want to change an Enum into array of strings, you can use the Enum class GetNames method:

string[] Status = Enum.GetNames(typeof(Status));

You can bind the output from GetNames to a control to get the list of the names in the Enum displayed in UI.

There is a common scenario where we want to convert  a string containing one of the names in an Enum into the Enum item itself when you are reading the data from database.

Parse method below does that job,but throws an exception “System.ArgumentException was unhandled” if the string value you are passing to Parse isn’t an item in the Enum.

string custStatus = “Test”;

Status sts = (Status)Enum.Parse(typeof(Status), custStatus);

This exception can be avoided if you use the Enum’s TryParse method.

  Status stat;

    if (Enum.TryParse<Status>(custStatus, true, out stat))


        Console.WriteLine(“Status Found: “+stat.ToString());




        Console.WriteLine(“Status not found!”);


An even better solution  is to use the Enum’s IsDefined method to see if the item exists before you try to get it .

if (Enum.IsDefined(typeof(Status), custStatus))


                Status sts = (Status)Enum.Parse(typeof(Status), custStatus);




                Console.WriteLine(“Status not found!”);



Hope you enjoyed reading this.


Some of the users might have already faced the scenario of having databound controls like checkboxes inside GridView, which gets created at runtime.The problem here is if you look at the client id of checkboxes generated at run time,it will be quite unpredictable to use with document.getElementById and accessing it is not very straight.At run time the clientID will be something like GridView1_ctl01_CheckBox1 for a particular check box. ctl01 will not remain same it will be ctl02, ctl03 etc for the checkboxs in the respective rows. So you will have to manipulate the clientid someway so that it turns predictable & you can acess each checkbox to do some operations like making it checked or unchecked based on your conditons.

What I explained so far is history now 🙂 Things have changed in .Net 4.0 .ClientId is no longer unpredictable.Cool right!A much awaited feature is introduced now.

Details of changes in .Net4.0

.Net 4.0 introduces two new properties ClientIDMode Property & ClientIDRowSuffix Property which can help you in this.If you set the ClientIDMode property to Predictable, ASP.NET generates the ClientID by appending a suffix that is derived from the data field specified in ClientIDRowSuffix(Any column name you can specify as ClientIDRowSuffix for eg EmpId column of your datasource ) . If ClientIDRowSuffix is not set, the suffix is a sequential number.This number begins at zero and is incremented by 1 for each row. and each segment is separated by an underscore character (_).

ClientIDMode enumeration values are as below:

This algorithm was used in versions of ASP.NET earlier than ASP.NET 4 which I have already explained.If you use Visual Studio to convert a Web project to ASP.NET 4 from an earlier version, Visual Studio automatically sets the site default to AutoID in the Web.config file
The ClientID value is set to the value of the ID property. If the control is a naming container, the control is used as the top of the hierarchy of naming containers for any controls that it contains.
I have already explained this how it works with ClientIDRowSuffix Property
The control inherits the ClientIDMode setting of its parent control.

Right now we saw how this property can be set at the Control level.In two more ways you can set this:

Page Level -Set the ClientIDMode value for a page in the @ Page directive
Application Level-Set the ClientIDMode value for all pages in a Web site by setting the pages element in the site’s Web.config file.

MSDN has got very good explanation for this.But there it’s a bit vast & might be difficult for a beginner to understand.Hence I have grabbed few things from there & presented it in my own style.Hope you find this helpful!

I have always thought about the fact that Visual Studio comes with such awesome utilities,still it is  difficult to run one by one everytime from outside.

I was trying to figure out a way & it took me to msdn  which talks about how to run external tools from visual studio.I felt as if my wish got granted so fast 🙂 In my previous post I talked about the tool guidgen.exe which helps to create guids & here I will explain how you can run the same guidgen or some other tool from Visual Studio itself.

Open Visual Studio,On the Tools menu  choose External Tools

In the External Tools dialog box,click Add, and enter a name in Title Box – CreateGuid

Add path in Command box

C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\NETFX 4.0 Tools\guidgen.exe

Leave Arguments box as empty as for this one you do not require that

Add the following to Initial directory

C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\NETFX 4.0 Tools\

Click Ok ,You are done!

Again click on tools,you will be able to see the menu item with the name you added in Title Box.Click on it,the utility is loaded for you.

Same steps apply to any of the exes which you find in Microsoft SDKs folder.Read more here

Hope you find this useful 🙂

In one of my stored pocedure’s an input parameter accepts Guid value & every time I wanted to test it,I used to run class from C# with Guid.NewGuid().ToString() to copy value & add it to stored procedure.Quite weird right 🙂 Because I never knew how else I can generate a guid value.

Visual Studio External Tools come with a tool guidgen.exe that can help you create Guid in a specified format.

Path – C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\NETFX 4.0 Tools\guidgen.exe

How to Use guidgen.exe?

  1. Run exe
  2. Select the format you want for the GUID.
  3. Click New GUID & then Copy.

The GUID is copied to the Clipboard so that you can paste it whereever you want.

If you want to generate another GUID, click New GUID

I decided to write a method utilizing Tuple which is newly introduced in VS 2010.I did not bother to open a new solution,just tried to add a new method of return type Tuple in an existing project’s class.

It took half an hour to figure out why it was giving a compilation error saying “The type or namespace name “Tuple” could not be found”.I rushed to msdn to figure out which namespace it referes to or any dll I need to refer.I found,it is added in System namespace which is already added to my cs file.I kept on googling for sometime & nothing helped.Finally figured out that though my solution is VS2010,Target Framework is not set to 4.0 & it’s still 3.5 😦 so simple it is,still took long time to track the exact issue.

Moral is,whenever you are implementing something newly introduced to framework,make sure that you check the target framework version & not the visual studio version :).

I beleive most of you know about overloading in oops.Well,to have some optional parameters some time before, we had to rely on overloading itself.But now things have changed & with the introduction of Optional Parameters in C#4.0,it’s going to be really easy. This is how it will look like.

public void ExampleMethod(int required, string optionalstr = "default string",int optionalint = 10)

  • Each optional parameter has a default value as part of its definition.
  • If no argument is sent for that parameter, the default value is used. These default values must be constants.
  • Comma-separated gaps in the argument list are not supported.
  • The following call to ExampleMethod causes a compiler error, because an argument is provided for the third parameter but not for the second.

    ExampleMethod(3, ,4);

    However, if you know the name of the third parameter, you can use a named argument to accomplish the task.

    ExampleMethod(3, optionalint: 4);

  • Optional parameters can also be defined at the end of the parameter list, after any required parameters.
  • public void ExampleMethod(int required,int optionalint = 10,string optionalstr = "default string")

  • If the caller provides an argument for any one of a succession of optional parameters, it must provide arguments for all preceding optional parameters.