Tuesday, 8 April 2014

Window Form/Window application Tutorial

.

Connect sql server with windows application

In This tutorial we will learn how to connect sql server with windows application

Create a login form with Sql Server

Here we will learn how to create a login form with Sql Server

Password protection using code.

In This tutorial we will learn how we do password protection using code.

Use of Group Box and Picture Box in window form.

Here we will learn how to use of Group Box and Picture Box in window form.

Open second from using first form in window form

In This tutorial we will learn how to open second from using first form in window form

Insert data into dataBase in window form application

Here we will learn how Insert data into dataBase in window form application

Edit And Update data from database in window form.

In This tutorial we will learn how Edit and Update data from database in window form.

Delete data from database in window form

Here we will learn how to Delete data from database in window form

Use of comboBox in windows form

In This tutorial we will learn how to Use of comboBox in windows form

How to Link combobox with database

Here we will learn how to Link combobox with database

Database values in textbox if select Combobox in window form

In This tutorial we will learn Database values in textbox if select Combobox in window form

Link list box with DataBase in window form

Here we will learn how to Link list box with DataBase in window form

Database value in textBox if selected in listbox in window form

In This tutorial we will learn Database value in textBox if selected in listbox in window form

Show database value in DataGridView in window application

Here we will learn how to Show database value in DataGridView in window application

How to use chart graph in window appliaction

In This tutorial we will learn How to use chart graph in window appliaction

How to link chart Graph with database in window form

Here we will learn How to link chart Graph with database in window form

Dynamically display Current date and time in window form

In This tutorial we will learn How to Dynamically display Current date and time in window form

How to use progressBar and button in window appliaction

Here we will learn How to use progressBar and button in window appliaction

How to Exit from this application

In This tutorial we will learn How to Exit from this application

Change column title of datagridview

Here we will learn How to Change column title of datagridview

Display selected Row from datagrid view to textBoxes

In This tutorial we will learn How to Display selected Row from datagrid view to textBoxes in windows application

How to use CheckBox and redio Button in window form

Here we will learn How to use CheckBox and redio Button in window form

How to use DateTime Picker and save in databas

In This tutorial we will learn How to How to use DateTime Picker and save in databas in windows application

How to use OpenFile Dialog and Copy that path

Here we will learn How to use OpenFile Dialog and Copy that path

Open File Text into TextBox and Rich TextBox

In This tutorial we will learn How to Open File Text into TextBox and Rich TextBox

Search_Highlight text in TextBox or richTextBox

Here we will learn How to Search_Highlight text in TextBox or richTextBox

Create a Text File and write in it in window application

In This tutorial we will learn How to Create a Text File and write in it in window application

Create Excel(.XLS and .XLSX) file from C# using excellibrary

Here we will learn How to Create Excel(.XLS and .XLSX) file from C# using excellibrary in windows application

How to export data from database to Excel file

In This tutorial we will learn How to export data from database to Excel file

How to import Excel File to DataGridView

Here we will learn How to import Excel File to DataGridView

How to Open and show a PDF file inside the form

In This tutorial we will learn How to Open and show a PDF file inside the form

How to launch any (_exe) file in any directory

Here we will learn How to launch any (_exe) file in any directory

Make application to beep and How to add a delay in second

In This tutorial we will learn to Make application to beep and How to add a delay in second

How to play a audio file in window application

Here we will learn How to play a audio file in window application

Random Number Generator within range

In This tutorial we will learn how to Generat Random Number within range

How to use and connect Sqlite in a window application

Here we will learn How to use and connect Sqlite in a window application

How to add a (window media palyer) video clip to the form

In This tutorial we will learn How to add a (window media palyer) video clip to the form

MP3 media Player in window application

Here we will learn How to create MP3 media Player in window application

How to load image in picture Box from computer

In This tutorial we will learn How to load image in picture Box from computer

Save Image in database

Here we will learn How to Save Image in database

Retrieving Image from database in window application

