C# – Get Selected Values from MultiSelect ListBox

May 30, 2010

How to iterate MultiSelect ListBox using C# (.NET)

Here is a way of retrieving the selected values of Multiselect listbox

  1. for (int i1 = 0; i1 < listBox1.SelectedItems.Count; i1++)
  2. {
  3. DataRowView D1 = listBox1.SelectedItems[i1] as DataRowView;
  4. MessageBox.Show(D1[1].ToString());
  5. }
for (int i1 = 0; i1 < listBox1.SelectedItems.Count; i1++)
            {
                DataRowView D1 = listBox1.SelectedItems[i1] as DataRowView;

                MessageBox.Show(D1[1].ToString());
            }

The above code uses SelectedItems collection to retrieve information Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl // StumbleUpon

Posted by Shasur at 12:34 AM
Labels: , ,

Formatting Currency in C#/VB.NET/Csharp Writeline function

May 30, 2010

How to format Currency (Pound/Dollar/Euro etc) using C#/VB.NET/Csharp Writeline function

You can use .NET’s Composite Formatting to format the currency as shown below

  1. Double Incentive = 234.45;
  2. Console.WriteLine(“The agreed incentive in local currency is {0:C} ”, Incentive);
    Double Incentive = 234.45;
            Console.WriteLine("The agreed incentive in local currency is {0:C} ", Incentive);

If you want to convert it into dollars/pounds etc you need to change the culture info :

  1. Thread.CurrentThread.CurrentCulture = new CultureInfo(“en-US”, false);
  2. Console.WriteLine(“The agreed incentive in USD is {0:C} ”, Incentive);
  3. Thread.CurrentThread.CurrentCulture = new CultureInfo(“en-GB”, false);
  4. Console.WriteLine(“The agreed incentive in GBP is {0:C} ”, Incentive);
            Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US", false);
            Console.WriteLine("The agreed incentive in USD is {0:C} ", Incentive);

            Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB", false);
            Console.WriteLine("The agreed incentive in GBP is {0:C} ", Incentive);

The above code needs the following directives

  1. using System.Threading;
  2. using System.Globalization;
using System.Threading;
using System.Globalization;

Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl // StumbleUpon

Posted by Shasur at 12:37 AM
Labels: , ,

Building an Electronic Clock in VB.Net using timer class

April 27, 2008

Using Timer in VB.Net


Building an Electronic Clock in VB.Net using timer class

(VB.NET ProgressBar using Timer)

Public Class Form1

Dim t As New Timer

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

t.Interval = 1000

AddHandler t.Tick, AddressOf Me.t_ShowProgress

AddHandler t.Tick, AddressOf Me.t_ShowTime

t.Start()

End Sub

Private Sub t_ShowProgress()

ProgressBar1.Value += 10

If ProgressBar1.Value = 100 Then

ProgressBar1.Value = 0

End If

End Sub

Private Sub t_ShowTime()

Label1.Text = Now

End Sub

End Class

Add Handler – Associates an event with an event handler at run time. The Handles keyword and the AddHandler statement both allow you to specify that particular procedures handle particular events, but there are differences. The AddHandler statement connects procedures to events at run time. Use the Handles keyword when defining a procedure to specify that it handles a particular event.

The Tick event (this is similar to Visual Basic Timer1_Timer event) occurs when the specified timer interval has elapsed and the timer is enabled. This is based on the interval set for the Timer (1000 ms or 1 sec here)

The progress bar will be reset after it reaches 100. The timer will run till the form is closed. Since the process is synchronous only the timer event will be executed or the label will be updated. The same can also be achieved async

Regular Expressions in Dot Net (.NET)

Finding Duplicate Words in a String using .NET Regular Expressions

Regular Expressions (REGEX) does wonders in programming. Here is a simple Regex code that identifies duplicate words like ‘the the’, ‘something something’ etc. Probably copyeditors can use this code to do the work that Microsoft Spell check does

