Sign up to the jQuery Grid Subscription list.

List Box Resort Solution

Original Post by RobertMc at http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2454479&SiteID=1

The Question :

I have a listbox with roughly 2500 items that were sorted when created. Now I want to re-sort the same listbox using the time and date portion of the string. Shown below are 5 items as is and then how I'd like the re-sort to place them in the listbox.

Initial Sort

25536_002 9/20/2007 10:37:04 PM
25536_002 9/20/2007 10:41:04 PM
25536_002 8/27/2007 8:41:17 AM
26875_001 9/20/2007 1:48:18 PM
26875_001 9/19/2007 12:38:12 PM

Final Sort

25536_002 8/27/2007 8:41:17 AM
25536_002 9/20/2007 10:37:04 PM
25536_002 9/20/2007 10:41:04 PM
26875_001 9/19/2007 12:38:12 PM
26875_001 9/20/2007 1:48:18 PM

I am hoping for a simple resolution.

Thanks,
RobertMC

The Accepted Answer (by Solitaire)


This is not so simple, involving some string manipulation, but I tested it with your sample data and it works.

Code Block
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim L As Integer, strdat As String
L = ListBox1.Items.Count
Dim strdate(L) As String
For x As Integer = 0 To L - 1
ListBox1.SelectedIndex = x
strdat = ListBox1.SelectedItem.ToString.Substring(20)
strdate(x) = strdat.PadRight(13) & (ListBox1.SelectedItem.ToString).Substring(0, 20)
Next x
ListBox1.Items.Clear()
For x As Integer = 0 To L - 1
ListBox1.Items.Add(strdate(x))
Next x
ListBox1.Sorted = True
For x As Integer = 0 To L - 1
ListBox1.SelectedIndex = x
strdat = ListBox1.SelectedItem.ToString.Substring(14)
strdate(x) = strdat & (ListBox1.SelectedItem.ToString).Substring(0, 13)
Next x
ListBox1.Items.Clear()
For x As Integer = 0 To L - 1
ListBox1.Items.Add(strdate(x))
Next x
End Sub

How to use Debugger

Original solution posted by ReneeC at http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1141328&SiteID=1

Sometimes the idea of using the debugger, can be intimdating to those unfamiliar with them.
This is a tutorial based in a standard piece a source code that we will supply for the purposes of this tutorial. We're going to make a cheap MP3 player. I hope this tutorial is highly interactive and constructive.
Needed Ingredients:
1.) A test directory with about 4 mp3 files. Make them as short as possible.
2.) Create a new Windows project. In the form Designer, add:
a.) A progressbar called progressbar b.) Two buttons, One named btPlay and the other called btStop. In their respective text property boxes in the designer, insert Play and Stop. c.) A windows Media Player control. This probably is not in your toolbox. Go to Tools Choose Toolbox Items COM Windows Media Player. It will now appear at the bottom of your toolbox. Add a media player to your form and name it wmp in it's properties window in the forms designer.
3.) Close the Project to write it to a directory and re-open it
4.) Go to the source editor and depress Control-A and then depress the delete Key.
5.) Then select, copy and paste the following source code:
Imports AxWMPLib
Imports WMPLib

Imports System.Runtime.InteropServices
Public Class Form1
Protected Friend WithEvents tmr As New Timer
Private Duration As Single
Const SongDirectory As String = "InsertYourTestDirectoryPathHere"

