Tuesday, 7 August 2012

custom control textbox with validation c# and vb.net


Custom control textbox with validation in C#


first that why we create a custom text box control in .net application development. is any reason or not. so first reason is you can automatically validate all control. and it's easy to use. simple example for if you want to input only integer or decimal from text box you have to write event for it on text box. suppose you have to more than one text box than you have to write for all control. where you use. so that time if you create a custom control than it's help you in fast development.

here in code i give you how to input only integer or decimal from textbox in vb.net and c#.
here code in c# and vb.net.

1> go to add new item in visual studio's current project.
2> select custome control and give name CustomeTextBox. which example given in following image.



3> Goes to source code of and change inheritance from control to TextBox or System.Windows.Forms.TextBox









4> Add following code in class. for c#. For vb.net copy it from here and convert from web. it's also working for vb.net also.

private InputType _InputSelection;
        public InputType InputTextType
        {
            set { _InputSelection = value; }
            get { return _InputSelection; }
        }
        public enum InputType
        {
            [Description("Input General String")]
            Text,
            [Description("Input Only Integer Number")]
            Integer,
            [Description("Input Only Decimal Number")]
            Decimal
        }
        string FTextC;
        public  CustomeTextBox()
        {
            InitializeComponent();
            this.TextChanged += new EventHandler(ORTextBox_TextChanged);
            this.KeyDown += new KeyEventHandler(ORTextBox_KeyDown);
            FTextC = this.Text;
        }
        protected override void OnPaint(PaintEventArgs pe)
        {
            base.OnPaint(pe);
        }
        private void ORTextBox_TextChanged(object sender, EventArgs e)
        {
            if (_InputSelection == InputType.Text)
            {

            }
            else if (_InputSelection == InputType.Integer)
            {
                if (string.IsNullOrEmpty(((TextBox)sender).Text))
                {
                    FTextC = "";
                }
                else
                {
                    Int64 num = 0;
                    bool success = Int64.TryParse(((TextBox)sender).Text, out num);
                    if (success & num >= 0)
                    {
                        ((TextBox)sender).Text.Trim();
                        FTextC = ((TextBox)sender).Text;
                    }
                    else
                    {
                        ((TextBox)sender).Text = FTextC;
                        ((TextBox)sender).SelectionStart = ((TextBox)sender).Text.Length;
                    }
                }
            }
            else if (_InputSelection == InputType.Decimal)
            {
                if (string.IsNullOrEmpty(((TextBox)sender).Text))
                {
                    FTextC = "";
                }
                else
                {
                    double num = 0;
                    bool success = double.TryParse(((TextBox)sender).Text, out num);
                    if (success & num >= 0)
                    {
                        ((TextBox)sender).Text.Trim();
                        FTextC = ((TextBox)sender).Text;
                    }
                    else
                    {
                        ((TextBox)sender).Text = FTextC;
                        ((TextBox)sender).SelectionStart = ((TextBox)sender).Text.Length;
                    }
                }
            }
        }
        private void ORTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                SendKeys.Send("{TAB}");
                e.SuppressKeyPress = true;
            }
        }


here also code for move's next control. when you press enter than it's send TAB key so it's moves to next control.

and it's completed. debug your application.

you get your control in Toolbox panel. just drag on form and enjoy with it.

for change input type you have to just change the property which is InputType

have you any query about it than comment.
than you.

Monday, 2 July 2012

Class for mainage mssql database in vb.net

Imports System.Data.SqlClient

Public Class _MsSqlLib

'Developed By Nilesh Makavana.

Sub New()

_ConectionString = ""

End Sub

Private _ConectionString As String

#Region "Connection Function"

Public Function TestConnection() As Boolean

Try

Using Cn As New SqlConnection(_ConectionString)

Cn.Open()

Cn.Close()

End Using

Return True

Catch ex As Exception

Return False

End Try

End Function

Public Function ManageConnection() As Boolean

Try

Dim Cn As New SqlConnection(_ConectionString)

If Cn.State = ConnectionState.Open Then

Cn.Close()

ElseIf Cn.State = ConnectionState.Closed Then

Cn.Open()

End If

Return True

Catch ex As Exception

Return False

End Try

End Function

#End Region

#Region "Execute Non Query"

Public Function ExecuteNonQuery(ByVal SqlQuery As String) As Boolean

