-->

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

How to change Application name in Windows Store Grid App

Introduction

In our previous article, we have studied about Windows Store Grid App. In this article we will learn about App.xaml file and their behaviors also take a simple example to change Application name.

Pre-requisite

  • You need windows 8 SDK
  • You need developer license

General Structure of App.xaml file

<Application
    x:Class="FirstGridApplication.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:FirstGridApplication"
    xmlns:localData="using:FirstGridApplication.Data">

    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>

                <!--
                    Styles that define common aspects of the platform look and feel
                    Required by Visual Studio project and item templates
                 -->
                <ResourceDictionary Source="Common/StandardStyles.xaml"/>
            </ResourceDictionary.MergedDictionaries>

            <!-- Application-specific resources -->

            <x:String x:Key="AppName">FirstGridApplication</x:String>
        </ResourceDictionary>
    </Application.Resources>

</Application>

If you want to change Application name in Grid App then you should go for  App.xaml file and change in markup as specified in below XAML code

 <x:String x:Key="AppName">FirstGridApplication</x:String>

First Output Page
How to change Application name in Windows Store Grid App

<x:String x:Key="AppName">My Application</x:String>

After change Output will become

How to change Application name in Windows Store Grid App



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.

Getting Started with Windows Store Grid App (XAML)

Introduction

The Grid App is basically used for navigating between categories. User can search contents between categories for example, photo and video apps in Windows 8. In this article we will discuss basics about windows store Grid App. Lets start windows Store Grid Apps with some simple steps. Select  File->New Project->Windows Store Grid (XAML) under the "Windows Store" category.

Windows Store Grid(XAML)

After selecting "OK" button you have successfully created windows Store Grid Application and by-default application page will be opened. This app contains many files shown in Solution Explorer:

Windows Store Grid App(XAML) : Solution explorer

The Grid App template includes these .xaml files:

App.xaml, where you can change your application name also provides markup for the content Host.
GroupedItemsPage.xaml, it is the first page of the application. It contains Application name, Group name, Item name with sub-title. It enables a user to select an item to navigate to the full-page item view, or to select a group label to navigate to the group details page.
GroupedItemsPage.xaml in windows store Grid App

GroupDetailPage.xaml, It shows Group name with short description and also item name with short description, and select an item to navigate to the full-page item view.
GroupDetailPage.xaml in windows store Grid Apps

ItemDetailPage.xaml, which is the full-page view for an item.
ItemDetailPage.xaml in windows store Grid Apps

Programmatically Change RadioButtonList BackGround Color in ASP.NET

Introduction

In this example we will show that how to change backGround color of the RadioButtonList. There are two methods for changing background color, first method contains Color structure and second method contain style sheet.

Algorithm behind the scene 

Step-1: Add a RadioButtonList and Button control on WebForm.
Step-2: Generate the Click event of Button
Step-3: Change color using System.Drawing.Color.Beige structure.
Step-4: In Second Method add attribute with RadioButtonList.

Example of change RadioButtonList BackGround.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default4.aspx.cs" Inherits="Default4" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
        <asp:RadioButtonList ID="RadioButtonList1" runat="server" Height="26px" Width="201px">
            <asp:ListItem>ASP.NET</asp:ListItem>
            <asp:ListItem>WINDOWS PHONE</asp:ListItem>
            <asp:ListItem>C#</asp:ListItem>
            <asp:ListItem>WINDOWS STORE</asp:ListItem>
        </asp:RadioButtonList>
        <br />
        <asp:Button ID="Button1" runat="server" Height="32px" Text="First Method " Width="108px" OnClick="Button1_Click" />
        <br />
        <br />
        <asp:Button ID="Button2" runat="server" Height="32px" Text="Second Method" Width="108px" OnClick="Button2_Click" />
   
    </div>
    </form>
</body>

</html>

Codebehind code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Default4 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        RadioButtonList1.BackColor = System.Drawing.Color.Bisque;

    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        RadioButtonList1.Attributes.Add("Style", "Background-color:Red");
    }
}


Output



Friday, November 15, 2013

How to Remove Record Entry in DataGridView by Command Button: Windows Form

Binding datagridview only is not sufficient for a programmer, he/she need to be known about how to remove unnecessary records from the list. For that we have to first bind our list of item to datagridview and then add a command button with text “Remove” as discussed in earlier post.

To remove an entry, either we have to find out the record’s unique detail or the index of the record in temporary list of items. Because we are binding the datagridview with the temporary list, that’s why we can remove this record using only the index of the record.
Bind a datagridview with the list of items and then add a command button with the text property to “Remove”. Our main motive in this article here is to access the command column, we have discussed earlier. So generate the Cell_Click event of datagridview and write the following c# code:
if (e.ColumnIndex == 0)
{
stuList.RemoveAt(e.RowIndex);
dataGridView1.DataSource = null;
dataGridView1.DataSource = stuList;
}
Run the form and click on remove button of any row you want to delete. And it will remove that record from the list only.
Form having all the rows:
How to Remove Record Entry in DataGridView by Command Button: Windows Form

Form after deleting the last row, it will show only two records.

How to Remove Record Entry in DataGridView by Command Button: Windows Form

Suppose, the user don’t want to remove, and by mistake he/she has clicked on the button then what? We have to use a confirmation message, record will be deleted only when user presses “Yes” and do nothing if user clicked on “No”. Write the following code replacing above code:
if (e.ColumnIndex == 0)
{
DialogResult result = MessageBox.Show("Sure Delete!", "Confirmation", MessageBoxButtons.YesNo);
if (result==DialogResult.Yes)
{
stuList.RemoveAt(e.RowIndex);
dataGridView1.DataSource = null;
dataGridView1.DataSource = stuList;
}
}
Run the code, it will show a confirmation message box as below. If you click on “Yes” it will delete it, and if you click on “No” it will do nothing. You can change the code as per your requirements.
© Copyright 2013 Computer Programming | All Right Reserved