-->

Sunday, November 9, 2014

Commonly used jQuery Event Methods: jQuery

All the DOM events have its equivalent jQuery methods that may be implement by programmer as per the requirement. Anything happens through input devices on the web-page is called an event.

All these events have its unique names e.g. clicking on the page, pressing key, hovering mouse etc. According to jQuery masters, these events have some categories, some of them listed below:

  • Keyboard events: KeyDown, KeyUp and KeyPress etc.
  • Mouse events: Click, double click, mouse hover, mouse enter and mouse leave etc.
  • Form events: submit, focus, blur etc. 
  • Document/window events: Load, UnLoad, scrolling, resizing etc.

All these events have its own method, discussed earlier in changing default behavior. Some of those events have listed below with example:

$(document).ready()

Whenever the document/page is ready, this event have triggered. Anything written in this event have been executed just after the page loaded. All the events except functions must be written in this event to be executed. Some of the selectors have been discussed here.
$(document).ready(function(){
alert(‘document is ready’); // This message will shown just after the page load its contents.
});

click()

This event triggers when user clicks on any html events. Programmer can write particular click method on any html event. The below code will execute when user clicks on any <p> element.
$(“p”).click(function(){
alert(‘p tag clicked’);
});

dblclick()

This event triggers when user double clicks on any html events. Programmer can write particular double click method on any html event. The below code will execute when user clicks two times on any <p> element.
$(“p”).dblclick(function(){
alert(‘p tag double clicked’);
});

mouseenter()

This event triggers when user enters mouse in the area of html events. The below code will execute when user enters into area of any <p> element.
$(“p”).mouseenter(function(){
alert(‘mouse entered in <p> tag’);
});

blur()

whenever an html event losses its focus, this event will triggered. This is just opposite event of focus() event which triggers when an element have focus on it.
$(“p”).blur(function(){
alert(‘losses focus from <p> tag’);
});

There are many events related to each html element, can be read from jQuery official website of through the help option of visual studio. All those events have similar syntax to write method for them. In the next article we will discuss about jQuery effects.

Monday, September 22, 2014

How to Change Default Behaviour of element in jQuery

Earlier article was about installing and embedding jQuery on our web-pages, and then using jQuery selectors to perform some events. These events can be easily written on the same page or may be in another javascript file having extension (js).

jQuery provides simple function to prevent the default behavior of any event on the web page. I have an anchor tag on the page and on the click on that tag I am redirecting the user on the jQuery.com website.

Now to cancel this redirection programmer can use:

$( document ).ready(function() {
    $( "a" ).click(function( event ) {
               event.preventDefault();
    });
});

The above code will can cancel all the redirection of all the anchor tag on the page. If you want to prevent the behavior for some specific element then use their id or may be class selector. Selectors have discussed in earlier article, you can get more help out there.

Let’s suppose we have a form filling out all the details by the user and at the last there is a submit button to post the form data to controller. Now we don’t want to post data then we can use this simple jQuery code:

$( document ).ready(function() {
    $( "#btnSubmit" ).click(function( event ) {
               event.preventDefault();
    });
});

Now we have some more buttons or may be anchor tag to be used on the form but don’t want their click event or redirection on their click. Add any class for each of the anchor element whichever click event you want to cancel and write the following code:

$( document ).ready(function() {
    $( ".className" ).click(function( event ) {
               event.preventDefault();
    });
});

Wednesday, November 20, 2013

How to Implement Custom Control, Currency TextBox: Windows Forms

Currency Textbox, custom control, as the name implies, will accept only numbers, decimals and control characters. None of other type will be allowed in this textbox. This textbox is basically used to input prices, rates or any measurement including precision.

I have discussed about all the events used to create custom textbox. Open your Visual Studio 2013 Windows Forms project and add a new class named “CurrencyTextBox”, inherit this by System.Windows.Forms.TextBox. Go through the following points, they all together will make this textbox:

Property

Property will be used to get or set the value in the textbox.
private decimal currencyValue;
public decimal CurrencyValue
        {
            get { return currencyValue; }
            set { currencyValue = value; }
        }

Constructor

When the object of this class has been created, by-default it’s value is set to zero, as written in the below c# code.
public CurrencyTextBox()
        {
            currencyValue = 0;
        }

OnKeyPress