Sub Regex_Checker_Duplicate_Words()

Dim oRegex As Regex

Dim sPattern As String

Dim oMatches As Match

Dim sText As String

sText = ” the the category catastropic cat cat and rat b b “

sPattern = “\b([a-zA-Z]+)\s+\1″

oRegex = New Regex(sPattern)

oMatches = oRegex.Match(sText, sPattern)

While oMatches.Success

MsgBox(oMatches.Groups(0).Value.ToString)

oMatches = oMatches.NextMatch

End While

End Sub

Returns a new Match with the results for the next match, starting at the position at which the last match ended (at the character beyond the last matched character).

Get Computer Name in .Net

December 25, 2007

Get Computer Name in .Net

Use the My object to get the name of the computer

‘ Returns Name of the Computer

Function Get_Comp_Name() As String

Return My.Computer.Name.ToString

End Function

The VBA/Visual Basic function to do the same is :
http://vbadud.blogspot.com/2007/05/get-computer-name.html

The SQL Statement to get the computer name is :
http://sqldud.blogspot.com/2007/04/get-computer-name-from-sql-query.html

Changing LINKS

ASP.Net Get User / .Net Get User

December 25, 2007

ASP.Net Get User / .Net Get User

User names are the most important ones. Whether to write in logs or display a warm hello message, it is there throughout

Here let us look at the way to get the user of the system. Webdevelopemt will have different ‘users’.

Function Get_User_Name() As String

Return My.User.Name

End Function

BlogRankings.com

Again the My namespace comes in handy

The same can be done using VBA :
http://vbadud.blogspot.com/2007/05/get-computer-name.html

For knowing the user using SQL select statement please refer :

Opening & Closing Forms in .Net

December 25, 2007

Opening & Closing Forms in .Net

Opening & Closing the forms have changed from Visual Basic 6.0 to VB.Net

The Form object in Visual Basic 6.0 is replaced by the Form class in Visual Basic 2005. The names of some properties, methods, events, and constants are different, and in some cases there are differences in behavior

Form1.Show Modal=True in VB 6.0 is replaced with the ShowDialog

Sub Show_Form_Modal()

Form1.ShowDialog() ' Modal

End Sub

Sub Show_Form_Modeless()

Form1.Show() ' Modeless

End Sub

Closing which was done by Unload(Me)

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

Me.Close()

End Sub

Top Computers blogs

VB.Net Form Close vs Form Dispose

December 25, 2007

VB.Net Form Close vs Form Dispose

Two methods doing some identical jobs always create some confusion. What to use to ‘unload’ the form Form.Close or Form.Dispose

Form.Close should be the answer as going by Microsoft Form.Close disposes the form as well if the form Modeless .

One more advantage you get from this method is from the events that are associated with the form

You can prevent the closing of a form at run time by handling the Closing event and setting the Cancel property of the CancelEventArgs passed as a parameter to your event handler.

Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
If MessageBox.Show(“Form is closing”, “Form Close”, MessageBoxButtons.YesNo, MessageBoxIcon.Hand) = Windows.Forms.DialogResult.No Then
e.Cancel = True
End If
End Sub

The above prevents the form being closed

When the form is opened as Modal form (using Showdialog) you can dispose the form explicitly


Setting Default & Cancel Buttons in Visual Basic.Net Form

December 25, 2007

VB.Net Setting Default & Cancel Buttons

Setting Default & Cancel Buttons in Visual Basic.Net Form

Default button is in VB.NEt with a different name – AcceptButton. However, cancel button retains its name:

Here is a way you can set them

Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

‘Sets cmdOK as the button control that is clicked when the user presses the Enter key.
Me.AcceptButton = cmdOK

‘Sets cmdCancel as the button control that is clicked when the user presses the ESC key.
Me.CancelButton = cmdCancel

End Sub

For setting the same in VBA/VB refer : http://vbadud.blogspot.com/2007/06/setting-default-cancel-buttons-in.html