In This tutorial we will learn How to Retrieving Image from database in window application

SQL server database connection in Window Form


                                                                                                                                          Next

I will start first Tutorial with SQL server database connection. Here i will explain step by step. follow these steps.
step (1):- create a window form
Open visual stdio and create a new project and select window form application and give it name as First_Csharp app.

step (2):- Drag and down a button
now from tool box drag and down a button and click on button

step (3):-Database table
create a database table in sql server. here database name is windowapp and tablename is data


step (4):-Coding on button click
first insert a namespace "using System.Data.SqlClient".
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace First_Csharp_app
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                String str = "server=MUNESH-PC;database=windowapp;UID=sa;password=123";
                String query = "select * from data";
                SqlConnection con = new SqlConnection(str);
                SqlCommand cmd = new SqlCommand(query, con);
                con.Open();
                DataSet ds = new DataSet();
                MessageBox.Show("connect with sql server");
                con.Close();
            }
            catch (Exception es)
            {
                MessageBox.Show(es.Message);

            }
        }
    }
} 
step (5):-Run the application 
                                                                                                                                          Next



Monday, 10 February 2014

Properties in C#

                                                                                                                                              Previous....

                                                                                                                                                     Next.....



Properties are special kind of class member, In Properties we use predefined Set or Get method.They use accessors through which we can read, written or change the values of the private fields.

For example, let us Take a class named Employee, with private fields for name,age and Employee Id. We cannot access these fields from outside the class , but we can accessing these private fields Through properties.

Why We use properties
Marking the class field public & exposing is a risky, as you will not have control what gets assigned & returned.

To understand this clearly with an example lets take a student class who have ID, pass mark , name.Now in this example some problem with public field
  1. ID should not be -ve.
  2. Name can not be set to null
  3. Pass mark should be read only.
  4. If student name is missing No Name should be return.
To remove this problem We use Get and set method.
// A simple example
public class student
{
public int ID;
public int passmark;
public string name;
public class programme
{
    public static void main()
    {
       student s1 = new student();
       s1.ID = -101; // here ID can't be -ve
       s1.Name = null ; // here Name can't be null
    }
}

Now we take an example of get and set method

public class student
{
    private int _ID;
    private int _passmark;
    private string_name ;
    // for id property
   public void SetID(int ID)
   {
       if(ID<=0)
       {
         throw new exception("student ID should be greater then 0");
       }
       this._ID = ID;
    }
    public int getID()
    {
       return_ID;
     }
   }
   public class programme
   {
       public static void main()
       {
         student s1 = new student ();
         s1.SetID(101);
      }
      // Like this we also can use for Name property
      public void SetName(string Name)
      {
        if(string.IsNullOrEmpty(Name))
        {
          throw new exeception("name can not be null");
        }
        this._Name = Name;
     }
     public string GetName()
     {
        ifstring.IsNullOrEmpty(This.Name))
        {
          return "No Name";
       }
       else
      {
        return this._name;
      }
      // Like this we also can use for Passmark property
      public int Getpassmark()
      {
        return this._passmark;
      }
}                                                                                                                                             Previous....
                                                                                                                                                     Next.....

Exception Handling in C#

                                                                                                                                                                                                Previous....
                                                                                                                                                                                                    Next......


An exception is an error Which occurs during a program is running. 
C# exception handling has four keywords: trycatchfinally and throw.

Try: A try block identifies a block of code for which particular exceptions will be activated. It's followed by one or more catch blocks.

catch: A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The catch keyword indicates the catching of an exception.

finally: The finally block is used to execute a given set of statements, whether an exception is thrown or not thrown. For example, if you open a file, it must be closed whether an exception is raised or not.

throw: A program throws an exception when a problem shows up. This is done using a throw keyword.

Syntax

try
{
   // a statements 
}
catch( Exception e1 )
{
   // error handling code
}

finally
{
   // statements to be executed
}
     This article talks about best practices of exception handling, and guides you for some common programming mistakes developers do, as that seems appropriate in most applications written.

Best practices are only guidelines and do not enforce you to follow these, but if followed correctly then you won't only write less lines of code, but you work and code with more logical approach of coding and designing the code modules.


#1 Do Not Throw Exceptions to Control Application Flow

Scenario

The following code throws an exception inappropriately, when a supplied product is not found


.
public static void CheckProductExists(int ProductId)
{
    //... search for Product    if (ProductId == 0) // no record found throw error    {
        throw (new Exception("Product is  Not found in inventory"));
    }
    else    {
        Console.WriteLine("Product is available");
    }
}