Try

Using Cn As New SqlConnection(_ConectionString)

Cn.Open()

Using cmd As New SqlCommand

With cmd

.CommandType = CommandType.Text

.CommandTimeout = 30

.CommandText = SqlQuery

.Connection = Cn

End With

cmd.ExecuteNonQuery()

End Using

End Using

Return True

Catch ex As Exception

Return False

End Try

End Function

#End Region

#Region "Set Data Table"

Public Function SetDataTable(ByVal _Datatable As DataTable, ByVal SqlQuery As String) As Boolean

Dim DataReader As IDataReader

Try

Using Cn As New SqlConnection(_ConectionString)

Cn.Open()

Using cmd As New SqlCommand

With cmd

.CommandType = CommandType.Text

.CommandTimeout = 30

.CommandText = SqlQuery

.Connection = Cn

End With

DataReader = cmd.ExecuteReader()

_Datatable.Load(DataReader)

DataReader.Close()

End Using

End Using

Return True

Catch ex As Exception

MsgBox(ex.ToString)

Return False

End Try

End Function

#End Region

#Region "Fetch One Field In array of list"

Public Function FetchSingleColunm(ByVal TableName As String, ByVal ColumnName As String, Optional ByVal Conditon As String = "") As List(Of String)

Dim ArrayOfFiled As New List(Of String)

Try

Using Cn As New SqlConnection(_ConectionString)

Cn.Open()

Dim DataReader As IDataReader

Using cmd As New SqlCommand

With cmd

.CommandType = CommandType.Text

.CommandTimeout = 30

If Conditon = String.Empty Then

.CommandText = "select " & ColumnName & " FROM [" & TableName & "]"

Else

.CommandText = "select " & ColumnName & " FROM [" & TableName & "] where " & Conditon & ""

End If

.Connection = Cn

End With

DataReader = cmd.ExecuteReader()

While DataReader.Read

ArrayOfFiled.Add(DataReader.Item(0).ToString)

End While

DataReader.Close()

DataReader.Dispose()

End Using

End Using

Catch ex As Exception

MsgBox(ex.ToString)

'MsgBox("Error in table name or colunma name or condition or arraylist")

End Try

Return ArrayOfFiled

End Function

Public Function FetchSingleColunmStr(ByVal TableName As String, ByVal ColumnName As String, Optional ByVal Conditon As String = "") As String

Dim ArrayOfFiled As String = String.Empty

Try

Using Cn As New SqlConnection(_ConectionString)

Cn.Open()

Dim DataReader As IDataReader

Using cmd As New SqlCommand

With cmd

.CommandType = CommandType.Text

.CommandTimeout = 30

If Conditon = String.Empty Then

.CommandText = "select " & ColumnName & " FROM [" & TableName & "]"

Else

.CommandText = "select " & ColumnName & " FROM [" & TableName & "] where " & Conditon & ""

End If

.Connection = Cn

End With

DataReader = cmd.ExecuteReader()

While DataReader.Read

ArrayOfFiled = (DataReader.Item(0).ToString)

End While

DataReader.Close()

DataReader.Dispose()

End Using

End Using

Catch ex As Exception

MsgBox(ex.ToString)

'MsgBox("Error in table name or colunma name or condition or arraylist")

End Try

Return ArrayOfFiled

End Function

Public Function FetchSingleColunmStr(ByVal Query As String) As String

Dim ArrayOfFiled As String = String.Empty

Try

Using Cn As New SqlConnection(_ConectionString)

Cn.Open()

Dim DataReader As IDataReader

Using cmd As New SqlCommand

With cmd

.CommandType = CommandType.Text

.CommandTimeout = 30

.CommandText = Query

.Connection = Cn

End With

DataReader = cmd.ExecuteReader()

While DataReader.Read

ArrayOfFiled = (DataReader.Item(0).ToString)

End While

DataReader.Close()

DataReader.Dispose()

End Using

End Using

Catch ex As Exception

MsgBox(ex.ToString)

'MsgBox("Error in table name or colunma name or condition or arraylist")

End Try

Return ArrayOfFiled

End Function

Public Function FetchSingleColunm(ByVal Query As String) As List(Of String)

Dim ArrayOfFiled As New List(Of String)

Try