What is to be allowed to write in the textbox? Decided in this event. The first line is used to call its base class constructor with specified arguments. After this I have used some if conditions to specify which key is to be accepted or which is not. “e.Handled=true” this line is used to stop the character from being entered into the textbox.
protected override void OnKeyPress(KeyPressEventArgs e)
        {
            base.OnKeyPress(e);
            if (!Char.IsDigit(e.KeyChar) && !Char.IsControl(e.KeyChar) && e.KeyChar != '.')
            {
                e.Handled = true;
            }
            if (e.KeyChar == '.' && this.Text.Contains("."))
            {
                e.Handled = true;
            }
            if (e.KeyChar == '.' && this.Text.Length < 1)
            {
                e.Handled = true;
            }
        }

OnValidated

When the focus is changed, this event will convert the entered value into decimal value. Because currency is used in decimal not string.
protected override void OnValidated(EventArgs e)
        {
            Decimal value = Convert.ToDecimal(this.Text);
            this.Text = value.ToString("C");
        }

OnClick

When the user click on the textbox, it will set the text to currencyValue (property value) and the cursor will be placed at the last of input value.
protected override void OnClick(EventArgs e)
        {
            this.Text = currencyValue.ToString();
            if (this.Text == "0")
                this.Clear();
            this.SelectionStart = this.Text.Length;
        }

OnTextChanged

Change the newly entered value into decimal format.
protected override void OnTextChanged(EventArgs e)
        {
            currencyValue = Convert.ToDecimal(this.Text);
        }

Run your project and in the toolbox a node is added named components followed by project name. You can use this textbox in your project as per your requirements.

Download CurrencyTextBox.cs

Wednesday, August 7, 2013

Validating Input Controls in windows forms C#

Data entered by user, should be valid and properly formatted, Otherwise a lot of resources could be wasted in fixing the problems that could be arise due to incorrect data format. Data should be properly checked according to the input criteria. Windows forms provides some ways to validate input in your application.

Masked TextBox Validation

We often requires some data like contact number in a well-defined format and also correct no of digits. This problem can easily be solved by using MaskedTextBox in windows forms. MaskedTextBox displays some formats to the user. If user types a wrong entry then this textbox automatically reject that input.

Just add a MaskedTextBox control and look out the mask property. There are approx. 9 predefined masks such as Phone number, zip code, Numeric digits etc. as in following screenshot:
Mask options of Masked TextBox in windows forms

There is no mask for mobile no in the above masks, so we have to create a new mask. Use the last mask i.e. custom mask and insert ten zero’s in the mask textbox just below the list of mask because mobile no is of ten digits, and our new mask has been created.

Event-Driven Validation

Each input control has a Validating event that occur whenever the control requires data validation. Validating event enables you to prevent from shifting focus from the control being validated to another control until validation has been completed.

To check whether the textbox is blank or not, we will simply check this by using the following line of codes in validating event of textbox in C# language.
private void textBox1_Validating(object sender, CancelEventArgs e)
{
if (textBox1.Text == string.Empty)
{
MessageBox.Show("Textbox is empty");
}
}

Just like above code we can validate any other control using some lines of code. There is an argument e of type CancelEventArgs, which can be used to cancel the validating event if required input has been entered by user.
Displaying message when validating the textbox

As in above screenshot if the textbox left empty by the user then a message has been displayed written above. This message can be displayed by any of the message box, status strip etc.

Friday, July 26, 2013

How to Change file attributes in C# Programming

File attributes are metadata associated with computer files that define system behaviour.  Same as files, folders, volumes and other file system objects may have these attributes. All the operating system have often four attributes i.e. archive, hidden, read-only and system. Windows has more attributes. Read more about File Attributes

User have to right click on desired file or folder and then open properties, to change the attributes of that file or folder. If one want to change attributes of multiple files then he/she has to either select all the files and then change or change attributes of each file or folder one by one.

In programming context we can do this task with a predefined class i.e. FileAttributes which provides all the attributes for files and directories. We can easily change the desired attribute of a file or directory using the above class FileAttributes that is exists in System.IO namespace.

Design a new form in windows form application that will look like the below form:


Change file attributes in C#

There are some controls which are used for specific task in this project, we will discuss them one by one:
  • TextBox: show the path of folder selected by user.
  • Browse Button: open a folderBrowserDialog which select a path of folders and files.
  • CheckBox: if checked program will check all the sub-folders for files.
Except these controls there are three more buttons which are used to play with attributes of files or folders as their text shows. For example "Remove all" will remove all the attributes of files and folder at selected path.

Write the following code in the click event of Only Hidden button:
private void btnSetHidden_Click(object sender, EventArgs e)
        {
            count = 0;
            setHidden(txtPath.Text);
            lblStatus.Text = "Number Of Scanned Files And Folders:" + count.ToString();
        }
In the above code there is an integer variable count that will count the scanned file and folders. Then it will call a function setHidden(string ) that will use the selected path and set the hidden property to true of all the files and folders at that selected path.


