search/filter the records for the entered value

Below Code will help u to select a GridView Row in Run-Time and also search/filter the record according to the enter value in a textbox..kindly refer the image below..
VB.NET CODE
Private Sub frmDynamicSearch_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
ds = clsDBManager.FillDataSet("Select * from tbUserMst")
If Not ds.Tables(0) Is Nothing AndAlso ds.Tables(0).Rows.Count > 0 Then
DataGridView1.DataSource = ds.Tables(0)
_strDynamicSearchColumn = "UserName"
FindGridTable = ds.Tables(0).Copy
dtSearchResult = ds.Tables(0).Copy
Else
MessageBox.Show("No Records Available", "Santosh Test", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Me.Close()
End Sub
Private Sub HilightCell()
For i As Integer = 0 To DataGridView1.Rows.Count - 2
If DataGridView1.Rows(i).Cells(1).Value.ToString.StartsWith(txtUserName.Text.Trim) Then
'dgvDisplay.Rows(i).DefaultCellStyle.BackColor = Color.Tan
DataGridView1.Rows(i).DefaultCellStyle.BackColor = Color.Cyan
Else
DataGridView1.Rows(i).DefaultCellStyle.BackColor = Color.White
End If
Next
End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
If txtUserName.Text = "" Then
MessageBox.Show("Please Enter a Value to Search", "Santosh Test", MessageBoxButtons.OK, MessageBoxIcon.Information)
Else
HilightCell()
End If
End Sub
C#.NET CODE
private void frmDynamicSearch_Load(object sender, System.EventArgs e)
{
ds = clsDBManager.FillDataSet("Select * from tbUserMst");
if (ds.Tables[0] != null && ds.Tables[0].Rows.Count > 0)
{
DataGridView1.DataSource = ds.Tables[0];
_strDynamicSearchColumn = "UserName";
FindGridTable = ds.Tables[0].Copy();
dtSearchResult = ds.Tables[0].Copy();
}
else
{
MessageBox.Show("No Records Available", "Santosh Test", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}





private void HilightCell()
{
for (int i = 0; i <= DataGridView1.Rows.Count - 2; i++) { if (DataGridView1.Rows[i].Cells[1].Value.ToString().StartsWith(txtUserName.Text.Trim())) { //dgvDisplay.Rows(i).DefaultCellStyle.BackColor = Color.Tan DataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.Cyan; } else { DataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.White; } } } private void Button2_Click(object sender, System.EventArgs e) { if (txtUserName.Text == "") { MessageBox.Show("Please Enter a Value to Search", "Santosh Test", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { HilightCell(); } } OUTPUT:
How Was The Coding
Regards
Santosh

Save Image in DataBase in .NET

This Example will help u to insert image in DataBase
VB CODE
Dim ImagePath As String = "F:\santosh\Image"
Dim ImageInput As String = "Sample.jpg"
Dim ImageOutput As String = "SampleOut.jpg"
Dim dtReturnImage As DataTable
Shared StrConn As String = ""
Private Sub btnSaveImage_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSaveImage.Click
Dim ReturnValue As Integer = 0
Dim Img As FileStream
Dim BinaryReader As BinaryReader
Dim ImgArray() As Byte
Img = New FileStream(ImagePath & "\" & ImageInput, FileMode.Open, FileAccess.Read)
BinaryReader = New BinaryReader(Img)
ImgArray = BinaryReader.ReadBytes(Img.Length)
BinaryReader.Close()
Img.Close()
Dim cls As New clsCommon
ReturnValue = InsertImage(0, ImgArray)
If ReturnValue > 0 Then
Dim dt As New DataTable
dt = cls.ReturnImage(ReturnValue)
For Each dr As DataRow In dt.Rows
ImgArray = CType(dr("ImageFile"), Byte())
Dim oOutput As FileStream = File.Create(ImagePath & "\" & ImageOutput, ImgArray.Length)
oOutput.Write(ImgArray, 0, ImgArray.Length)
oOutput.Close()
Next
End If
End Sub
Private Function InsertImage(ByVal ImageID As Integer, ByVal Image() As Byte) As Integer
Dim InsertSqlCommand As New SqlCommand()
Dim RetunId As Integer = 0
Dim com As New SqlCommand
Dim con As New SqlConnection
con = GetConnectObj()
com.Connection = con
com.CommandType = CommandType.StoredProcedure
com.CommandText = "SaveImage"
Dim objOutputParam As New SqlParameter("@NewID", SqlDbType.Int)
objOutputParam.Direction = ParameterDirection.Output
Dim objImageParam As New SqlParameter("@ImageFile", SqlDbType.Image)
objImageParam.Direction = ParameterDirection.Input
objImageParam.Value = Image
Dim objImageIDParam As New SqlParameter("@ImageID", SqlDbType.Int, 12, ParameterDirection.Input)
objImageIDParam.Value = ImageID
com.Parameters.Add(objImageIDParam)
com.Parameters.Add(objImageParam)
com.Parameters.Add(objOutputParam)
con.Open()
com.ExecuteNonQuery()
RetunId = objOutputParam.Value
Return RetunId
End Function
Public Function ReturnImage(ByVal ImageIdvalue As Integer) As DataTable
dtReturnImage = FillDatatable(" select ImageFile from Images where ImageID = " & ImageIdvalue & "")
Return dtReturnImage
End Function
Private Function ConnectionString() As String
StrConn = "Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=Santosh_Practice;Data Source=SANTOSH\SQLEXPRESS" 'Myconnection is Key in App.Config
Return StrConn
End Function
Private Function GetConnectObj() As SqlConnection
Return New SqlConnection(ConnectionString())
End Function
Private Function FillDatatable(ByVal Query As String) As DataTable
Dim objDT As New DataTable()
Dim objda As New SqlDataAdapter(Query, ConnectionString())
objda.Fill(objDT)
Return objDT
End Function
C# CODE
private string ImagePath = "F:\\santosh\\Image";
private string ImageInput = "Sample.jpg";
private string ImageOutput = "SampleOut.jpg";
private DataTable dtReturnImage;
public static string StrConn = "";
private void btnSaveImage_Click(object sender, System.EventArgs e)
{
int ReturnValue = 0;
FileStream Img = null;
BinaryReader BinaryReader = null;
byte[] ImgArray = null;
Img = new FileStream(ImagePath + "\\" + ImageInput, FileMode.Open, FileAccess.Read);
BinaryReader = new BinaryReader(Img);
ImgArray = BinaryReader.ReadBytes(Img.Length);
BinaryReader.Close();
Img.Close();
clsCommon cls = new clsCommon();
ReturnValue = InsertImage(0, ImgArray);
if (ReturnValue > 0)
{
DataTable dt = new DataTable();
dt = cls.ReturnImage(ReturnValue);
foreach (DataRow dr in dt.Rows)
{
ImgArray = (byte[])(dr["ImageFile"]);
FileStream oOutput = File.Create(ImagePath + "\\" + ImageOutput, ImgArray.Length);
oOutput.Write(ImgArray, 0, ImgArray.Length);
oOutput.Close();
}
}
}
private int InsertImage(int ImageID, byte[] Image)
{
SqlCommand InsertSqlCommand = new SqlCommand();
int RetunId = 0;
SqlCommand com = new SqlCommand();
SqlConnection con = new SqlConnection();
con = GetConnectObj();
com.Connection = con;
com.CommandType = CommandType.StoredProcedure;
com.CommandText = "SaveImage";
SqlParameter objOutputParam = new SqlParameter("@NewID", SqlDbType.Int);
objOutputParam.Direction = ParameterDirection.Output;
SqlParameter objImageParam = new SqlParameter("@ImageFile", SqlDbType.Image);
objImageParam.Direction = ParameterDirection.Input;
objImageParam.Value = Image;
SqlParameter objImageIDParam = new SqlParameter("@ImageID", SqlDbType.Int, 12, ParameterDirection.Input);
objImageIDParam.Value = ImageID;
com.Parameters.Add(objImageIDParam);
com.Parameters.Add(objImageParam);
com.Parameters.Add(objOutputParam);
con.Open();
com.ExecuteNonQuery();
RetunId = objOutputParam.Value;
return RetunId;
}
public DataTable ReturnImage(int ImageIdvalue)
{
dtReturnImage = FillDatatable(" select ImageFile from Images where ImageID = " + ImageIdvalue + "");
return dtReturnImage;
}
private string ConnectionString()
{
StrConn = "Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=Santosh_Practice;Data Source=SANTOSH\\SQLEXPRESS"; //Myconnection is Key in App.Config
return StrConn;
}
private SqlConnection GetConnectObj()
{
return new SqlConnection(ConnectionString());
}
private DataTable FillDatatable(string Query)
{
DataTable objDT = new DataTable();
SqlDataAdapter objda = new SqlDataAdapter(Query, ConnectionString());
objda.Fill(objDT);
return objDT;
}

Any Doubt Plz post a comment or send mail to santosh.mcao8@gmail.com

Take Backup At your own Time

hi i am giving a very nice code to take backup at your own setting time.
1.Drag a Timer Control
2.make it Enabled is true.


VB.NET Code
Imports Microsoft.SqlServer.Server
Imports Microsoft.SqlServer.Management.Smo
Imports System.IO
Public Class TestForm
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Dim BackUpTime As Date = DateTime.Now
If BackUpTime.ToLongTimeString = "8:09:18 PM" Then
TakeBackUp("DMS", "D:\Mail\TestForU.bak") 'DMS is the correct database name exist in server
End If
End Sub
Private Sub TakeBackUp(ByVal BackupDBName As String, ByVal FileNamePath As String)
Try
Dim sqlServerInstance As New Server(New Microsoft.SqlServer.Management.Common.ServerConnection _
(New System.Data.SqlClient.SqlConnection("Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=;Data Source=SANTOSH\SQLEXPRESS"))) 'This is only for connection if u give Initial Catalog null it will work
Dim objBackup As New Backup
objBackup.Devices.AddDevice(FileNamePath, DeviceType.File)
objBackup.Database = BackupDBName
objBackup.Action = BackupActionType.Database
objBackup.SqlBackup(sqlServerInstance)
MessageBox.Show("The backup of database " & "'" & BackupDBName & "'" & " completed sccessfully", "Microsoft SQL Server Management Studio", MessageBoxButtons.OK, MessageBoxIcon.Information)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
End Class

C#.NET Code
using Microsoft.SqlServer.Server;
using Microsoft.SqlServer.Management.Smo;
using System.IO;
public class TestForm
{
//TODO: INSTANT C# TODO TASK: Insert the following converted event handler wireups at the end of the 'InitializeComponent' method for forms, 'Page_Init' for web pages, or into a constructor for other classes:
Timer1.Tick += Timer1_Tick;

private void Timer1_Tick(object sender, System.EventArgs e)
{
System.DateTime BackUpTime = DateTime.Now;
if (BackUpTime.ToLongTimeString() == "8:09:18 PM")
{
TakeBackUp("DMS", "D:\\Mail\\TestForU.bak"); //DMS is the correct database name exist in server
}
}
private void TakeBackUp(string BackupDBName, string FileNamePath)
{
try
{
Server sqlServerInstance = new Server(new Microsoft.SqlServer.Management.Common.ServerConnection (new System.Data.SqlClient.SqlConnection("Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=;Data Source=SANTOSH\\SQLEXPRESS"))); //This is only for connection if u give Initial Catalog null it will work
Backup objBackup = new Backup();
objBackup.Devices.AddDevice(FileNamePath, DeviceType.File);
objBackup.Database = BackupDBName;
objBackup.Action = BackupActionType.Database;
objBackup.SqlBackup(sqlServerInstance);
MessageBox.Show("The backup of database " + "'" + BackupDBName + "'" + " completed sccessfully", "Microsoft SQL Server Management Studio", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}

OUTPUT:-

Regards
Santosh

Calculate the running total in a datagridview

Please follow the below code,this will help to calculate the running total in a datagridview
VB Code
Dim dtRunningTot As New DataTable
Shared StrConn As String = ""
Private Function ConnectionString() As String
StrConn = "Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=Santosh_Practice;Data Source=SANTOSH\SQLEXPRESS" 'Myconnection is Key in App.Config
Return StrConn
End Function
Private Function GetConnectObj() As SqlConnection
Return New SqlConnection(ConnectionString())
End Function
Private Function FillDatatable(ByVal Query As String) As DataTable
Dim objDT As New DataTable()
Dim objda As New SqlDataAdapter(Query, ConnectionString())
objda.Fill(objDT)
Return objDT
End Function
Private Sub frmRunningTotal_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
dtRunningTot = FillDatatable("Select salary from RunningTotal")
DataGridView1.DataSource = dtRunningTot
For i As Integer = 0 To DataGridView1.Rows.Count - 2
For j As Integer = 0 To DataGridView1.Columns.Count - 1
If i = 0 Then
DataGridView1.Rows(i).Cells("RunningTotal").Value = Val(DataGridView1.Rows(i).Cells("Salary").Value)
Else
DataGridView1.Rows(i).Cells("RunningTotal").Value = Val(DataGridView1.Rows(i - 1).Cells("RunningTotal").Value) + Val(DataGridView1.Rows(i).Cells("Salary").Value)
End If
Next
Next
End Sub
C# Code
private DataTable dtRunningTot = new DataTable();
public static string StrConn = "";
//TODO: INSTANT C# TODO TASK: Insert the following converted event handler wireups at the end of the 'InitializeComponent' method for forms, 'Page_Init' for web pages, or into a constructor for other classes:
base.Load += frmRunningTotal_Load;

private string ConnectionString()
{
StrConn = "Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=Santosh_Practice;Data Source=SANTOSH\\SQLEXPRESS"; //Myconnection is Key in App.Config
return StrConn;
}
private SqlConnection GetConnectObj()
{
return new SqlConnection(ConnectionString());
}
private DataTable FillDatatable(string Query)
{
DataTable objDT = new DataTable();
SqlDataAdapter objda = new SqlDataAdapter(Query, ConnectionString());
objda.Fill(objDT);
return objDT;
}
private void frmRunningTotal_Load(object sender, System.EventArgs e)
{
dtRunningTot = FillDatatable("Select salary from RunningTotal");
DataGridView1.DataSource = dtRunningTot;
for (int i = 0; i <= DataGridView1.Rows.Count - 2; i++)
{
for (int j = 0; j < DataGridView1.Columns.Count; j++)
{
if (i == 0)
{
DataGridView1.Rows[i].Cells["RunningTotal"].Value = Microsoft.VisualBasic.Conversion.Val(DataGridView1.Rows[i].Cells["Salary"].Value);
}
else
{
DataGridView1.Rows[i].Cells["RunningTotal"].Value = Microsoft.VisualBasic.Conversion.Val(DataGridView1.Rows[i - 1].Cells["RunningTotal"].Value) + Microsoft.VisualBasic.Conversion.Val(DataGridView1.Rows[i].Cells["Salary"].Value);
}
}
}
}
How was the Coding ??
Any Problem Plz feel free to Contact Santosh.mca08@gmail.com
i will reply u soon

Thanx and Regards
Santosh

Dynamic Search in Windows Application

Please follow the below code,how it is working to search Dynamically.
it will filter all the data corresponding to the textbox entering characters.
1. Drag a Text Box and a DataGridView.
VB Code
[Code]
Public Class frmDynamicSearch
Dim ds As DataSet
Dim _dt As DataTable
Public _strDynamicSearchColumn As String = "UserName"
Dim FindGridTable As DataTable
Dim dtSearchResult As DataTable
Public Property DynamicSearchColumn() As String
Get
Return _strDynamicSearchColumn
End Get
Set(ByVal value As String)
_strDynamicSearchColumn = value
End Set
End Property
Private Function DynamicSearch() As DataTable
Try
If txtUserName.Text.Trim.Equals(String.Empty) Then
Return FindGridTable
End If
dtSearchResult.Rows.Clear()
Dim dr() As DataRow = Nothing
Dim rowSearchResult As DataRow
For Each row As DataRow In FindGridTable.Rows
If Not IsDBNull(row(DynamicSearchColumn)) Then
If row(DynamicSearchColumn).ToString().Trim.ToUpper.StartsWith(txtUserName.Text.Trim.ToUpper) Then
rowSearchResult = dtSearchResult.NewRow()
rowSearchResult.ItemArray = row.ItemArray
dtSearchResult.Rows.Add(rowSearchResult)
End If
End If
Next
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
Return dtSearchResult
End Function

Private Sub txtCode_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtUserName.TextChanged
Dim dt As DataTable = DynamicSearch()
If Not dt Is Nothing And dgvDisplay.RowCount > 0 Then
dgvDisplay.DataSource = dt
Else
MessageBox.Show("No Records Available", "Santosh Test", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
End Sub
Private Sub frmDynamicSearch_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
ds = clsDBManager.FillDataSet("Select * from tbUserMst")
If Not ds.Tables(0) Is Nothing AndAlso ds.Tables(0).Rows.Count > 0 Then
dgvDisplay.DataSource = ds.Tables(0)
_strDynamicSearchColumn = "UserName"
FindGridTable = ds.Tables(0).Copy
dtSearchResult = ds.Tables(0).Copy
Else
MessageBox.Show("No Records Available", "Santosh Test", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
End Sub
End Class
[/Code]

C# Code
[Code]
public class frmDynamicSearch
{
private DataSet ds;
private DataTable _dt;
public string _strDynamicSearchColumn = "UserName";
private DataTable FindGridTable;
private DataTable dtSearchResult;
//TODO: INSTANT C# TODO TASK: Insert the following converted event handler wireups at the end of the 'InitializeComponent' method for forms, 'Page_Init' for web pages, or into a constructor for other classes:
txtUserName.TextChanged += txtCode_TextChanged;
base.Load += frmDynamicSearch_Load;

public string DynamicSearchColumn
{
get
{
return _strDynamicSearchColumn;
}
set
{
_strDynamicSearchColumn = value;
}
}
private DataTable DynamicSearch()
{
try
{
if (txtUserName.Text.Trim().Equals(string.Empty))
{
return FindGridTable;
}
dtSearchResult.Rows.Clear();
DataRow[] dr = null;
DataRow rowSearchResult = null;
foreach (DataRow row in FindGridTable.Rows)
{
if (! (System.Convert.IsDBNull(row[DynamicSearchColumn])))
{
if (row[DynamicSearchColumn].ToString().Trim().ToUpper().StartsWith(txtUserName.Text.Trim().ToUpper()))
{
rowSearchResult = dtSearchResult.NewRow();
rowSearchResult.ItemArray = row.ItemArray;
dtSearchResult.Rows.Add(rowSearchResult);
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return dtSearchResult;
}

private void txtCode_TextChanged(object sender, System.EventArgs e)
{
DataTable dt = DynamicSearch();
if (dt != null & dgvDisplay.RowCount > 0)
{
dgvDisplay.DataSource = dt;
}
else
{
MessageBox.Show("No Records Available", "Santosh Test", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
private void frmDynamicSearch_Load(object sender, System.EventArgs e)
{
ds = clsDBManager.FillDataSet("Select * from tbUserMst");
if (ds.Tables[0] != null && ds.Tables[0].Rows.Count > 0)
{
dgvDisplay.DataSource = ds.Tables[0];
_strDynamicSearchColumn = "UserName";
FindGridTable = ds.Tables[0].Copy();
dtSearchResult = ds.Tables[0].Copy();
}
else
{
MessageBox.Show("No Records Available", "Santosh Test", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
[/Code]

OutPut:
How was the Coding ???
Plz post a comment

Thanx and Regards
Santosh
http://santoshdotnetarena.blogspot.com/

Find Driver Details in VB.NET

Below Code will Help to Find Driver Details of a System

Imports System.IO
Imports System
Imports System.Math
Public Class frmFindDriverName
Private Sub frmFindDriverName_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
For Each objdriveinfo As DriveInfo In DriveInfo.GetDrives()
If objdriveinfo.Name = "A:\" Or objdriveinfo.Name = "G:\" Then
Else
ListBox1.Items.Add(objdriveinfo.Name & " " & Round((objdriveinfo.TotalFreeSpace / 1073741824), 2) & "GB" & " " & Round((objdriveinfo.TotalSize / 1073741824), 2) & "GB" & " " & objdriveinfo.DriveFormat & " " & objdriveinfo.VolumeLabel & "")
End If
'Label1.Text = Round(objdriveinfo.TotalFreeSpace, 2)
Next
End Sub
End Class

Output:

AUTO INCREMENT PRIMERY KEY IN RUN TIME

BELOW SP WILL HELP YOU TO AUTO INCREMENT PRIMERY KEY IN RUN TIME

ALTER PROCEDURE AUTO_INCREMENT
@NAME VARCHAR(12) = NULL
AS
BEGIN
DECLARE @ID INT
SELECT @ID = MAX(ID) FROM TEST --(TABLENAME)
IF @ID IS NULL
INSERT INTO TEST VALUES(1,@NAME)
ELSE
INSERT INTO TEST VALUES(@ID +1 ,@NAME)
END

Format Decimal Values In Window Application

if you want to format the value(32.00)
but u r entering the value 23,then u just
follow the below code

call code in KeyLeave

VB.NET

Shared Sub FormatDecimal(ByVal ctxt As System.Windows.Forms.TextBox, ByVal ad As Int16)
If ctxt.Text.Trim <> "" Then
If ctxt.Text.Trim = "-" Then
MessageBox.Show("Enter Valid Inputs ", "Notification", MessageBoxButtons.OK, MessageBoxIcon.Information)
ctxt.SelectAll()
ctxt.Focus()
Else
If ctxt.Text.Trim = "-." Or ctxt.Text.Trim = "." Then
ctxt.Text = "0"
End If
ctxt.Text = FormatNumber(ctxt.Text.Trim, ad).Replace(",", "")
End If
End If
End Sub

C#.NET

public static void FormatDecimal(System.Windows.Forms.TextBox ctxt, Int16 ad)
{
if (ctxt.Text.Trim() != "")
{
if (ctxt.Text.Trim() == "-")
{
MessageBox.Show("Enter Valid Inputs ", "Notification", MessageBoxButtons.OK,

MessageBoxIcon.Information);
ctxt.SelectAll();
ctxt.Focus();
}
else
{
if (ctxt.Text.Trim() == "-." || ctxt.Text.Trim() == ".")
{
ctxt.Text = "0";
}
ctxt.Text = Microsoft.VisualBasic.Strings.FormatNumber(ctxt.Text.Trim(), ad,

Microsoft.VisualBasic.TriState.UseDefault, Microsoft.VisualBasic.TriState.UseDefault,

Microsoft.VisualBasic.TriState.UseDefault).Replace(",", "");
}
}
}

Happy Coding
Santosh

To Validate Textbox Decimal Values

for web application validation controls are there to validate control
but in windows application it is little bit difficult
i am giving the below code to validate dacimal values of a textbox

Ex:Let you need to enter a textbox decimal values like(123.34) instead of no rtestriction
no need to set any properties of textbox.

just in KeyPress u call this below method and Pass before and after decimal values.
if u want to enter like(2124.98) so need to pass bd value =4 and ad value = 2



VB.NET
Shared Sub ChkDecimal(ByVal Ctxt As System.Windows.Forms.TextBox, ByVal x As System.Windows.Forms.KeyPressEventArgs, ByVal bd As Int16, ByVal ad As Int16)
Ctxt.Text = Ctxt.Text.Trim
If (Char.IsControl(x.KeyChar) Or Char.IsDigit(x.KeyChar) = True) Or Asc(x.KeyChar) = 46 Or Asc(x.KeyChar) = 45 Or

Asc(x.KeyChar) = 8 Then
If ((Ctxt.Text.IndexOf(".") <> -1 And x.KeyChar = ".") Or (Ctxt.Text.IndexOf("-") = 0 And x.KeyChar = "-") Or

(Ctxt.Text.IndexOf("-") = 0 And Ctxt.SelectionStart = 0 And Asc(x.KeyChar) <> 8)) And Ctxt.SelectionLength = 0 Then
x.Handled = True
ElseIf (Ctxt.Text <> "" And x.KeyChar = "-" And Ctxt.SelectionStart <> 0) Then
x.Handled = True
Else
If Ctxt.Text.IndexOf(".") <> -1 Then
If Ctxt.SelectionStart >= 0 And Asc(x.KeyChar) <> 8 Then
If ((((Mid(Ctxt.Text, Ctxt.Text.IndexOf(".") + 1).Length > ad + 1 And Ctxt.SelectionStart >

Ctxt.Text.IndexOf(".")) Or (Mid(Ctxt.Text, 1, Ctxt.Text.IndexOf(".") + 1).Length > bd And Ctxt.SelectionStart <> "-") And Ctxt.SelectionLength = 0) Or _
((((Mid(Ctxt.Text, Ctxt.Text.IndexOf(".") + 1).Length > ad And Ctxt.SelectionStart >

Ctxt.Text.IndexOf(".")) Or (Mid(Ctxt.Text, 2, Ctxt.Text.IndexOf(".")).Length > bd And Ctxt.SelectionStart <> -1)) And Ctxt.SelectionLength = 0) Then
x.Handled = True
End If
End If
Else
If (Ctxt.Text.IndexOf("-") <> -1 And Ctxt.SelectionLength = 0 And ((Mid(Ctxt.Text, 2).Length > bd - 1 And

x.KeyChar <> "." And Asc(x.KeyChar) <> 8) Or (Ctxt.SelectionStart > bd + 1 And x.KeyChar.ToString.Equals(".")))) Or _
(Ctxt.Text.IndexOf("-") = -1 And Ctxt.SelectionLength = 0 And (((Mid(Ctxt.Text, 1).Length > bd - 1

And x.KeyChar <> "." And Asc(x.KeyChar) <> 8) And Asc(x.KeyChar) <> 45) Or (Ctxt.SelectionStart > bd And

x.KeyChar.ToString.Equals(".")))) Then
x.Handled = True
End If
End If
End If
Else
x.Handled = True
End If
End Sub

C#.NET
public static void ChkDecimal(System.Windows.Forms.TextBox Ctxt, System.Windows.Forms.KeyPressEventArgs x, Int16 bd, Int16

ad)
{
Ctxt.Text = Ctxt.Text.Trim();
if ((char.IsControl(x.KeyChar) || char.IsDigit(x.KeyChar) == true) || System.Convert.ToInt32(x.KeyChar[0]) ==

46 || System.Convert.ToInt32(x.KeyChar[0]) == 45 || System.Convert.ToInt32(x.KeyChar[0]) == 8)
{
if (((Ctxt.Text.IndexOf(".") != -1 && x.KeyChar == ".") | (Ctxt.Text.IndexOf("-") == 0 && x.KeyChar

== "-") | (Ctxt.Text.IndexOf("-") == 0 && Ctxt.SelectionStart == 0 && System.Convert.ToInt32(x.KeyChar[0]) != 8)) &&

Ctxt.SelectionLength == 0)
{
x.Handled = true;
}
else if (Ctxt.Text != "" && x.KeyChar == "-" && Ctxt.SelectionStart != 0)
{
x.Handled = true;
}
else
{
if (Ctxt.Text.IndexOf(".") != -1)
{
if (Ctxt.SelectionStart >= 0 && System.Convert.ToInt32(x.KeyChar[0]) != 8)
{
if (((((Ctxt.Text.Substring(Ctxt.Text.IndexOf(".")).Length > ad + 1 &

Ctxt.SelectionStart > Ctxt.Text.IndexOf(".")) | (Ctxt.Text.Substring(0, Ctxt.Text.IndexOf(".") + 1).Length > bd &

Ctxt.SelectionStart < selectionlength ="="> ad & Ctxt.SelectionStart >

Ctxt.Text.IndexOf(".")) | (Ctxt.Text.Substring(1, Ctxt.Text.IndexOf(".")).Length > bd & Ctxt.SelectionStart < selectionlength ="=" handled =" true;" selectionlength ="="> bd - 1 & x.KeyChar != "." & System.Convert.ToInt32(x.KeyChar[0]) != 8) |

(Ctxt.SelectionStart > bd + 1 & x.KeyChar.ToString().Equals(".")))) | (Ctxt.Text.IndexOf("-") == -1 && Ctxt.SelectionLength

== 0 && (((Ctxt.Text.Substring(0).Length > bd - 1 & x.KeyChar != "." & System.Convert.ToInt32(x.KeyChar[0]) != 8) &

System.Convert.ToInt32(x.KeyChar[0]) != 45) | (Ctxt.SelectionStart > bd & x.KeyChar.ToString().Equals(".")))))
{
x.Handled = true;
}
}
}
}
else
{
x.Handled = true;
}
}


How Was the Coding??
Santosh,Bangalore

Validating Opened Form Under MDI Form

i am giving the code ,how to validate form Opened or Not??

Let under my MDI Parent 6 forms are there,if i opened a form called(frmTest1) and if again i am trying to open same before closing that form then instead of open again it will show the opened form from task Bar.
if some of forms are opened in taskBar,then u r trying to close the MDI Parent then it will show a message like "Some Forms are Already Opened"
To Validate above things,below VB.NET code will very helpful to you.

Code:

Public Class MDIForm
Dim objfrmCurMst As frmCurrencyMst
Dim frmCountMst As New frmCountrymst
Dim frmPortMst As New frmPortMst
Dim frmRegMst As New frmRegionMst
Dim frmStaMst As New frmStaffMst
Public objArrayList As New ArrayList()
Private Sub ShowNewForm(ByVal sender As Object, ByVal e As EventArgs) Handles
NewToolStripMenuItem.Click
Try
If frmCountMst Is Nothing Then
frmCountMst = New frmCountrymst
objArrayList.Add(frmCountMst)
frmCountMst.Show()
Else
If frmCountMst.IsDisposed Then
frmCountMst = New frmCountrymst
End If
objArrayList.Add(frmCountMst)
frmCountMst.Show()
frmCountMst.Activate()
End If
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.OkOnly)

End Try
End Sub

Private Sub OpenFile(ByVal sender As Object, ByVal e As EventArgs) Handles
OpenToolStripMenuItem.Click
Try
If objfrmCurMst Is Nothing Then
objfrmCurMst = New frmCurrencyMst
objArrayList.Add(objfrmCurMst)
objfrmCurMst.Show()
Else
If objfrmCurMst.IsDisposed Then
objfrmCurMst = New frmCurrencyMst
End If
objArrayList.Add(objfrmCurMst)
objfrmCurMst.Show()
objfrmCurMst.Activate()
End If
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.OkOnly)

End Try
End Sub

Private Sub SaveAsToolStripMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim SaveFileDialog As New SaveFileDialog
SaveFileDialog.InitialDirectory = My.Computer.FileSystem.SpecialDirectories.MyDocuments
SaveFileDialog.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*"

If (SaveFileDialog.ShowDialog(Me) = System.Windows.Forms.DialogResult.OK) Then
Dim FileName As String = SaveFileDialog.FileName
' TODO: Add code here to save the current contents of the form to a file.
End If
End Sub


Private Sub ExitToolsStripMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs)
Handles ExitToolStripMenuItem.Click
For Each obj As Object In objArrayList
If Not obj Is Nothing Then
If CType(obj, Form).IsDisposed = False And CType(obj, Form).Visible = True Then
MsgBox("Some screens are Opened,Please Save and close",
MsgBoxStyle.Information)
Exit Sub
End If
End If
Next
Me.Close()
End Sub

Private Sub CutToolStripMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs)
' Use My.Computer.Clipboard to insert the selected text or images into the clipboard
End Sub

Private Sub CopyToolStripMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs)
' Use My.Computer.Clipboard to insert the selected text or images into the clipboard
End Sub

Private Sub PasteToolStripMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs)
'Use My.Computer.Clipboard.GetText() or My.Computer.Clipboard.GetData to retrieve
information from the clipboard.
End Sub




Private Sub CascadeToolStripMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs)
Me.LayoutMdi(MdiLayout.Cascade)
End Sub

Private Sub TileVerticleToolStripMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs)
Me.LayoutMdi(MdiLayout.TileVertical)
End Sub

Private Sub TileHorizontalToolStripMenuItem_Click(ByVal sender As Object, ByVal e As
EventArgs)
Me.LayoutMdi(MdiLayout.TileHorizontal)
End Sub

Private Sub ArrangeIconsToolStripMenuItem_Click(ByVal sender As Object, ByVal e As
EventArgs)
Me.LayoutMdi(MdiLayout.ArrangeIcons)
End Sub

Private Sub CloseAllToolStripMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs)
' Close all child forms of the parent.
For Each ChildForm As Form In Me.MdiChildren
ChildForm.Close()
Next
End Sub

Private m_ChildFormNumber As Integer = 0

Private Sub ToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles ToolStripMenuItem1.Click
Try
If frmPortMst Is Nothing Then
frmPortMst = New frmPortMst
objArrayList.Add(frmPortMst)
frmPortMst.Show()
Else
If frmPortMst.IsDisposed Then
frmPortMst = New frmPortMst
End If
objArrayList.Add(frmPortMst)
frmPortMst.Show()
frmPortMst.Activate()
End If
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.OkOnly)

End Try
End Sub

Private Sub SaveToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles SaveToolStripMenuItem.Click
Try
If frmRegMst Is Nothing Then
frmRegMst = New frmRegionMst
objArrayList.Add(frmRegMst)
frmRegMst.Show()
Else
If frmRegMst.IsDisposed Then
frmRegMst = New frmRegionMst
End If
objArrayList.Add(frmRegMst)
frmRegMst.Show()
frmRegMst.Activate()
End If
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.OkOnly)

End Try
End Sub

Private Sub ToolStripMenuItem2_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles ToolStripMenuItem2.Click
Try
If frmStaMst Is Nothing Then
frmStaMst = New frmStaffMst
objArrayList.Add(frmStaMst)
frmStaMst.Show()
Else
If frmStaMst.IsDisposed Then
frmStaMst = New frmStaffMst
End If
objArrayList.Add(frmStaMst)
frmStaMst.Show()
frmStaMst.Activate()
End If
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.OkOnly)

End Try
End Sub


NiCE Coding

Ragards
Santosh

Find All Color's From your System

1. Drag a List Box (called lstFontStyle) then write the below Code in page load

string[] colorArray = Enum.GetNames(typeof(KnownColor));
lstFontColor .DataSource = colorArray;
lstFontColor.DataBind();




Santosh
Bangalore

Find Installed Font From your System in C#.NET

1. Drag a List Box (called lstFontStyle) then write the below Code in page load

InstalledFontCollection fontList = new InstalledFontCollection();
foreach (FontFamily Family in fontList.Families)
{
lstFontStyle.Items.Add(Family.Name);
}

Santosh
Bangalore

Find all BorerStye in C#.NET

1. Drag a List Box (called LstBorderStyle) then write the below Code in page load

string[] borderStyle = Enum.GetNames(typeof(BorderStyle));
LstBorderStyle.DataSource = borderStyle;
LstBorderStyle.DataBind();






Santosh
Bangalore

Date Format in SQL SERVER 2005

i am giving one example u try with other ID
Ex:
SELECT CONVERT(VARCHAR,GETDATE(),100) AS TODAY
u try with other just changing the ID.

ID FORMAT

0 OR 100 mon dd yyyy hh:miAM (or PM)
101 mm/dd/yy
102 yyyy.mm.dd
103 dd/mm/yyyy
104 dd.mm.yyyy
105 dd-mm-yyyy
106 dd mon yyyy
107 Mon dd, yy
108 hh:mm:ss
9 OR 109 mon dd yyyy hh:mi:ss:mmmAM (or PM)
110 mm-dd-yy
111 yyyy/mm/dd
112 yyyymmdd
13 OR 113 dd mon yyyy hh:mm:ss:mmm(24h)
114 hh:mi:ss:mmm(24h)
20 or 120 yyyy-mm-dd hh:mi:ss(24h)
21 or 121 yyyy-mm-dd hh:mi:ss.mmm(24h)
126 yyyy-mm-dd Thh:mm:ss.mmm(no spaces)
127 yyyy-mm-dd Thh:mm:ss.mmm(no spaces)
130 dd mon yyyy hh:mi:ss:mmmAM


any Doubt plz post comment i will reply soon.

santosh,bangalore

Filter Data in Windows Application

Like Web Application it you type a character then all the values will show down of the text box of that perticular character.
here i am giving very good example to filter records in windows application.

Code:
first import these two packages.
Imports System.Data
Imports System.Data.SqlClient

page load you call the below method


Private Sub Intellisense()
Dim con As New SqlConnection("Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=MyPractice;Data Source=IT\SQLEXPRESS")
con.Open()
Dim dsUser As New DataSet
Dim daUser As New SqlDataAdapter
Dim com As New SqlCommand
com.Connection = con
com.CommandText = "SELECT * FROM tbUSERMST"
daUser.SelectCommand = com
daUser.Fill(dsUser)
Dim datacollection As New AutoCompleteStringCollection
For i As Integer = 0 To dsUser.Tables(0).Rows.Count - 1
datacollection.Add(dsUser.Tables(0).Rows(i).Item(1).ToString)
Next
txtUserName.AutoCompleteSource = AutoCompleteSource.CustomSource
txtUserName.AutoCompleteMode = AutoCompleteMode.Suggest
txtUserName.AutoCompleteCustomSource = datacollection

End Sub

Output:Output 2:


Any Doubt Plz post comment i will reply u soon. Santosh,bangalore

Very Simple Code to Read a txt File in C#.net

StreamReader sr;
try
{
sr = File.OpenText("E:\\Avi.txt");
TextBox1.Text = sr.ReadToEnd();
sr.Close();
}
catch
{
TextBox1.Text = "Unable To Read File";
}

File Upload in C#.net

string FileName;
FileName = FileUpload1.FileName;
string ExtName;
ExtName = Path.GetExtension(FileName);
if (ExtName != ".jpg")
{
Response.Write("You choose the file dishonestly !!!");
return;
}
if (FileUpload1.PostedFile.ContentLength > 131072)
{
Response.Write("The size of big too file , the size of the file must 128 KB not exceed!!! ");
return;
}

string CurrentPath = Server.MapPath("~/UploadedPath/");

if (FileUpload1.HasFile)
{
CurrentPath += FileName ;
System.IO.FileInfo file = null;
file = new System.IO.FileInfo(FileName);
if (file.Exists)
{
Response.Write("File Already Exist!!!");
return;
}
FileUpload1.SaveAs(CurrentPath);

Response.Write("File Uploaded Sucessfully !!!");
}
else
{
Response.Write("Can not load the file !");
}

Coding Standard in .net

Prefix Control
lbl Label
llbl LinkLabel
but Button
txt Textbox
mnu MainMenu
chk CheckBox
rdo RadioButton
grp GroupBox
pic PictureBox
grd Grid
lst ListBox
cbo ComboBox
lstv ListView
tre TreeView
tab TabControl
dtm DateTimePicker
mon MonthCalendar
sbr ScrollBar
tmr Timer
spl Splitter
dud DomainUpDown
nud NumericUpDown
trk TrackBar
pro ProgressBar
rtxt RichTextBox
img ImageList
hlp HelpProvider
tip ToolTip
cmnu ContextMenu
tbr ToolBar
frm Form
bar StatusBar
nico NotifyIcon
ofd OpenFileDialog
sfd SaveFileDialog
fd FontDialog
cd ColorDialog
pd PrintDialog
Ppd PrintPreviewDialog
Ppc PrintPreviewControl
err ErrorProvider
pdoc PrintDocument
Psd PageSetupDialog
crv CrystalReportViewer
pd PrintDialog
Fsw FileSystemWatcher
fd FontDialog
cd ColorDialog
pd PrintDialog
Ppd PrintPreviewDialog
Ppc PrintPreviewControl
err ErrorProvider
pdoc PrintDocument
Psd PageSetupDialog
crv CrystalReportViewer
pd PrintDialog
Fsw FileSystemWatcher
log EventLog
Dire DirectoryEntry
Dirs DirectorySearcher
Msq MessageQueue
Pco PerformanceCounter
pro Process
ser ServiceController
rpt ReportDocument
ds DataSet
Olea OleDbDataAdapter
Olec OleDbConnection
Oled OleDbCommand
Sqla SqlDbDataAdapter
Sqlc SqlDbConnection
Sqld SqlDbCommand
Dvw DataView