Private Sub Form1_Load(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Me.Load
tmr.Interval = 1000 : tmr.Stop()
dim a as integer = 0 'Demo not relevant to the code
a = 1 'Demo not relevant to the code
End Sub

Private Sub btPlay_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles btPlay.Click
NewSong()
End Sub

Private Sub NewSong()
Dim Song as String = ""
ProgressBar.Value = 0
Song = ChooseRandomSong()
if Song <> "" then
wmp.URL = song
wmp.Ctlcontrols.play()
else
btPlay.enabled = false
beep()
end if
End Sub

Private Sub tmr_Tick(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles tmr.Tick

If wmp.playState = WMPPlayState.wmppsPlaying Then
ProgressBar.Value = _
(wmp.Ctlcontrols.currentPosition / Duration) * 100
Else
tmr.Stop()
btPlay.PerformClick()
End If
End Sub

Private Sub Player_PlayStateChange(ByVal sender As System.Object, _
ByVal e As _ AxWMPLib._WMPOCXEvents_PlayStateChangeEvent) _
Handles wmp.PlayStateChange

Dim NewState As WMPPlayState = e.newState

Select Case e.newState

Case WMPPlayState.wmppsBuffering
Case WMPPlayState.wmppsMediaEnded
ProgressBar.Value = 0
Case WMPPlayState.wmppsPaused
Case WMPPlayState.wmppsPlaying
Duration = wmp.currentMedia.duration
tmr.Start()
Case WMPPlayState.wmppsReady
Case WMPPlayState.wmppsReconnecting
Case WMPPlayState.wmppsScanForward
Case WMPPlayState.wmppsScanReverse
Case WMPPlayState.wmppsStopped
Case WMPPlayState.wmppsTransitioning
Case WMPPlayState.wmppsWaiting
Case Else
End Select
End Sub

Private Function ChooseRandomSong() As String
Dim DI As New System.IO.DirectoryInfo(SongDirectory)
Dim fi() As System.IO.FileInfo = DI.GetFiles()
Static Song As String = ""
Static LastSong As String = ""
Static SongList As New List(Of String) : SongList.Clear()
For Each file As System.IO.FileInfo In fi
If file.Extension.ToLower = ".mp3" Then
SongList.Add(file.FullName)
End If
Next

If SongList.Count = 0 Then Return ""
Static rnd As New Random
Static num As Int32
Song = LastSong
While Song = LastSong
num = rnd.Next(SongList.Count)
Song = SongList(num)
End While
LastSong = Song
SongList.Clear()
Return Song
End Function
End Class

Please note the board editor introduces spurious line wraps and may introduce syntax errors around continuations. if you see squiggles after adding everything, make all lines with the continuation character "_" one line, deleting the "_" and the space in front of it.
Be sure to insert your mp3 directory here:
Const SongDirectory As String = "InsertYourTestDirectoryPathHere"
Depress the save all files button above.
Go to View Toolbars and make sure that the debug toolbar is checked.

1.) Go to the source editor
2.) Find this line in the load event tmr.Interval = 1000 : tmr.Stop() (These are actually two lines of code separated by a ":".
3.) On exactly the same horizontal level as that line, to the left of the editor, do a single left click. A brown dot should appear. click until a brown dot does apear. [see Dave's comments below]
4.) In the debug toolbar, make sure the locals windows is depressed (activated).
5.) Depress the Green right triangle up above.
6.) What happened?
7.) Make sure you can see the Locals window.
8.) In the debugger toolbar, you will see the Green Arrow, and a [] square. To the right you will see a button with the a line and arrow pointing into the middle of lines. This is the "Step Into" control. On its right you will see the the "Step Over" control.
9.) Watching the Locals window, depress the Step Into button and look for a
10.) Depress the Step Into Button and look at a now.
11.) Finally depress the Green arrow.
What Happened?

1.) Make sure the debugger is not running. [ ] Button
2.) Go to your single existing break point by putting your cursor on the Brown dot representing the break point and left click on it. The Break point is deleted.
Now let's see if your project is working.
3.) Making sure your speakers are on, Depress the Green arrow, and your project should appear on the screen.
4.) Depress the Play button and you should hear one of your mp3s startup. Allow it to play through.
5.) While listening, put a new break point on this line:
Private Sub NewSong()
ProgressBar.Value = 0 ' Set a break here and wait for the ' song to finish.

6.) Depress the Step Over Button and observe the editor.

7.) Stop the project [ ].

8. Repeat step 4 and then 9.

9.) This time, depress the step into button oberving what happens, depress it again and again and again.

What was different?

1.) Stop your project [ ] and delete all of your previous break points.
2.) Insert a break point at this Next Statement
For Each file As System.IO.FileInfo In fi
If file.Extension.ToLower = ".mp3" Then
SongList.Add(file.FullName)
End If
Next
3.) Start your project with the Green Arrow. Depress the Play Button.
4.) When your breakpoint is reached, place your cursor here:
Static SongList As New List(Of String) : SongList.Clear()
on Songlist
5.) A window will appear. Put your mouse on the + boxes and new windows will appear
6.) Follow the + signs to the end.
7.) Depress the green arrow so you execute the loop again. Repeat steps 4 -6
8.) Repeat 7 again and again.
9.) Stop your Project
10.) Delete all Breakpoints
11. Place a breakpoint Here:
While Song = LastSong
num = rnd.Next(SongList.Count)
Song = SongList(num)
End While
LastSong = Song
SongList.Clear()Return Song ‘ Set your breakpoint here.
12.) Start your project
13.) Depress Play
What is the contents of Song?
1.) Stop your project.
2.) Delete your breakpoints.
3.) Place a point here:
Private Sub btPlay_Click(ByVal sender As Object, _
4.) Start your project
5.) Press Play......
6.) After observing that. Stop your project and delete all break points
7.) Place a break point here:

