-->

Sunday, July 7, 2013

Round off value in DataGridView Cell

In most of the situations programmer want to save value in decimal data type, but try to show that value in approximate format. For example we have a variable "income" that have some different value as below
income = 3.57 (stored in database exactly)
income = 3.6 (programmer want to show the user)

The decimal data type can store maximum of 38 digits. It stores exact representation of the number, there is no approximation of the stored value. Decimal data type can be used to store numbers with decimals when the values must store exactly as specified. We can read more about decimal values from http://msdn.microsoft.com/en-us/library/ms187912(v=sql.105).aspx

In above case programmer want to round off that value at run time binding. As we know about datagridview binding in which data will be shown as same as they are stored in our database. When we bind our list to datagridview it means we are binding each cell one by one. If we want to check which cell is binding to what value then we can do this in Cell Formatting event of datagridview.

Datagridview cell formatting event occurs when the contents of a cell need to be formatted for display. If the standard formatting is insufficient, we can customize the formatting by handling this event. This event occurs every time each cell is painted. Go through datagridview cell formatting event if you want to know more about cell formatting event.

Your cell formatting event should look like the below code if you want to round off all the decimal values bind to this datagridview.

private void dataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
double decValue;
if (e.Value == null)
return;
if (double.TryParse(e.Value.ToString(), out decValue) == false)
return;
e.Value = Math.Round(decValue);
}

This code will work only with decimal values. It will do nothing if either “value is null” or “value is not type of decimal”. If the value is of type decimal it will round off that value using Math.Round() method. This method rounds a value to its nearest integral value.

Saturday, July 6, 2013

How to check minimum or maximum value of integer data type

According to msdn ,  minimum and maximum value of Integer datatype are : -2,147,483,648 to 2,147,483,647.

Let's have an example :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace tutorial
{
   class Program
 {
   static void Main(string[] args)
 {
   int a = 0;
Console.WriteLine("minimum value of" + int.MinValue);
Console.WriteLine("maximum value of" + int.MaxValue);
Console.ReadKey();
 }
 }
}

Output
output
Here:
 MinValue field Represents the smallest possible value of System.Int32. This field is constant.
MaxValue field Represents the largest possible value of System.Int32. This field is constant

 

Wednesday, July 3, 2013

Use XML file as database

Sometimes, when we are creating small application, we have to use SQL Server database if we don’t know about any alternative solution. SQL Server databases are very familiar with programmers, but if our application is small then we don’t let the user install and maintain any database engine.



We have an alternative solution i.e. XML (Extensible Markup Language) files that is a textual data format. It is widely used for the representation of arbitrary data structures, for example in web services. We can read more about Xml files through http://en.wikipedia.org/wiki/XML.



To work with XML files we use XmlSerializer class that serializes and deserializes objects into and from XML documents. It is in System.Xml.Serialization namespace and enables us to control how objects are encoded into XML. The most important methods in this class are Serialize and Deserialize.



In this article we will serialize a class Person consists of public properties, as shown below:

public class Person
{
     public string Name { get; set; }
     public string FName { get; set; }
     public int Age { get; set; }

}

Write data to XML file:

To write data in XML file we use Serialize method that serializes the specified object and writes the XML document to a file using the specified stream. It takes two parameters.

First parameter will be used to write the data to file, it may be either a FileStream or an XmlWriter. Second parameter is the data that is to be written.



List<Person> personList = new List<Person>();
XmlSerializer serializer = new XmlSerializer(typeof(List<Person>));
using (FileStream stream = new FileStream(Environment.CurrentDirectory + "\\file.xml", FileMode.Create, FileAccess.Write))
{
    serializer.Serialize(stream, personList);
}



In above code


  • Add some data to personList that are to be written to file.
    personList.Add(new Person() { Name = "Student1", FName = "Father1", Age = 25 });
    personList.Add(new Person() { Name = "Student2", FName = "Father2", Age = 24 });
    personList.Add(new Person() { Name = "Student3", FName = "Father3", Age = 26 });
    personList.Add(new Person() { Name = "Student4", FName = "Father4", Age = 23 });

  • Create an object of XmlSerializer class which will decide the type of data that is to be written (list of person here).
  • Create a stream having FileMode Create and FileAccess Write.
  • At the last serialize the list to stream and stream will write it to xml file.

Read data from XML file:


To read data from XML file we use Deserialize method that deserialize the xml document contained by stream. It takes only one parameter i.e. our stream.


List<Person> accessedData = new List<Person&gt
XmlSerializer serializer = new XmlSerializer(typeof(List<Person>));
using (FileStream stream = new FileStream(Environment.CurrentDirectory + "\\file.xml", FileMode.Open, FileAccess.Read))
{
    accessedData = serializer.Deserialize(stream) as List<Person>;
}
dataGridView1.DataSource = accessedData;

In above code
  • Declare a list of person that will hold deserialized data.
  • Create an object of XmlSerializer class which will decide the type of data that is to be read (list of persons here).
  • Create a stream having FileMode Open and FileAccess Read.
  • At the last deserialize the data and convert them to List<Person>.
After successfully deserialize the data in list, i am bind that list to datagridview. When i run the project, my datagridview look like following screenshot:


We can read more about Environment.CurrentDirectory

Tuesday, July 2, 2013

