Getting parent control of a control in WPF through code or at runtime

I was working on a WPF project where I came across a problem where I need to refer to the parent container/control of specific type of control/item in WPF. So I did some RnD and search on the net for the problem and finally I came across a solution which I want to share.

Suppose we want to get ListViewItem on which a Button control is placed or we want to get the reference of that ListView in WPF.

Here is a method through which we can find parent of a control.

/// <summary>
/// Finds a parent of a given control/item on the visual tree.
/// </summary>
/// <typeparam name="T">Type of Parent</typeparam>
/// <param name="child">Child whose parent is queried</param>
/// <returns>Returns the first parent item that matched the type (T), if no match found then it will return null</returns>

public static T TryFindParent<T>(this DependencyObject child)
where T : DependencyObject
{
     DependencyObject parentObject = VisualTreeHelper.GetParent(child);
     if (parentObject == null) return null;

     T parent = parentObject as T;
     if (parent != null)
          return parent;
     else
          return TryFindParent<T>(parentObject);
}

To find child control of a control, refer to Find Child Control of a Control in WPF.

Hope you will find this blog helpful.

Enumeration in C#

There are many situations when we want to give specific names to values. In order to accomplish this task we use Enumeration.

In this blog I am going to explain how to create and use enumeration (enum).

Enumerations are special sets of named values which all maps to a set of numbers, usually integers. The enum keyword is used to declare an enumeration, a distinct type that consists of a set of named constants called the enumerator list.

Usually it is best to define an enum directly within a namespace so that all classes in the namespace can access it with equal convenience. However, an enum can also be nested within a class or struct.

By default, the first enumerator has the value 0, and the value of each successive enumerator is increased by 1. For example, in the following enumeration, Sunday is 0, Monday is 1, Tuesday is 2, and so forth.

Example:

enum Days 
{ 
     Sunday, 
     Monday, 
     Tuesday, 
     Wednesday, 
     Thursday, 
     Friday, 
     Saturday 
};

static void Main()
{
     int x = (int)Days.Sunday;
     int y = (int)Days.Friday;
     Console.WriteLine("Sunday = {0}", x);
     Console.WriteLine("Friday = {0}", y);
}

Output:

Sunday = 0

Friday = 5

Enumerators can have initializers to override the default values.

Example:

enum Days 
{ 
     Sunday=1, 
     Monday, 
     Tuesday, 
     Wednesday, 
     Thursday, 
     Friday, 
     Saturday 
};

Now in this case the output of the above code will be

Sunday = 1

Friday = 6

By default the underlying type of each element in the enum is int. You can specify another integral numeric type by using a colon, as shown in following example.

enum Months : byte 
{ 
     Jan, 
     Feb, 
     Mar, 
     Apr, 
     May, 
     Jun, 
     Jul, 
     Aug, 
     Sep, 
     Oct, 
     Nov, 
     Dec 
};

Conversions of enum in c#:

For demonstrating conversion I’m going to use the following enumeration:

enum Days 
{ 
     Sunday=1, 
     Monday, 
     Tuesday, 
     Wednesday, 
     Thursday, 
     Friday, 
     Saturday 
};

Converting enum to string:

Days day = Days.Monday;
string sDay = day.ToString();

In the above code sDay will hold “Monday” as a value.

Converting enum to int:

Days day = Day.Monday;
int iDay = (int)day;

After conversion iDay will be equal to 2.

Converting string to enum:

// Possible user input:
string sDay = "Monday";

// Try to convert the string to an enum:
Days day = (Days)Enum.Parse(typeof(Days), value);

Note: You can cause exceptions to be raised when parsing enums. When the contents of the string you try to parse is not represented in the enum, you must handle the exception. Handling exceptions is often one of the most important parts of your program.

Converting int to enum:

// Possible user input:
int iDay = 1;

// Try to convert the string to an enum:
Days day = (Days)iDay;

Hope, the above information on enum will be helpful. If you find any mistakes or want to give your suggestions please feel free to comment on the post and help me serve better.

Set max length of MultiLine TextBox in ASP.Net

There was a requirement in a project where I had to set the max length of TextBox in Multiline mode so I just set the MaxLength property of TextBox to the length which was required but it doesn’t worked. So as usual I took help of search engines and found that MaxLength does not work in MultiLine mode and found two alternatives to fix the issue, one is through javascript and another through RegularExpressionValidator.

Here I am going to share the two ways which I found

  • Through Javascript:Here is the Javascript code which should be added.
    <script type="text/javascript">
         function Check(textBox, maxLength) {
              if (textBox.value.length > maxLength) {
                   alert("Max characters allowed are " + maxLength);
                   textBox.value = textBox.value.substr(0, maxLength);
              }
         }
    </script>
    

    Now call the javascript function on two client side event of TextBox namely onKeyUp and onChange like this

    <asp:TextBox ID="TextBox1" runat="server" TextMode="MultiLine" 
    onKeyUp="javascript:Check(this, 100);" onChange="javascript:Check(this, 100);" />
    
  • Through RegularExpressionValidator Use "^[\s\S]{0,100}$" as Validation Expression to validate through RegularExpressionValidator like this
    <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" 
    ControlToValidate="TextBox1" ErrorMessage="Exceeding 100 characters" ValidationExpression="^[\s\S]{0,10}$" />

    You can change the value to in braces according to the requirement. The first value in braces is minimum required length and second value is maximum required length of Multiline TextBox.

Here is all which I found. If you get any other solution then do add your solution in your comment and help others.

All suggestions are welcome.