Private Sub tmr_Tick(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles tmr.Tick

If wmp.playState = WMPPlayState.wmppsPlaying Then
ProgressBar.Value = _
(wmp.Ctlcontrols.currentPosition / Duration) * 100
Else
tmr.Stop()
btPlay.PerformClick()
End If
End Sub
At tmr.stop
8.) Start your prject with the green arrow
9.) Depress Play
10.) Listen to the music until the end and watch the screen......

Solution for a pattern (Regular Expression)

Original post by cheatcountry at http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2362267&SiteID=1

The Question :

If I want the first letter in what I am looking for to be a value of a variable then how do I reference that variable in my reg expression?

The accepted answer : (By Gunjan246 )

string var = "A";
string pattern = @"\s" + var + "[A-Z]{0,4}\s";

Debugger HELP (General Dot Net)

Original post by MaxSpd at http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2422508&SiteID=1

The Question :

I have a project i am working on usint VB.net software and got into a jom...



here is the issue:



I created a project and wrote some code and slapped on the stuff into the windows application form1



I saved it all and exited...



Came back a few days later opened the project...put some more code and alligned the windows application form1.



Saved All



Run the debugger and it will only show the form1 from when i originally saved it and not when its all cleaned up and all the buttons and text boxes are alligned all pretty and only the code entered at that time is working at the time of the debgger...



When i stop and go back the new code is still there and the updated form1 is nice and neat...run the debugger again...same deal...only shows and runs the form1 code from the first save...



I save again and exit VB.net



go back and start the VB.net...all new code is there, form1 is nice and neat...



run the debugger...still only runs original code and not new code...still shows the unaligned form1 i slapped labels, buttons and textboxes into originally...



How can i make the debugger run the new code and pull up the updated version of the form1 with aligned labels, buttons and textboxes that show in design view???


The accepted answer : (By Dave 299)



Under Tools Options click on Show all Settings at the bottom, then expand the Projects and Solutions branch and select Build and Run. Ensure that under "On run when build or deployment errors occur" you have not got Launch Old Version selected.


Importing data from an Excel spreadsheet into a VB 2005 application SQL table

Original post by Carl Am at http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2375068&SiteID=1

The Question :

I am trying to re-write a VB6 application in VB 2005. One of the problems I have is I need to be able to import a spreadsheet into an SQL table. I have my VB 2005 application interface, where I need to enter the filename to import and then click a button. The old VB6 way was the transferspreadsheet command. I set my application to use an Access database.

What is the best way to achieve this in VB2005?.


The accepted answer : (by gpasp)


Private Sub loadDataFromExcel()
Dim excelFile As String = "c:\someDirectory\someFile.xls" 'replace with valid path - file
Dim excelSheet As String = "[Sheet1$]" 'replace with valid Sheet Name
Dim sql As String = "SELECT * FROM " & excelSheet ' add WHERE and ORDER if required
Dim tableName As String = "theNameYouLike"
Try
Using cn As New OleDb.OleDbConnection
' HDR = YES if first row contain column name else NO
' Excel 8.0 / 9.0 ... depending on your Excel version
cn.ConnectionString = "provider=Microsoft.Jet.OLEDB.4.0;" & _
"data source=" & excelFile & ";" & _
"Extended Properties=""Excel 8.0;HDR=YES"""

Dim da As OleDb.OleDbDataAdapter = New OleDb.OleDbDataAdapter(sql, cn)
cn.Open()
da.Fill(yourDataSetName, tableName)
cn.Close()
End Using
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
'TODO proccess data to add / update other tables
End Sub

Filter and Sort a Table in VB 2005 Express

Orginal post by Konker at http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2401261&SiteID=1

The Question :

I am using Visual Basic 2005 Express and wish to create a subset from a SQL database table, and then sort on a column of the subset. I can get the table into visual Basic but cannot then figure out how to create and then sort a subset.


The accepted answer : (by Riquel Dong)

Hi Knoker,



Based on your post, my understanding of your question is that you fill the data into a datatable from the database and need to filter and data. You can use filter property and sort property of the BindingSource class to handle this problem.



The BindingSource Filter property is used to filter the in-memory bound data source so that only rows that meet the criteria in the Filter string are made "visible" to the binding mechanism. The BindingSource Sort property is implemented like the ADO.NET DataView Sort property. This means you can name any column and indicate "ASC" (the default) for an ascending sort or "DESC" for a descending sort. For more information about how to use the bindingsource class, visit: http://www.databaseportal.org/Visual-Studio-and-SQL-Server/Using-the-Binding-Source-Class.html. Here is the simple code snippet to use this class. I use the Access database here.