Using Cn As New SqlConnection(_ConectionString)

Cn.Open()

Dim DataReader As IDataReader

Using cmd As New SqlCommand

With cmd

.CommandType = CommandType.Text

.CommandTimeout = 30

.CommandText = Query

.Connection = Cn

End With

DataReader = cmd.ExecuteReader()

Dim RowId As Integer = 0

While DataReader.Read

ArrayOfFiled.Add(DataReader.Item(0).ToString)

End While

DataReader.Close()

DataReader.Dispose()

End Using

Cn.Close()

End Using

Catch ex As Exception

MsgBox(ex.ToString)

'MsgBox("Error in table name or colunma name or condition or arraylist")

End Try

Return ArrayOfFiled

End Function

#End Region

#Region "Basic Tabal Function, MAX MIN Totoal Record"

Public Function TableCount(ByVal TableName As String, Optional ByVal condition As String = "NULL") As Integer

Dim FetchValue As String = "NULL"

Try

Using SqlConnectionObject As New SqlConnection(_ConectionString)

SqlConnectionObject.Open()

Dim SqlQuery As String = String.Empty

If condition = "NULL" Then

SqlQuery = "SELECT COUNT(*) FROM " & TableName & ""

Else

SqlQuery = "SELECT COUNT(*) FROM " & TableName & " WHERE " & condition & ""

End If

Using SqlCommand As New SqlCommand

With SqlCommand

.Connection = SqlConnectionObject

.CommandType =
CommandType.Text

.CommandText = SqlQuery

End With

Using Dtreader As SqlDataReader = SqlCommand.ExecuteReader

While Dtreader.Read

FetchValue = Dtreader.Item(0).ToString

End While

End Using

End Using

End Using

Catch exError As Exception

MsgBox(exError.ToString)

End Try

Return Integer.Parse(FetchValue)

End Function

Public Function TableMax(ByVal TableName As String, ByVal fieldname As String, Optional ByVal condition As String = "NULL") As Integer

If TableCount(TableName) = 0 Then

Return 0

Else

Dim FetchValue As String = "0"

Try

Using SqlConnectionObject As New SqlConnection(_ConectionString)

SqlConnectionObject.Open()

Dim SqlQuery As String = String.Empty

If condition = "NULL" Then

SqlQuery = "SELECT MAX(" & fieldname & " ) FROM " & TableName & ""

Else

SqlQuery = "SELECT MAX(" & fieldname & " ) FROM " & TableName & " WHERE " & condition & ""

End If

Using SqlCommand As New SqlCommand

With SqlCommand

.Connection = SqlConnectionObject

.CommandType =
CommandType.Text

.CommandText = SqlQuery

End With

Using Dtreader As SqlDataReader = SqlCommand.ExecuteReader

While Dtreader.Read

FetchValue = Dtreader.Item(0).ToString

End While

End Using

End Using

End Using

Catch exError As Exception

MsgBox(exError.ToString)

End Try

If FetchValue = "NULL" Or FetchValue = String.Empty Then

Return 0

Else

Return Integer.Parse(FetchValue)

End If

End If

End Function

Public Function TableMin(ByVal TableName As String, ByVal fieldname As String, Optional ByVal condition As String = "NULL") As Integer

Dim FetchValue As String = "NULL"

Try

Using SqlConnectionObject As New SqlConnection(_ConectionString)

SqlConnectionObject.Open()

Dim SqlQuery As String = String.Empty

If condition = "NULL" Then

SqlQuery = "SELECT MIN(" & fieldname & " ) FROM " & TableName & ""

Else

SqlQuery = "SELECT MIN(" & fieldname & " ) FROM " & TableName & " WHERE " & condition & ""

End If

Using SqlCommand As New SqlCommand

With SqlCommand

.Connection = SqlConnectionObject

.CommandType =
CommandType.Text

.CommandText = SqlQuery

End With

Using Dtreader As SqlDataReader = SqlCommand.ExecuteReader

While Dtreader.Read

FetchValue = Dtreader.Item(0).ToString

End While

End Using

End Using

End Using

Catch exError As Exception

MsgBox(exError.ToString)

Finally

End Try

If FetchValue = "NULL" Or FetchValue = String.Empty Then

Return 0

Else

Return Integer.Parse(FetchValue)

End If

End Function

#End Region

End Class