The code of this function is:
private void setHidden(string dir)
{
if (!Directory.Exists(dir))
{
lblStatus.Text = "Invalid path!";
return;
}
if (chkSub.Checked)
{
foreach (string d in System.IO.Directory.GetDirectories(dir))
{
count++;
lblStatus.Text = dir;
setHidden(d);
DirectoryInfo df = new DirectoryInfo(d);

df.Attributes = System.IO.FileAttributes.Hidden;
foreach (string fil in System.IO.Directory.GetFiles(d))
{
FileInfo f = new FileInfo(fil);
f.Attributes = System.IO.FileAttributes.Hidden;
Application.DoEvents();
count++;
}
}
}
}
In above code it will change the attribute of a directory and then all the files in that directory. Here, a new Method doEvents() is used which process all windows messages currently in the message queue. Calling this method causes the current thread to be suspended while all waiting window messages are processed. You can read more about DoEvents().

Go for example.

Saturday, June 29, 2013

Find a control in windows forms

When we drag-n-drop controls in our designer file then we can easily access those controls in our code file directly by its name. But when we dynamically add some controls either in constructor or in load event of form then we can't access them directly in our code.

Let's have an example

  • Add a textbox and a button using drag-n-drop operation on our form i.e. Form1.
  • Leave the name of controls i.e. textBox1 and button1 as they are.
  • Now in constructor add a new textbox dynamically having name "txtBox" with some properties like:

    TextBox txtBox = new TextBox();
    txtBox.Name = "txtBox";
    txtBox.Text = "dynamically added control";
    txtBox.Width = 250;
    txtBox.Location = new Point(10, 10);

    this.Controls.Add(txtBox);
In above code the Name property will be used to find this control. All the remaining properties are familiar to you as in our designer file. At the last we have added this textbox to the form, here the keyword this is pointing Form1.
This form will look like the following screenshot: 

find control in windows form


In click event of button when we will try to access above controls then we notice that "textBox1" will be accessed by its name and "txtBox" will not accessed here.

To access these dynamically added controls we have to use a pre-defined method Find(). This method searches the controls by their name and builds an array as in below code.

Control[] controls = this.Controls.Find("txtBox", false);
foreach (var item in controls)
{
     TextBox txtBox = item as TextBox;
     if (txtBox != null)
        MessageBox.Show("control accessed");
}

In above set of code "controls" will hold the array of all the controls having name "txtBox". One by one we will access items of array and check the type of item. If type of item is TextBox then we found our textbox having name "txtBox".

As we know about naming standards of programming that two controls of the same name cannot exists. Keep in mind the above line, and we are sure that, there will only one control named “txtBox” of type TextBox.

Now we will access the above textbox in one line of code i.e.

TextBox txtBox1 = this.Controls.Find("txtBox", false).First() as TextBox;
if (txtBox1 != null)
 MessageBox.Show("control accessed");

When we run our project and click on button then our form look like this.
find control


Sunday, June 9, 2013

How to drag and drop items from one CheckedListBox to another in windows forms

Most of the GUI based application provides Drag-n-Drop operation. This function enables the user to drag an item from one location and drop to another location. In our previous post we have studied how to bind CheckedListBox using database. Now we will perform Drag-n-Drop operation with two CheckedListBox.


There are series of events that needs to be handled to perform this Drag-n-Drop operation, these are:

MouseDown (of source control): this event is occur when the mouse pointer is over the control and mouse button is pressed. It is beginning point of this operation, where DoDragDrop() method is called to set the data that is to be dragged.
DragEnter (of destination control): occur when mouse drag an item into area of this control. Here, we check that the desired type of data are present or not.
DragDrop (of destination control): occur when Drag-n-Drop operation completed. Here, we retrieve the dragged data and drop it.

Before we start this operation do insert some items in checkedListBox1 i.e.


string[] items = new string[] { "item 1", "item 2", "item 3", "item 4", "item 5" };

checkedListBox1.Items.AddRange(items);

Steps to perform this operation:
Step 1
            Initiate Drag-n-Drop operation for checkedListBox1 by calling DoDragDrop() method from MouseDown event of the control.


Drag-n-Drop

Step 2
            Handle the event to provide information about the operation to the user i.e. DragEnter event of checkedListBox2.


Drag-n-Drop2

Step 3
            To enable to checkedListBox2 to accept the data, set its AllowDrop property to true.
            checkedListBox2.AllowDrop = true;

Step 4
            Handle DragDrop event of checkedListBox2 to specifying what is to be done with dropped data.


DragDrop event of checkedListBox2

Download Example here.
© Copyright 2013 Computer Programming | All Right Reserved