Code BlockImports System.Data.OleDb

Public Class Form1

Dim con As OleDbConnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Northwind.mdb")

Dim sql As OleDbCommand = New OleDbCommand("SELECT * FROM Shippers", con)

Dim ds As DataSet = New DataSet()

Dim DataAdapter1 As OleDbDataAdapter = New OleDbDataAdapter()

Dim bs As New BindingSource

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

bs.Filter = "ShipperID>'15'"

bs.Sort = "CompanyName DESC"

End Sub

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

con.Open()

DataAdapter1.SelectCommand = sql

DataAdapter1.MissingSchemaAction = MissingSchemaAction.AddWithKey

DataAdapter1.Fill(ds, "Shippers")

bs.DataSource = ds.Tables("shippers")

DataGridView1.DataSource = bs

con.Close()

End Sub

End Class






Best regards,

Riquel

Tell your story to Microsoft and Win 100 $

Microsoft Express Heroes Promotion
Want a chance to show off a cool project you’ve created using Visual Studio or SQL Server Express? We’re looking for your stories! Tell us about something that makes your life easier or is just plain fun and if we like it enough to include in a feature article, we’ll give you a $100 Amazon.com gift certificate!

Here’s how to enter:

Send an email to exphero@microsoft.com
Please include your name, email, and a description of how you’re using the Express products. Make sure to tell us enough details that we can understand just how cool it is!
You’re free to submit multiple projects, but please only one per email submission.
If you are selected, we will contact you back via your email address.
Good luck!

For More information have a look @ http://msdn2.microsoft.com/fr-fr/vstudio/Aa718400.aspx



Feed Burner was added to MSDN Forums Tracker!

Hi then!
I just added feed burner to this blog. Why then ? If you are new to Rss and feed burner you may ask what's this? Simply if you want to receive (in your mail box) our lastet posts and the lastet answered posts you subscribe your email!

Subscribe then now if you are interested !

Return multiple values from a function (Visual Basic General)

Original post by c.hunter at http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2415779&SiteID=1


The Question :
I have a function that sends out emails to four users. I am to add another a fifth one but i can get it to go out can some one please help? Here is my code...

Thanks





Private Function GetRecipient(ByVal state As String) As String

Dim Central As String = "AR,IA,IL,KS,LA,MN,MO,MS,NE,OK,TN,TX,WI"

Dim Eastern As String = "AL,CT,DC,DE,FL,GA,IN,KY,MA,MD,ME,MI,NC,NH,NJ,NY,OH,PA,RI,SC,VA,VT,WV"

Dim Western As String = "AK,AZ,CA,CO,HI,ID,MT,ND,NM,NV,OR,SD,UT,WA,WY"

If state.Split(" - ").Length >= 1 Then

Dim shortState As String = state.Split(" - ")(state.Split(" - ").Length - 1)

'lblerror.Text = shortState

If Central.IndexOf(shortState) >= 0 Then

Return "cxcas@domain.com"

ElseIf Eastern.IndexOf(shortState) >= 0 Then

Return "fndda@domain.com"

ElseIf Western.IndexOf(shortState) >= 0 Then

Return "assddf@domain.com" <------------------------------- Want to add the other email address here. ElseIf shortState = "USA" Then Return "kortaed@domain.com" Else Return "NONE" End If Else Return "NONE" End If End Function
The Accepted answer :

Create a StringArray and store all return values into it. Then return the Array.
Ex:

Function ReturnArrayExample() as String()
Dim strarray(2) as String
strarray(0)= value 1
strarray(1)= value 2
strarray(2)= value 3

return strarray

End Function

To access values from Array use strarray(indexnumber).
Ex:
msgbox(strarray(0))

This will display value 1.

So your Function is modified like this:


Private Function GetRecipient(ByVal state As String) As String()

Dim strarray(3) as String


Dim Central As String = "AR,IA,IL,KS,LA,MN,MO,MS,NE,OK,TN,TX,WI"

Dim Eastern As String = "AL,CT,DC,DE,FL,GA,IN,KY,MA,MD,ME,MI,NC,NH,NJ,NY,OH,PA,RI,SC,VA,VT,WV"

Dim Western As String = "AK,AZ,CA,CO,HI,ID,MT,ND,NM,NV,OR,SD,UT,WA,WY"

If state.Split(" - ").Length >= 1 Then

Dim shortState As String = state.Split(" - ")(state.Split(" - ").Length - 1)

'lblerror.Text = shortState

If Central.IndexOf(shortState) >= 0 Then

strarray(0)="cxcas@domain.com"

ElseIf Eastern.IndexOf(shortState) >= 0 Then