Get Folder Size using .Net

December 25, 2007

Directory Size using VB.Net

For getting the size of each directory in Vb.Net, you need to add up the size of each file in the directory.

This function gets the size of each directory including sub-directories and writes to a text file

Imports System.IO

Dim oBuffer As System.IO.TextWriter

Function Get_Directory_Size(ByVal sDirPath As String)

Dim lDirSize As Long
Dim oDir As DirectoryInfo
Dim sDir As DirectoryInfo
Dim sFiles As FileInfo
Dim iFN As Short ‘* File Number
Dim sPath As String ‘* Saving Path

‘Dim oFSW As System.IO.FileSystemWatcher

oDir = New DirectoryInfo(sDirPath)

Dim oDirs As DirectoryInfo() = oDir.GetDirectories()

For Each sDir In oDirs

lDirSize = 0

For Each sFiles In sDir.GetFiles(“*.*”)
lDirSize += sFiles.Length
Next

‘——————————————————–
‘ Coded by Shasur for http://dotnetdud.blogspot.com/
‘——————————————————–

‘MsgBox(“Size of Directory ” & sDir.Name & ” is ” & lDirSize)
oBuffer.WriteLine(sDir.FullName & vbTab & lDirSize)

Get_Directory_Size(sDirPath & sDir.Name & “\”)

Next

End Function

The procedure below uses WriteLine function of the StreamWriter class

Sub Store_Size_Of_Directory

Dim sOPFile As String

sOPFile = c:\SystemDirSize.log”

‘——————————————————–
‘ Coded by Shasur for http://dotnetdud.blogspot.com/
‘——————————————————–

oBuffer = New System.IO.StreamWriter(sOPFile)
oBuffer.WriteLine(Now())

Get_Directory_Size(“c:\”)

oBuffer.Close()
End Sub

Directory Selection in Windows Forms using VB.Net

December 25, 2007

Selecting a Folder in VB.Net

The Visual Basic 6.0 DirListBox control has been rendered obsolete by the OpenFileDialog and SaveFileDialog components in Visual Basic 2005. If you want to select a directory FolderBrowser Dialog will be the one you need to use

For this example, Let us have a form with a TextBox and a command button. When the command buton is pressed, the folderdialog is shown and then the selected folder is displayed in the textbox

Sample Form:

Add the FolderBrowser Dialog to the form from the Dialogs Collection (see below).

This control will not be placed on the form but on a separate tray at the bottom of the Windows Forms Designer. (see below)

Now in the click event for the Button have the following code:

Private Sub BtnFolder_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnFolder.Click

Dim MyFolderBrowser As New System.Windows.Forms.FolderBrowserDialog

‘ Descriptive text displayed above the tree view control in the dialog box
MyFolderBrowser.Description = “Select the Folder”

‘ Sets the root folder where the browsing starts from
‘MyFolderBrowser.RootFolder = Environment.SpecialFolder.MyDocuments

‘ Do not show the button for new folder
MyFolderBrowser.ShowNewFolderButton = False

Dim dlgResult As DialogResult = MyFolderBrowser.ShowDialog()

If dlgResult = Windows.Forms.DialogResult.OK Then
txt_watchpath.Text = MyFolderBrowser.SelectedPath
End If

End Sub

The FolderBrowserDialog component is displayed at run time using the ShowDialog method. Set the RootFolder property to determine the top-most folder and any subfolders that will appear within the tree view of the dialog box. Once the dialog box has been shown, you can use the SelectedPath property to get the path of the folder that was selected

For similar functionality in VB6.0 refer http://vbadud.blogspot.com/2007/04/browse-folder-select-folder-thru-shell.html

When a Visual Basic 6.0 application is upgraded to Visual Basic 2005, any existing DirListBox controls are upgraded to the VB6.DirListBox control that is provided as a part of the compatibility library (Microsoft.VisualBasic.Compatibility).


Follow

Get every new post delivered to your Inbox.