How to use CompareValidator Control in ASP.NET

Introduction
The CompareValidator control is used to compare the value entered by a user into one input control with the value entered into another input control or with an already existing value. The CompareValidator control exists within the System.Web.UI.WebControls namespace.

Operator Properties of the CompareValidator Control
Equal : Checks whether the compared values are equal .

NotEqual : Checks that controls are not equal to each other.

GreaterThan : Checks the greater than relationship.

GreaterThanEqual : Checks for a greater than or equal to relationship.

LessThan : Checks for a less than relationship.

LessThanEqual : Checks for a less than or equal to relationship.

DataTypeCheck : Compare dataTypes between the value entered into the data-entry .

The Type property is used to specify the data type of both the comparison values, where String is the default type. Both values are automatically converted to the string data type before the comparison operator is performed . The different data types that can be use are as follows

String : A string data type.
Integer : An Integer data type.
Double : A double data type.
Date : A date data type.
Currency : A currency data type.
Public Properties of the CompareValidator class

ControlToCompare : Obtains or sets the data entry , which has to be compared with the data-entry control.
Operator : Obtains or sets the comparison operation to perform.

ValueToCompare: Obtains or sets a constant value to compare with the value entered by a user in the data entry control being validated.

Example


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

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>





Enter password :
 
 
<asp:TextBox ID="pwd" runat="server"></asp:TextBox>
<br />
<br />
Re-Enter:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<asp:TextBox ID="repwd" runat="server"></asp:TextBox>
<asp:CompareValidator ID="CompareValidator1" runat="server" ControlToCompare="pwd" ControlToValidate="repwd" ForeColor="Maroon">Password does not match</asp:CompareValidator>
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="Check Comparison" />




 
 
</div>
</form>
</body>
</html>
Output
comparevalidator

Sunday, June 30, 2013

How to use ImageButton Control in ASP.NET

Introduction
The ImageButton control is a Button control that displays an image instead of text . The ImageButton control exists within the System.Web.UI.WebControls namespace . This control is specifically useful when you want to create image maps . Image maps are clickable regions on images and can initiate various actions depending on part of the image that you click.

Public Properties of the ImageButton Class:

CauseValidation : Obtains or set a value showing whether or not validation is performed when the ImageButton control is clicked.

CommandArgument : Obtains or sets a argument that provides information about the CommandName property

CommandName : Obtains or sets the command name related to the ImageButton control

Enabled : Obtains or sets a value indicating whether the ImageButton control can be clicked to perform a PostBack operation to the server.
GenerateEmptyAlternateText : Obtains or sets a value showing whether the control generates an alternate-text attribute for an empty string value.

OnClientClick : Obtains or sets the client-side script , which is executed when an ImageButton control's Click event fired.

PostBackUrl : Obtains or sets the url of the web page to post from the current web page when the ImageButton control is clicked.

ValidationGroup : Obtains or sets the group of controls for which the ImageButton control cause validation when they are post back to the server.


Public Events of the ImageButton Class
Click : occurs when the ImageButton is clicked . The event cause the page to be posted back to the server.

Command : occurs when the ImageButton is clicked . The Command event is raised through this control hierarchy in the form of the BubbleEvent.

Example

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

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
 
        <asp:Label ID="Label1" runat="server" Text="Image Button Control Example"></asp:Label>
        <br />
        <asp:Label ID="Label2" runat="server" Text="Click any where on the  ImageButton Control Bellow"></asp:Label>
 
    </div>
        <asp:ImageButton ID="ImageButton1" runat="server" Height="81px" ImageUrl="~/samsung.jpg" OnClick="ImageButton1_Click" Width="189px" />
        <br />
        <br />
        <asp:Label ID="Label3" runat="server" Text="You Clicked on the image button at following co-ordinate"></asp:Label>
        <p>
            <asp:Label ID="result" runat="server" BackColor="#FF6600"></asp:Label>
        </p>
    </form>
</body>
</html>

Code Behind 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 imageButton : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
    {
        result.Text = e.X.ToString() + "," + e.Y.ToString();
    }
}
OutPut


imagebutton
 
 

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


Online Voting System Project in ASP.NET

Introduction:
Online voting system is a web based solution.It removes traditional voting system problems such as :
  • Take more time and human resources
  • Does not give instant poll result
  • False voter
  •  Inefficient

Online voting system project



Those problem are major problem in traditional system . If you want to remove such types of problem in traditional system then you will use web-based solution.

Features of Online voting system:
  • Detect false voter
  • Instant poll result
  • Easy method for vote count
  • keep global information
System Requirements : 
  • Visual studio 2010 
  • SqlServer 2008
  • Internet connection
  • Mail_id
 How to run this project :

  • Open website folder in Visual studio 2010
  • Run your project by selecting green triangle button
  • Open voter register page 
  • Fill some required filled and click on submit button
  • Login in Admin panel by username and password
  • Approve Voter by changing flag bit (0 to 1)
  • After approval login in your mail id and copy your secure code
  • Login in voter login panel and fill some required filled(voter-id , securecode , email )
  • After login you can vote now of your desired candidate .
  • Count total vote by admin
  • Show result by admin
If you want to purchase this please contact me on :  narenkumar851@gmail.com

Project Demo
© Copyright 2013 Computer Programming | All Right Reserved