Wednesday, July 1, 2009

Sample Program in VB.Net 2005


Imports System
Imports System.Data.SqlClient
Imports System.DBNullImports System.IO
Public Class Form1
Public cnstr As String = "Data Source=VIJAY\SQLEXPRESS;Initial Catalog=giri;Integrated Security=True"
Public cn As New SqlConnection(cnstr)
Public cmd As SqlCommand
Public ada As SqlDataAdapter
Public dtb As New DataTable

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
loaddata()
autonum()
TextBox1.Focus()
End Sub

Private Sub BtnNew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnNew.Click
autonum()
End Sub

Private Sub BtnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnSave.Click
Try
If Not validation() Then
Exit Sub
End If

Dim str As String
If MessageBox.Show("Do u want to save ?", " Sample Code", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
str = "insert into tst(code,name) values(" & TextBox1.Text & ",'" & TextBox2.Text & "')"
If SendDataStr(str) = True Then
MessageBox.Show("Details are SAVED sucessfully", "Sample Code ", MessageBoxButtons.OK, MessageBoxIcon.None)
clear()
loaddata()
autonum()
Else
MessageBox.Show(" error in data")
End If
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub


Private Sub BtnEdit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnEdit.Click
Try
If Not validation() Then
Exit Sub
End If

Dim str As String
If MessageBox.Show("Do u want to save ?", "Sample Code", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
str = "update tst set name='" & TextBox2.Text & "' where code=" & TextBox1.Text & ""
If SendDataStr(str) = True Then
MessageBox.Show("Details are update sucessfully", "Sample Code ", MessageBoxButtons.OK, MessageBoxIcon.None)
clear()
loaddata()
autonum()
Else
MessageBox.Show(" error in data")
End If
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub

Private Sub BtnDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnDelete.Click
If Not validation() Then
Exit Sub End If
Dim str As String
If MessageBox.Show("Do u want to save ?", "Sample Code", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
str = "delete from tst where code=" & TextBox1.Text & ""
If SendDataStr(str) = True Then
MessageBox.Show("Details are deleted sucessfully", "Sample Code", MessageBoxButtons.OK, MessageBoxIcon.None)
clear()
loaddata()
autonum()
Else
MessageBox.Show(" error in data")
End If
End If
End Sub

Private Sub DataGridView1_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles DataGridView1.DoubleClick
Try
'vb.net 2003'
'Dim row As Integer = DataGrid.CurrentRowIndex
'txtcode.Text = DataGrid.Item(row, 0)
'txtname.Text = DataGrid.Item(row, 1)
'--------------------------------------------
'vb.net 2005
Dim row As Integer = DataGridView1.CurrentRow.Index
TextBox1.Text = DataGridView1.Rows(row).Cells(0).Value
TextBox2.Text = DataGridView1.Rows(row).Cells(1).Value
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub

Private Sub BtnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnExit.Click
If MessageBox.Show("Do u want exit?", "Sample Code", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
Me.Close()
Else
TextBox1.Focus()
End If
End Sub

Private Sub BtnLoad_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnLoad.Click
Try
loaddata()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub

Private Sub BtnClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnClear.Click
clear()
End Sub

Public Function validation()
If TextBox1.Text = "" Then
MessageBox.Show("Enter the Name", "Sample Code", MessageBoxButtons.OK, MessageBoxIcon.Information)
TextBox1.Focus()
Return False
End If
If TextBox2.Text = "" Then
MessageBox.Show("Enter address1", "Sample Code", MessageBoxButtons.OK, MessageBoxIcon.Information)
TextBox2.Focus()
Return False
End If
Return True
End Function

Public Sub DATAOPEN()
If ConnectionState.Open Then cn.Close()
cn.Open()
End Sub

Public Sub DATACLOSE()
cn.Close()
End Sub

Public Function getdatastr(ByVal cmdstr As String)
Try
DATAOPEN()
dtb = New DataTable("data")
ada = New SqlDataAdapter(cmdstr, cn)
ada.Fill(dtb)
Return dtb
DATACLOSE()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Function

Public Function SendDataStr(ByVal cmdstr As String) As Boolean
Try
cmd = New SqlCommand(cmdstr, cn)
DATAOPEN()
cmd.ExecuteNonQuery()
DATACLOSE()
Return True
Catch ex As Exception
MsgBox(ex.Message)
Return False
End Try
End Function

Public Sub loaddata()
Dim dtb As DataTable = getdatastr("select * from tst order by code") DataGridView1.DataSource = dtb
End Sub

Public Sub autonum()
Try
Dim dtb As DataTable = getdatastr("select max(code)+1,0 from tst") TextBox1.Text = dtb.Rows(0).Item(0)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub

Public Sub clear()
TextBox1.Text = ""
TextBox2.Text = ""
End Sub

Private Sub Form1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
'first you set below instruction
' form-right click -->properties --> key preview = true

If e.KeyCode = Keys.Enter Then
SendKeys.Send("{tab}")
End If
End Sub
End Class

Abstract and Sealed Classes

Abstract and Sealed Classes and Class Members (C# Programming Guide)

The abstract keyword enables you to create classes and class members solely for the purpose of inheritance—to define features of derived, non-abstract classes. The sealed keyword enables you to prevent the inheritance of a class or certain class members that were previously marked virtual. For more information, see How to: Define
Abstract Properties (C# Programming Guide).
Abstract Classes and Class Members
Classes can be declared as abstract. This is accomplished by putting the keyword abstract before the keyword class in the class definition. For example:

C# Copy Code
public abstract class A
{
// Class members here.
}
An abstract class cannot be instantiated. The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share. For example, a class library may define an abstract class that is used as a parameter to many of its functions, and require programmers using that library to provide their own implementation of the class by creating a derived class.

Abstract classes may also define abstract methods. This is accomplished by adding the keyword abstract before the return type of the method.

For example:C# Copy Code
public abstract class A
{
public abstract void DoWork(int i);
}
Abstract methods have no implementation, so the method definition is followed by a semicolon instead of a normal method block. Derived classes of the abstract class must implement all abstract methods. When an abstract class inherits a virtual method from a base class, the abstract class can override the virtual method with an abstract method.

For example:C# Copy Code
// compile with: /target:library

public class D
{
public virtual void DoWork(int i)
{
// Original implementation.
}
}
public abstract class E : D
{
public abstract override void DoWork(int i);
}

public class F : E
{
public override void DoWork(int i)
{
// New implementation.
}
}
If a virtual method is declared abstract, it is still virtual to any class inheriting from the abstract class. A class inheriting an abstract method cannot access the original implementation of the method—in the previous example, DoWork on class F cannot call DoWork on class D. In this way, an abstract class can force derived classes to provide new method implementations for virtual methods.

Sealed Classes and Class Members

Classes can be declared as sealed. This is accomplished by putting the keyword sealed before the keyword class in the class definition.

For example:C# Copy Code
public sealed class D
{
// Class members here.
}

A sealed class cannot be used as a base class. For this reason, it cannot also be an abstract class. Sealed classes are primarily used to prevent derivation. Because they can never be used as a base class, some run-time optimizations can make calling sealed class members slightly faster.

A class member, method, field, property, or event, on a derived class that is overriding a virtual member of the base class can declare that member as sealed. This negates the virtual aspect of the member for any further derived class. This is accomplished by putting the sealed keyword before the override keyword in the class member declaration.

For example:C# Copy Code
public class D : C
{
public sealed override void DoWork()
{ }
}

Inheritance in C#

Inheritance in C#
This article discusses Inheritance concepts in the context of C#. Before we understand Inheritance in C# it is important to understand the key players involved, viz. Objects, Classes and Structs.
Classes and Structs are ‘blue-prints’ or templates from which we instantiate (create) objects. Example a car may be created based on its blue print. Car is the object and blue print is the class (or template).
What are types?
An object can be of the following types – Class or Struct. There are many differences between the two ‘types’. The main difference between the two is the way in which they are stored in memory and the way they are accessed. Classes are also called reference types Structs are known as value types. Classes are stored in a memory space called ‘heap’ and Structs are stored in a memory space known as ‘stack’
Constructors:
In C#, (like other Objected Oriented languages) constructor is a method having the same name as the class. The constructor is called when the object is being created. It can have one or more parameters.
Interfaces:
In the context of C#, an interface provides a contract. A class that is derived from this interface will implement the functions specified by the interface.
Inheritance:
C# supports two types of Inheritance mechanisms 1) Implementation Inheritance 2) Interface Inheritance
What is Implementation Inheritance?
- When a class (type) is derived from another class(type) such that it inherits all the members of the base type it is Implementation Inheritance
What is Interface Inheritance?
- When a type (class or a struct) inherits only the signatures of the functions from another type it is Interface Inheritance.
In general Classes can be derived from another class, hence support Implementation inheritance. At the same time Classes can also be derived from one or more interfaces. Hence they support Interface inheritance. Structs can derive from one more interface, hence support Interface Inheritance. Structs cannot be derived from another class they are always derived from System.ValueType
Multiple Inheritance:
C# does not support multiple implementation inheritance. A class cannot be derived from more than one class. However, a class can be derived from multiple interfaces.
Inheritance Usage Example: Here is a syntax example for using Implementation Inheritance.
Class derivedClass:baseClass { }
derivedClass is derived from baseClass.
Interface Inheritance example:
private Class derivedClass:baseClass , InterfaceX , InterfaceY{ }
derivedClass is now derived from interfaces – InterfaceX, InterfaceY Similarly a struct can be derived from any number of interfaces
private struct childStruct:InterfaceX, InterfaceY{}
Virtual Methods: If a function or a property in the base class is declared as virtual it can be overridden in any derived classes Usage Example:
class baseClass { public virtual int fnCount() { return 10;} } class derivedClass :baseClass {public override int fnCount() { return 100;} }

This is useful because the compiler verifies that the ‘override’ function has the same signature as the virtual function
Hiding Methods: Similar to the above scenario if the methods are declared in a child and base class with the same signature but without the key words virtual and override, the child class function is said to hide the base class function
class someBaseClass { } class abcClass:someBaseClass {public int fnAge() {return 99;} } class grandchildClass: abcClass{public int fnAge() { return 10;} }

Polymorphism

Polymorphism Overview : -When a derived class inherits from a base class, it gains all the methods, fields, properties and events of the base class. To change the data and behavior of a base class, you have two choices: you can replace the base member with a new derived member, or you can override a virtual base member.
Replacing a member of a base class with a new derived member requires the new keyword. If a base class defines a method, field, or property, the new keyword is used to create a new definition of that method, field, or property on a derived class. The new keyword is placed before the return type of a class member that is being replaced.When the new keyword is used, the new class members are called instead of the base class members that have been replaced. Those base class members are called hidden members. Hidden class members can still be called if an instance of the derived class is cast to an instance of the base class.
or
Generally, the ability to appear in many forms. In object-oriented programming, polymorphism refers to a programming language's ability to process objects differently depending on their data type or class. More specifically, it is the ability to redefine methods for derived classes.
For example, given a base class shape, polymorphism enables the programmer to define different area methods for any number of derived classes, such as circles, rectangles and triangles. No matter what shape an object is, applying the area method to it will return the correct results. Polymorphism is considered to be a requirement of any true object-oriented programming language.
Nizam Sep 01, 2006

polymorpihsm ->one name, many form.
have 2 types : 1. Compile time, 2 Run time
1 compile time: also called overloadinghave 3 types. 1. Constructor overloading(i.e.,with same constructor name and different no of arguments or different datat types or both ) 2 Function overloading(i.e.,with same function name and different no of arguments or different datat types or both)
3. operator overloading: exaample : String s = "James";
s = s + "Bond";
Runtime poly: is achieved by overridding parent class method:
This is called Dynamic method dispatch.



Polymorphism, Method Hiding and Overriding in C#

Overview
One of the fundamental concepts of object oriented software development is polymorphism. The term polymorphism (from the Greek meaning "having multiple forms") in OO is the characteristic of being able to assign a different meaning or usage to something in different contexts - specifically, to allow a variable to refer to more than one type of object.
Example Class Hierarchy
Let's assume the following simple class hierarchy with classes A, B and C for the discussions in this text. A is the super- or base class, B is derived from A and C is derived from class B. In some of the easier examples, we will only refer to a part of this class hierarchy.
Inherited Methods
A method Foo() which is declared in the base class A and not redeclared in classes B or C is inherited in the two subclasses
using System; namespace Polymorphism { class A { public void Foo() { Console.WriteLine("A::Foo()"); } } class B : A {} class Test { static void Main(string[] args) { A a = new A(); a.Foo(); // output --> "A::Foo()" B b = new B(); b.Foo(); // output --> "A::Foo()" } } }
The method Foo() can be overridden in classes B and C:
using System; namespace Polymorphism { class A { public void Foo() { Console.WriteLine("A::Foo()"); } } class B : A { public void Foo() { Console.WriteLine("B::Foo()"); } } class Test { static void Main(string[] args) { A a; B b; a = new A(); b = new B(); a.Foo(); // output --> "A::Foo()" b.Foo(); // output --> "B::Foo()" a = new B(); a.Foo(); // output --> "A::Foo()" } } }
There are two problems with this code.
The output is not really what we, say from Java, expected. The method Foo() is a non-virtual method. C# requires the use of the keyword virtual in order for a method to actually be virtual. An example using virtual methods and polymorphism will be given in the next section.
Although the code compiles and runs, the compiler produces a warning:
...\polymorphism.cs(11,15): warning CS0108: The keyword new is required on 'Polymorphism.B.Foo()' because it hides inherited member 'Polymorphism.A.Foo()'
This issue will be discussed in section Hiding and Overriding Methods.
Virtual and Overridden Methods
Only if a method is declared virtual, derived classes can override this method if they are explicitly declared to override the virtual base class method with the override keyword.
using System; namespace Polymorphism { class A { public virtual void Foo() { Console.WriteLine("A::Foo()"); } } class B : A { public override void Foo() { Console.WriteLine("B::Foo()"); } } class Test { static void Main(string[] args) { A a; B b; a = new A(); b = new B(); a.Foo(); // output --> "A::Foo()" b.Foo(); // output --> "B::Foo()" a = new B(); a.Foo(); // output --> "B::Foo()" } } }
Method Hiding
Why did the compiler in the second listing generate a warning? Because C# not only supports method overriding, but also method hiding. Simply put, if a method is not overriding the derived method, it is hiding it. A hiding method has to be declared using the new keyword. The correct class definition in the second listing is thus:
using System; namespace Polymorphism { class A { public void Foo() { Console.WriteLine("A::Foo()"); } } class B : A { public new void Foo() { Console.WriteLine("B::Foo()"); } } class Test { static void Main(string[] args) { A a; B b; a = new A(); b = new B(); a.Foo(); // output --> "A::Foo()" b.Foo(); // output --> "B::Foo()" a = new B(); a.Foo(); // output --> "A::Foo()" } } }
Combining Method Overriding and Hiding
Methods of a derived class can both be virtual and at the same time hide the derived method. In order to declare such a method, both keywords virtual and new have to be used in the method declaration:
class A { public void Foo() {} } class B : A { public virtual new void Foo() {} }
A class C can now declare a method Foo() that either overrides or hides Foo() from class B:
class C : B { public override void Foo() {} // or public new void Foo() {} }
Conclusion
C# is not Java.
Only methods in base classes need not override or hide derived methods. All methods in derived classes require to be either defined as new or as override.
Know what your doing and look out for compiler warnings.