strarray(0)="fndda@domain.com"

ElseIf Western.IndexOf(shortState) >= 0 Then

strarray(0)="assddf@domain.com" <------------------------------- Want to add the other email address here. strarray(1)="another email address" ElseIf shortState = "USA" Then strarray(0)="kortaed@domain.com" Else strarray(2)= "NONE" End If Else strarray(3)= "NONE" End If return strarray End Function I hope this will help. More Accepted solutions :

Hi,



Here is another way to do it, I have changed the FUNCTION to a SUB and still changed some array values.



Add one button to a FORM to test this code please.









Regards,



John

______________________________________________







Option Strict Off



Public Class Form1



'Declare this array big enough for your needs here.>>

Private email(9) As String



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

'Call the SUB Test() to test the FUNCTION.

Call Test()

End Sub









Private Sub Test()



Call GetRecipient("CA")



Dim outputString As String = ""

For index As Integer = 0 To 9

If email(index) <> "" Then

outputString &= email(index) & ControlChars.NewLine

End If

Next

MessageBox.Show(outputString)

End Sub









Private Sub GetRecipient(ByVal state As String)

Dim Central As String = "AR,IA,IL,KS,LA,MN,MO,MS,NE,OK,TN,TX,WI"

Dim Eastern As String = "AL,CT,DC,DE,FL,GA,IN,KY,MA,MD,ME,MI,NC,NH,NJ,NY,OH,PA,RI,SC,VA,VT,WV"

Dim Western As String = "AK,AZ,CA,CO,HI,ID,MT,ND,NM,NV,OR,SD,UT,WA,WY"

If state.Split(" - ").Length >= 1 Then

Dim shortState As String = state.Split(" - ")(state.Split(" - ").Length - 1)

'lblerror.Text = shortState

If Central.IndexOf(shortState) >= 0 Then

email(0) = "cxcas@domain.com"



ElseIf Eastern.IndexOf(shortState) >= 0 Then

email(0) = "cxcas@domain.com"



ElseIf Western.IndexOf(shortState) >= 0 Then

'Now changing two values in the array named "email".

'No RETURN statements are needed as this is now a SUB.

email(0) = "cxcas@domain.com"

email(1) = "joe-bloggs@domain.com"



ElseIf shortState = "USA" Then

email(0) = "kortaed@domain.com"

Else

End If

Else

End If

End Sub

End Class

division remainders and if statments ( Visual Basic General)

Original Post by alex905 at http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2421317&SiteID=1

The problem
alex905 :
hi i have a unsual question and im very bad at explaing things so please bear with me.

i have this code

'these are entered by the user
dim dig as single = 27
dim slt as single = 8

dim sltval as single

dim digval as single







If dig + slt = 0 Then

ElseIf dig = 0 Then
sltval = slt / 16
ElseIf slt = 0 Then
digval = dig / 16
Else
' im not sure
End If




now im gonna try and explain it all. this code if to help a cusotmer buy a telephone system. he can buy a 16 port dig card, 8 port dig card, 16 port slt card or a combo 8 slt and 8 dig port card. the variables dig and slt are the amnount of ports. what i want to do with thse numbers is try and find out how many of each card the customer needs. still with me.

i got as far as dividing that amount of ports needed by the card with the most amount of ports (which i can do) then if their is a remainder above 8 add on another card if below 8 add on a 8 port card. but its not as easy as that as their are two types of port. so its fine if they only need one type of port whihc i have sort of covered in my code but if they have both types of port im lost. i know that if i use the figures i set in the variables above they would need.

27/16 = 1 and 11 remainder this means that i say the guy needs two 16 port dig cards. if the remander was below 8 i would say he needs one 16 port and one 8 port. but we have some slt ports aswell. so thats 8 whihc is les than or equle to 8 so one 8 port card is needed.

you still their. i dont expect anyone to help with this as it is long winded and overly complex. but my baic qustion is which division, how do you show whole numbers and the remanders not decimal places, and then put the remanders and whole numbers into differnet variables.


The Accepted solution

Dim x as integer = 10 Mod 3 ' Remainder
Dim y as integer = 10 \ 3 ' Whole number from division

MsgBox(x.ToString & " " & y.ToString)


hth,
Olice

Welcome to the MSDN Forums Tracker

Hi again!
What's this also, another blog for programers ?
Yes and from now you don't have to search on Google engines to solve your problems on Microsoft Programming.
How this work ?
Shortly we work on getting the best answered topic on the MSDN forums and we post them!
You can access the MSDN forums here : http://forums.microsoft.com/
We don't give you all MSDN forums answers but only best and that we find helpful!
Have find browsing answers!