-->

Monday, April 14, 2014

How to Use Checkbox in WPF

Checkbox is a GUI element that permits the user to make a binary choice i.e. user may have to answer yes or no. Now a days programming have a new option to set the value to null. It means checkbox may be used as a three state which are checked, unchecked and intermediate.

The following screenshot shows three states of a checkbox

CheckBox control in WPF

In the above image all the three checkboxes have IsThreeState property to true and some more properties like the following code in xaml:
<CheckBox IsThreeState="True" Content="Checked" IsChecked="True"></CheckBox>
<CheckBox IsThreeState="True" Content="UnChecked" IsChecked="False"></CheckBox>
<CheckBox IsThreeState="True" Content="Intermediate" IsChecked="{x:Null}"></CheckBox>

IsChecked property is used to set the state of checkbox. You may have three options for these state values as I have used in above code snippet. Checkbox is mostly used in objective type answers or we can say Boolean type answers. Gender value may also be store through checkbox control.


We can perform the desired function, when the checkbox is checked or unchecked using the events respectively.
private void Checkbox_Checked(object sender, RoutedEventArgs e)
{
MessageBox.Show("Checkbox Checked");
}

private void Checkbox_Unchecked(object sender, RoutedEventArgs e)
{
MessageBox.Show("Checkbox Checked");
}
Each time when a checkbox is checked or unchecked, a message will be shown defined in the above code snippets. To add a checkbox dynamically with checked property true we can write the following code:

CheckBox chkBox = new CheckBox();
chkBox.Name = "checkBox";
chkBox.Content = "Checked";
chkBox.IsChecked = true;
chkBox.IsThreeState = true;
this.Content = chkBox;
The above code will replace all the content of the window with this checkbox. So if you want to add this to any other container like stackpanel or anything, then you have to add this as a children of that container.

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

Tuesday, November 19, 2013

Steps and Events Used to Create Custom Control in C#: Windows Forms

In my previous article I have explained what is Custom Control, its types and features in brief. In this article I will write some steps to create the custom control, and will create a currency textbox control that will accept only currency type value.

Steps to create Custom control


  • Open your windows forms project, and create a class. Name of class will be the control’s name, you want to create.
  • Define a property, type should be respective to the value stored e.g. decimal, string, int etc.
  • Override some of the required methods like onClick, onKeyPressed, onTextChanged and OnValidated in the sense of textbox, including the constructor (discussed later).
  • Build the project and the control will added in to your toolbox window.

As I said that to make a custom control we have to override some required events of the base class. Here below I am writing about the methods, required to make a custom textbox.

OnKeyPress: this event occurs when user pressed a key while the respective control have focus. It passes the current value, the control have. When we override this event it has the following Syntax:

protected override void OnKeyPress(KeyPressEventArgs e)
{
//your code
}

OnValidated: Occurs when the respective control is validating. When user change the focus by using keyboard, or any other way, this validating event will occur. Following syntax will be used to override this event.

protected override void OnValidated(EventArgs e)
{
//your code
}

OnClick: Raises when the user click on the control. Contains the function is to be executed, when user click on the control. Syntax:

protected override void OnClick(EventArgs e)
{
//your code
}

OnTextChanged: Occurs when the user change the text of the control. Contains the code to be executed, when user change the text of the control. Syntax:

protected override void OnTextChanged(EventArgs e)
{
//your code
}

In the next, we will create a currency TextBox, that will only accept the currency related value like decimal, control characters.

Make your own Custom CurrencyTextBox

Monday, November 18, 2013

How to Develop your Own Custom Controls in C#

Custom control, the control with combined features of other controls, can be developed by any programmer easily. A custom control will not only be usable in the same application, but also it can be used in any other application that may be on other system. This designed control can be easily embedded in other applications.

Custom control have some basic features as well as some functionality that may be known by the programmer:
  • Improves encapsulation.
  • Simplifying a programming model.
  • Can swap out a control with another one.
  • Combines UI elements in a simple way.
  • Using these controls programmer can develop unique controls.

Types

User Control: combines other controls in a logical unit. Inherit from System.Windows.Forms.UserControl class.

Inherited controls: developed by an existing .NET control that is as close as you want to develop. We have to create a custom class and inherit an existing abstract class that is close to what we are developing.

Owner-drawn controls: inherit from a base class like System.Windows.Forms.Control. These controls provides most customizable UI.

Extender providers: These are used to add features to other controls on a form, means these are not necessarily at all.

These controls may be used in our other applications and it reduces the amount of code and the code duplication. It also helps in modularize your code. In the next article we will explain about the steps to create a custom control and also about the events, need to override to create custom textbox.

Sunday, November 10, 2013

How to set PictureBox Image using OpenFileDialog or Bitmap Class: WindowsForms

A person’s basic properties are name, age, date of birth, contact no. and also have a picture of that person. To insert the picture we have to preview that picture at the same time we are loading the picture. That’s why we need this picture box control on the windows forms.

Picture Box control is used to display pictures that may be jpeg, jpg, png or any bitmap file. The picture can be set during run time by the user, or can be fixed by the programmer during design time. It have many properties to be used by the programmer, to make the picture adjustable.
Picture box have some common properties that are mostly used by, which are:

  • SizeMode: used to control the clipping and positioning of the image in the display area.
  • ImageLocation: specify the image to be displayed.
  • ClientSize: used to change the size of the display area at run time.
  • BorderStyle: to distinguish the control from the rest of the form, even it have no image.