static void Main(string[] args)
{   
     Console.WriteLine("Enter a ProductId you would like to search [1 – 100]"); 
     
 int productId = Int32.Parse(Console.ReadLine());
 
      CheckProductExists(productId);
      Console.ReadLine();
}

After execution of Main, and when 0 is passed as shown in Figure 1-1 below.
 Figure 1-1 Reading productId from Console

The value being passed to the program as shown in Figure 1-1 will result in an exception as shown in Figure 1-2 below.


Problem

Throwing an exception as shown in Scenario section and Figures 1-1 and 1-2 is expensive; presumably throwing an exception causes the CPU to fetch code and data it would otherwise not have executed. You probably should not throw any exceptions in that scenario.

Solution

Consider the possibility that the code shown above not finding a product is an expected condition. Hence, re-factor the code to return a value that indicates the search result after the method's execution. The following code re-writes the code to verify the availability of the product in inventory and sets a flag to true or false. 

This apparently avoids a new exception being thrown. The calling code uses a flag value to identify whether the inventory has the specified product or not.


public static bool CheckProductExists(int productId)
{
    //... search for Product    if (productId == 0) // no record found    {
        return false;
    }
    else    {
        return true;
    }
}

static void Main(string[] args)
{
    Console.Write("Enter a ProductId you would like to search [1 – 100] : "); 
    int productId = Int32.Parse(Console.ReadLine());

    if
 (!CheckProductExists(productId) == false)
    {
        Console.WriteLine("Found");
    }
    
else
    {
         Console.WriteLine("Not Available");
    }

    Console.ReadLine();}


#2 Use Validation Code to Reduce Unnecessary Exceptions
Scenario

Using a try/catch block can be a very handy solution for most programming situations, for example the most commonly known is DivideByZero. The following code uses a try/catch block to handle DivideByZero and that is pretty convincing.


static void Main(string[] args)
{
    Console.Write("Enter numerator : "); 
    int numerator = Int32.Parse(Console.ReadLine());

    Console.Write("Enter divisor : ");
    int divisor = Int32.Parse(Console.ReadLine());

    try    {
        double result = numerator / divisor;
        Console.WriteLine(result);
    }
    catch (DivideByZeroException ex)
    {
        Console.WriteLine(ex.Message);
    }
    
    Console.ReadLine();
}
Problem

There is no need to perform exception handling if we can use the basic validation techniques before code is executed. In this scenario an exception only needs to be handled if the divisor is 0 (zero) otherwise it should work fine.

Solution

Let's re-factor the code and rewrite it so try/catch blocks can be avoided, and as a result is more efficient.
 


static void Main(string[] args)
{
    Console.Write("Enter nemerator : ");
    int numerator = Int32.Parse(Console.ReadLine());

    Console.Write("Enter divisor : ");
    int divisor = Int32.Parse(Console.ReadLine());

    if (divisor != 0)
    {
        Console.WriteLine(numerator / divisor);
    }
    else
    {
        Console.WriteLine(Double.NaN);
    }
   
    Console.ReadLine();
}
Figure 1-4 Using validation code instead to avoid try/catch to handle an exception


                                                                                                    
                                                                                                                                                                                           Previous....
                                                                                                                                                      Next...

C# program Selection Sorting

Selection sort is a straightforward sorting algorithm. This algorithm search for the smallest number in the elements array and then swap i...