Showing posts with label Windows Applcation. Show all posts
Showing posts with label Windows Applcation. Show all posts

Code to get some important folder path and OS Version

Below code will help to get the important folder path and OS Version
VB.NET Code
Dim PersonalDir As String = Environment.GetFolderPath(Environment.SpecialFolder.Personal)
Dim CookiesDir As String = Environment.GetFolderPath(Environment.SpecialFolder.Cookies)
'Path of the Exe
Dim Location As String = System.Reflection.Assembly.GetExecutingAssembly().Location
Dim os As OperatingSystem
os = Environment.OSVersion
MessageBox.Show(os.Version.ToString()) 'OS Version
MessageBox.Show(os.Platform.ToString()) 'OS Platform

C#.NET Code
string PersonalDir = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
string CookiesDir = Environment.GetFolderPath(Environment.SpecialFolder.Cookies);
//Path of the Exe
string Location = System.Reflection.Assembly.GetExecutingAssembly().Location;
OperatingSystem os = default(OperatingSystem);
os = Environment.OSVersion;
MessageBox.Show(os.Version.ToString()); //OS Version
MessageBox.Show(os.Platform.ToString()); //OS Platform

Code to Download the Files from Internet

Below Code will help you download files from internet.
it's very simple code just follow the few steps.
Step 1:Drag two textboxes a two button to ur form.
Step 2 : Just enter the Download Link in Download Location textbox
Step 3 : Just enter the path where u want to save the file.
Note:Download Link path and save as path should be correct.
Step 4 :Just Click the save as Button
Refer the Image Below
VB.NET Code
Private Sub btnSaveAs_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSaveAs.Click
Try
If txtLocation.Text.Trim = String.Empty Then
MessageBox.Show("Please Enter the Location from where you want to download", "San Test", MessageBoxButtons.OK, MessageBoxIcon.Information)
txtLocation.Focus()
Exit Sub
ElseIf txtSaveas.Text.Trim.Trim = String.Empty Then
MessageBox.Show("Please Enter the Location to where you want to Save teh File", "San Test", MessageBoxButtons.OK, MessageBoxIcon.Information)
txtSaveas.Focus()
Exit Sub
Else
My.Computer.Network.DownloadFile(txtLocation.Text, txtSaveas.Text & "\Santosh.jpg")
End If
Catch ex As Exception
MessageBox.Show("Please Enter the Correct Path", "San Test", MessageBoxButtons.OK, MessageBoxIcon.Information)
txtSaveas.Focus()
End Try
End Sub

Private Sub btnClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClose.Click
Me.Close()
End Sub
C#.NET Code
private void btnSaveAs_Click(System.Object sender, System.EventArgs e)
{
try {
if (txtLocation.Text.Trim == string.Empty) {
MessageBox.Show("Please Enter the Location from where you want to download", "San Test", MessageBoxButtons.OK, MessageBoxIcon.Information);
txtLocation.Focus();
return;
} else if (txtSaveas.Text.Trim.Trim == string.Empty) {
MessageBox.Show("Please Enter the Location to where you want to Save teh File", "San Test", MessageBoxButtons.OK, MessageBoxIcon.Information);
txtSaveas.Focus();
return;
} else {
My.Computer.Network.DownloadFile(txtLocation.Text, txtSaveas.Text + "\\Santosh.jpg");
}
} catch (Exception ex) {
MessageBox.Show("Please Enter the Correct Path", "San Test", MessageBoxButtons.OK, MessageBoxIcon.Information);
txtSaveas.Focus();
}
}

private void btnClose_Click(System.Object sender, System.EventArgs e)
{
this.Close();
}

Generate the Password Randomly

Just follow the below code tp generate the password character randomly....
Step:1 just drag a text box into the form
Step:2 Just Drag a Button into the form

Step3: write the below method
VB.NET Code
Private Function GenerateRandomNo()
Dim s As String="kkdskkds87430900403kdsjj88ds88899d9sefghijkmnopqrstuvwxyzABCDEFrer"
Dim rand As New Random
Dim count As Integer = s.Length
Dim arr As Char() = New Char(6) {} 'defined the array
For i As Integer = 0 To 6 'array length
arr(i) = s(s.Length * rand.NextDouble)
Next
Return New String(arr)
End Function

Step 4:click the button
Private Sub btnGenerate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGenerate.Click
TextBox1.Text = GenerateRandomNo()
End Sub

C#.Net Code
public class frmRandomPassGen
{
//generate the password Randomly
private object GenerateRandomNo()
{
//just define some
string s = "hdaskkdskkds87430900499d9sefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRST";
Random rand = new Random();
int count = s.Length;
char[] arr = new char[7];
//defined the array
//array length
for (int i = 0; i <= 6; i++) {
arr[i] = s[s.Length * rand.NextDouble()];
}
return new string(arr);
}

private void btnGenerate_Click(System.Object sender, System.EventArgs e)
{
TextBox1.Text = GenerateRandomNo();
}
}

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

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/

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

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

Find last Day of a Month

Dim dt As DateTime = DateTimePicker1.Value
Dim days1 As Integer = Date.DaysInMonth(dt.Year(), dt.Month)
MsgBox("Last Day of " & dt.ToString("MMMM") & " is " & days1) 'Long Format("September")
MsgBox("Last Day of " & dt.ToString("MMM") & " is " & days1) 'Short ("Sep")
MsgBox("Last Day of " & dt.Month.ToString() & " is " & days1) 'Integer Format("9")


Any Doubt Plz post a Comment.

with Regards
santosh

Sort DataGridView in VB.NET

Dim MyDataView As New DataView
MyDataView = ds.Tables(0).DefaultView
MyDataView.Sort = "SortColumnName"
'SortColumnName is the name of the columnName of DataGridView you want to sort.
DGVFindList.DataSource = MyDataView