Drag-n-drop a picture box which will hold the image and button to be used to browse the image. The form will look like the image below:

How to set PictureBox Image using OpenFileDialog or Bitmap Class: WindowsForms

Generate the click event of button and write the following C# code:
OpenFileDialog ofd = new OpenFileDialog();
ofd.ShowDialog();
pictureBox1.ImageLocation = ofd.FileName;
pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;

When you run this project and click on the button, it will show an openFileDialog box. You have to select an image file and click on OK button. At the last the picture has been set on the picture box as shown in the below image.

How to set PictureBox Image using OpenFileDialog or Bitmap Class: WindowsForms

It is not required to set the picture as above, we can set an object also of the Image class in the System.Drawing namespace. For that, just create an object of Bitmap class and set that object to the image property of picture box, as described in the below code:
Bitmap bt = new Bitmap(“image path”);
pictureBox1.Image = bt;
pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;

The most thing to be noticed in the second code, is we have to know the exact path of the image file. Run the code and it will give the same output as the first code provide.

See Also: OpenFileDialog in windows forms

Saturday, October 12, 2013

Check If File Exist or Not at Specified Location: C#

We can specify the extension of files, to be opened using OpenFileDIalog as I have explained in Use Filters in Open File Dialog. Let suppose user have been copied a file at a specified location and save that location for future reference. After some time, when user want to use that file with that location and, the file is not there, then it will throw an exception.


To avoid that exception, we have to check that file’s existence at the given location. The existence of file can be check through File.Exist() method, which resided in System.IO.File class in Visual Studio.

The following c# code will check the file named “ab.jpg” in our current directory which is Debug folder of the solution.
if (File.Exists(Environment.CurrentDirectory + "\\ab.jpg"))
{
//Write your code to execute
}
else
MessageBox.Show("File Not Exist");

If the file exist at the debug folder, it will execute our line of code, and if file not exist, it will show a message containing “File Not Exist”.

How to check file's existence in windows forms C#


See Also: Use Filters to Open Desired Files

Friday, October 11, 2013

How to Specify Filters in OpenFileDialog: Windows Forms

To open an existing file on the system, open file dialog box is used. Create an object of OpenFileDialog class and call the ShowMethod() to open this type of dialog box. I have explained about this dialog box in my previous article i.e. Use OpenFileDialog to open an existing file.

In many Software, we can select only the specified type of file such as excel, word or text files. In Windows forms we can also use this feature by using filters for this dialog box.

Add a windows form project and write the following code in C# language:
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "jpg files: |*.jpg";
ofd.Title = "Images";
ofd.ShowDialog();

Now in the above code, I have specified the type of file, user have to select. Using above code the user have to select only jpg files. Run this code and it will show an open file dialog look like the following:

How to use filters in open file dialog: Windows Forms C#

We can change these filter as per our requirements, even we can specify some more filters in a single file dialog. Check out the below line of code:

ofd.Filter = "jpg files: |*.jpg; *.jpeg;*.png";

The above line, when used, can select these three type of files as specified.

Previous:  Open File Dialog in Windows Forms                 Next: Check If File Exist or Not

How to Use Images in Treeview: WPF

Image control can be placed in any other control such like Treeview, Toolbar control or any other controls. The images can be stored in your solution files. To place an image in Treeview control using following simple steps.

Place a stackpanel with horizontal orientation and look like following structure:
 <StackPanel Orientation="Horizontal" Height="30">
<Label Content="first"></Label>
<Image Source="buttonImage.png"></Image>
</StackPanel>

The XAML code will place a label and an image in a stack panel. Now to use this in treeview control just place it in between the treeview item code.
<TreeView HorizontalAlignment="Left" VerticalAlignment="Top" Margin="5">
<TreeViewItem Header="Item1">
<StackPanel Orientation="Horizontal" Height="30">
<Label Content="first"></Label>
<Image Source="buttonImage.png"></Image>
</StackPanel>
</TreeViewItem>
</TreeView>

A single treeview item will be placed in the WPF window. Now write the following code to place three treeview items each having an image:
<TreeView HorizontalAlignment="Left" VerticalAlignment="Top" Margin="5">
<TreeViewItem Header="Item1">
<StackPanel Orientation="Horizontal" Height="30">
<Label Content="first"></Label>
<Image Source="buttonImage.png"></Image>
</StackPanel>
</TreeViewItem>
<TreeViewItem Header="Item2">
<StackPanel Orientation="Horizontal" Height="30">
<Label Content="second"></Label>
<Image Source="image1.png"></Image>
</StackPanel>
</TreeViewItem>
<TreeViewItem Header="Item3">
<StackPanel Orientation="Horizontal" Height="30">
<Label Content="third"></Label>
<Image Source="image2.png"></Image>
</StackPanel>
</TreeViewItem>
</TreeView>

Run the project and expand each of the node of treeview, each node have its label and an image as shown in the following image:

How to use images in Treeview control WPF XAML

See Also: Place an Image in Toolbar
© Copyright 2013 Computer Programming | All Right Reserved