How to track item's index in type list - vb.net

This may be a simple question, but I'm having a real mental block on it. I'm trying to track the index of a Report in my reportList (of Report type) when navigating forwards and backwards through the list.
I've done this one way by assigning the index of the selected item in a combobox. However I also need to do it directly from the list (already filled), with the only input of the user being the next and previous buttons.
Where I set the Report:
If wantFixture = True Then
ind = UC_Menu_Scout1.cmbSelectedPlayer.SelectedIndex
Else
ind = reportList(0) 'index of item in reportList-
'this doesn't work because reportList is of type Report, not integer
End If
reportList.Clear()
reportList = retrieveReport()
'*****General Information
UC_Menu_Scout1.lblRptPosition.Text = reportList(ind).PositionPlayed
Where the next Report can be navigated to:
Private Sub btnNextPlayer_Click(sender As System.Object, e As System.EventArgs) Handles btnNextPlayer.Click
'Moves to next item in playerList
Dim x As Integer = cmbSelectedPlayer.SelectedIndex
If x = cmbSelectedPlayer.Items.Count - 1 Then
x = 0
Else
x += 1
End If
cmbSelectedPlayer.SelectedIndex = x
lblNumberOfReports.Text = "Report: " & x + 1 & "/" & cmbSelectedPlayer.Items.Count
End Sub

Store the current index and report in variables.
Class level variables:
Private curIndex As Integer = 0
Private curReport As Report = Nothing
Next button:
If Not curIndex = reportList.Count - 1 Then
curIndex += 1
End If
curReport = reportList.ElementAt(curIndex)
Previous button:
If Not curIndex = 0 Then
curIndex -= 1
End If
curReport = reportList.ElementAt(curIndex)

Related

How to freeze merged columns in data grid view when scrolling vertically?

I have a data grid view where I need the columns to be frozen or fixed when scrolling vertically.
I have a data grid view control in vb.net windows application which displays the data in a parent-child hierarchy(as shown below). The first column displays the parent data and the second column displays all its child data. The child data in the second column can be as much as 100 rows or even more. So when scrolling down through the grid, the value in the first column does not remain there as it is while the values in the second column(i.e. the child data) scrolls down. So if the user wants to check to which parent, the current child info belongs to, then again he will have to scroll up to the starting of the column to find the name of the parent. I want the values in the first column to be displayed or frozen till it reaches the end of the list of its child values in the grid or at least till the next row where the next parent data starts. I have suggested the client to go with a tree view but they are not agreeing and need it in a data grid view itself. Is there anyway to achieve this in a data grid view?
Thanks in advance.
You can't freeze a row (in runtime, on dgv scrolling) with index greater than zero because all those before are frozen and at that point you can't scroll your datagridview.
If I understood correctly what you want I wrote this class quickly (probably should be optimized). Usage is simple.
1 - First create your own datagridview.
2 - then add your columns and rows (IMPORTANT: Put a “X” in the Tag in each row is a Parent or is considered as title for other rows as you seen in TestPopulate method) .
3 - Call the class I made by passing the datagridview (you created first) as a parameter. At this point this control takes its size, placement and REPLACE YOUR DATAGRIDVIEW .
Private Class CustomDgv
Inherits Panel
Dim WithEvents TopDgv As DataGridView = New DataGridView
Dim WithEvents DownDgv As DataGridView = New DataGridView
Dim Cols As Integer
' This variable is in case you have more rows as "headrow"
' In TestPopulate you can see how to get those
Dim listOfOwnerRows As List(Of Integer) = New List(Of Integer)
Dim currentTopRow As Integer = -1
Protected Overloads Property Height As Integer
Get
Return MyBase.Height
End Get
Set(value As Integer)
MyBase.Height = value
TopDgv.Height = TopDgv.RowTemplate.Height - 1
DownDgv.Height = value - TopDgv.Height - 1
End Set
End Property
Protected Overloads Property Width As Integer
Get
Return MyBase.Width
End Get
Set(value As Integer)
MyBase.Width = value
TopDgv.Width = value - 1
DownDgv.Width = value - 1
End Set
End Property
Sub New(dgvOriginal As DataGridView)
DownDgv = dgvOriginal
Dim parentCtrl As Control = dgvOriginal.Parent
parentCtrl.Controls.Remove(dgvOriginal)
parentCtrl.Controls.Add(Me)
Me.Location = DownDgv.Location
Me.Size = DownDgv.Size
Me.BorderStyle = DownDgv.BorderStyle
TopDgv.Width = Width - 2 - SystemInformation.VerticalScrollBarWidth
TopDgv.Height = TopDgv.RowTemplate.Height
TopDgv.ScrollBars = ScrollBars.None
TopDgv.ColumnHeadersVisible = False
TopDgv.BorderStyle = BorderStyle.None
DownDgv.ColumnHeadersVisible = False
DownDgv.BorderStyle = BorderStyle.None
TopDgv.Left = 0
DownDgv.Left = 0
DownDgv.Width = Width - 2
DownDgv.Height = Height - 2
For Each Col As DataGridViewColumn In DownDgv.Columns
Dim cIndex As Integer = TopDgv.Columns.Add(Col.Clone)
If Col.Frozen Then
TopDgv.Columns(cIndex).Frozen = True
End If
Cols += 1
Next
DownDgv.Top = 0
Me.Controls.Add(TopDgv)
Me.Controls.Add(DownDgv)
If DownDgv.Rows.Count > 0 Then
listOfOwnerRows = (From R As DataGridViewRow In DownDgv.Rows
Where R.Tag = "X"
Select R.Index).ToList
If listOfOwnerRows.Count > 0 Then
SetFrosenRow(listOfOwnerRows(0))
End If
End If
End Sub
Protected Sub SetFrosenRow(index As Integer)
If DownDgv.Rows.Count > index Then
TopDgv.Rows.Clear()
TopDgv.Rows.Add()
Dim currentRIndex As Integer = DownDgv.FirstDisplayedScrollingRowIndex
'If you want onlly the base row
For i As Integer = 0 To Cols - 1
TopDgv.Rows(0).Cells(i).Value = DownDgv.Rows(index).Cells(i).Value
Next
'Or else get the diplayed on top row
TopDgv.Rows(0).DefaultCellStyle = New DataGridViewCellStyle With {
.BackColor = Color.Bisque
}
currentTopRow = index
End If
End Sub
Protected Sub SetChildValuesInTopRow(index As Integer)
For i As Integer = 1 To Cols - 1
TopDgv.Rows(0).Cells(i).Value = DownDgv.Rows(index).Cells(i).Value
Next
End Sub
Private Sub DownDgv_Scroll(sender As Object, e As ScrollEventArgs) Handles DownDgv.Scroll
Try
If e.ScrollOrientation = ScrollOrientation.VerticalScroll Then
Dim topR As Integer = DownDgv.FirstDisplayedScrollingRowIndex
'If you want in top row the current value that is in the top uncomment this
SetChildValuesInTopRow(topR)
If listOfOwnerRows.Count > 0 Then
Dim rToSetAsOwner As Integer = listOfOwnerRows(listOfOwnerRows.Count - 1)
For i As Integer = listOfOwnerRows.Count - 1 To 0 Step -1
If listOfOwnerRows(i) <= topR Then
rToSetAsOwner = listOfOwnerRows(i)
Exit For
End If
Next
If rToSetAsOwner <> currentTopRow Then
SetFrosenRow(rToSetAsOwner)
End If
Console.WriteLine("rToSetAsOwner: " & rToSetAsOwner)
End If
Else
TopDgv.HorizontalScrollingOffset = DownDgv.HorizontalScrollingOffset
End If
Catch ex As Exception
Console.WriteLine(ex.ToString)
End Try
End Sub
End Class
Usage:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
Try
' first populate you grid putting a tag in each row which is a header/parent/title for other rows
TestPopulate()
Dim customControl As Control = New CustomDgv(DataGridView1)
Catch ex As Exception
Console.WriteLine(ex.ToString)
End Try
End Sub
Sub TestPopulate()
For i As Integer = 0 To 100
DataGridView1.Rows.Add()
If i = 0 Then
DataGridView1.Rows.Item(0).Cells(0).Value = "Owner 0"
DataGridView1.Rows(0).Tag = "X"
End If
If i = 50 Then
DataGridView1.Rows.Item(50).Cells(0).Value = "Owner 50"
DataGridView1.Rows(50).Tag = "X"
End If
If i = 70 Then
DataGridView1.Rows.Item(70).Cells(0).Value = "Owner 70"
DataGridView1.Rows(70).Tag = "X"
End If
DataGridView1.Rows.Item(i).Cells(1).Value = "child_" & i.ToString & "_1"
DataGridView1.Rows.Item(i).Cells(2).Value = "child_" & i.ToString & "_2"
Next
End Sub
I hope I have been helpful

Sorted List in Array Visual Basic [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 7 years ago.
I have a program that creates a list of 25 random numbers from 0 to 1,000. I have to buttons the first button will load a list box with the random numbers and the second button will sort the list of numbers from the smallest to largest which is where I implemented bubble sort code. Now the other list box that is supposed to hold the sorted numbers doesn't work properly it only shows one number instead of all of them.
Here is my code:
Option Strict On
Public Class Form1
Dim rn As Random = New Random
Dim Clicked As Long = 0
Dim numbers, sort As Long
Private Sub GenerateBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles GenerateBtn.Click
Clicked += 1
For x = 0 To 25
numbers = rn.Next(0, 1000)
RandomBox.Items.Add(numbers)
If Clicked >= 2 Then
RandomBox.Items.Clear()
Clicked = 1
End If
Next
End Sub
Private Sub SortBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SortBtn.Click
Dim Sorted() As Long = {numbers}
Dim Swapped As Boolean
Dim endOfArray As Integer = Sorted.Length - 1
Dim Tmp As Byte
While (Swapped)
Swapped = False
For I = 0 To endOfArray - 1
If Sorted(I) > Sorted(I + 1) Then
Tmp = CByte(Sorted(I))
Sorted(I) = Sorted(I + 1)
Sorted(I + 1) = Tmp
Swapped = True
End If
endOfArray = endOfArray - 1
Next
End While
SortBox.Items.Clear()
For I = 0 To Sorted.Count - 1
SortBox.Items.Add(Sorted(I))
Next
End Sub
End Class
Change your:
Dim Sorted() As Long = {numbers}
to
Sorted(x) = numbers
edit: Since you changed your code. You need to put back in the line that loads the Sorted Array.
For x = 0 To 25
numbers = rn.Next(0, 1000)
RandomBox.Items.Add(numbers)
Sorted(x) = numbers
If Clicked >= 2 Then
RandomBox.Items.Clear()
Clicked = 1
End If
Next
and remove the:
Dim Sorted() As Long = {numbers}
from the second part and put this declaration back in the beginning like you had:
Dim Sorted(26) as Long
The way you have will only show the latest random number. It is not any array but a single entity. Therefore only the latest will be add into the array. You need to load each number into the array as you create each one. Thus the (x) which loads it into position x.
You didn't use any arrays at all in your project...you're using the ListBox as your storage medium and that's a really bad practice.
I recommend you set it up like this instead:
Public Class Form1
Private rn As New Random
Private numbers(24) As Integer ' 0 to 24 = 25 length
Private Sub GenerateBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles GenerateBtn.Click
For x As Integer = 0 To numbers.Length - 1
numbers(x) = rn.Next(0, 1000)
Next
' reset the listbox datasource to view the random numbers
RandomBox.DataSource = Nothing
RandomBox.DataSource = numbers
' empty out the sorted listbox
SortBox.DataSource = Nothing
End Sub
Private Sub SortBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SortBtn.Click
' make a COPY of the original array that we will sort:
Dim sorted(numbers.Length - 1) As Integer
Array.Copy(numbers, sorted, numbers.Length)
Dim Swapped As Boolean = True
Dim endOfArray As Integer = Sorted.Length - 1
Dim Tmp As Integer
While (Swapped)
Swapped = False
For I As Integer = 0 To endOfArray - 1
If sorted(I) > sorted(I + 1) Then
Tmp = sorted(I)
sorted(I) = sorted(I + 1)
sorted(I + 1) = Tmp
Swapped = True
End If
Next
endOfArray = endOfArray - 1
End While
' reset the listbox datasource to view the sorted numbers
SortBox.DataSource = Nothing
SortBox.DataSource = sorted
End Sub
End Class
Also, note that you were decrementing endOfArray inside your for loop. You should only decrement it after each pass; so outside the for loop, but inside the while loop.
Additionally, you were using a Tmp variable of type Byte, but generating numbers between 0 and 999 (inclusive). The Byte type can only hold values between 0 and 255 (inclusive).
Your Bubble Sort implementation was very close to correct!

What else can cause an AxWindowsMediaPlayer to play?

I have a button in my program that grabs a bunch of information from a DataGridView object (volume, url, delay, etc) and using that, it plays a file. I'm trying to get the delay to work (wait x number of seconds before playing) and I'm pretty it will work, but whenever I press the button, the play starts immediately. There is no Ctlcontrols.play() anywhere in the program except after the delay, so I have no idea what is causing it to play.
I explained my problem a little bit more in comments. Sorry if I didn't explain my code very well. If you could just tell my what else could be causing my player to start immediately, that would probably be enough.
'snd_btn_go is the button that is supposed to start it.
'This sub doesn't matter as much for the problem, it will just go to SndCueGO() if both numbers are in the valid range.
Private Sub snd_btn_go_Click(sender As Object, e As EventArgs) Handles snd_btn_go.Click
Dim cue1 As Integer
Dim cue2 As Integer
cue1 = If(Integer.TryParse(snd_txt_cue_1.Text, cue1), Int(snd_txt_cue_1.Text), snd_num1)
If snd_txt_cue_2.Text <> "" Then
cue2 = If(Integer.TryParse(snd_txt_cue_2.Text, cue2), Int(snd_txt_cue_2.Text), snd_num2)
Else
cue2 = -1
End If
If (cue1 <= dgSound.Rows.Count - 1 And cue1 > 0) Then
SndCueGO(cue1, cue2)
End If
End Sub
'This sub pulls all the info from the correct row in the DataGrid and assigns it to a list. It'll check if the start volume and end volume are the same and if they're not, it'll fade to the end volume.
Private Sub SndCueGO(cue1, cue2)
Dim cues() = {cue1, cue2}
snd_num1 = cue1
Dim cuedata1 = snd_ds.Tables(0).Rows(cue1 - 1)
Dim cuedata2 = snd_ds.Tables(0).Rows(cue1 - 1)
If cue2 <> -1 Then
snd_num2 = cue2
cuedata2 = snd_ds.Tables(0).Rows(cue2 - 1)
End If
Dim data() = {cuedata1, cuedata2}
For i = 0 To 1
If cues(i) <> -1 Then
snd_delay(i) = data(i).Item("Delay")
snd_startvol(i) = safeNum(data(i).Item("Start_Vol."))
snd_file(i) = data(i).Item("File")
snd_in(i) = data(i).Item("Fade_In")
snd_out(i) = data(i).Item("Fade_Out")
snd_vol(i) = safeNum(data(i).Item("Vol."))
snd_hold(i) = data(i).Item("Hold")
snd_af(i) = If(data(i).Item("AF") = "", False, True)
player_list(i).URL = snd_file(i)
snd_current(i) = snd_startvol(i)
If snd_startvol(i) <> snd_vol(i) Then 'snd_startvol(i) and snd_vol(i) were the same in all my tests, so this should not run.
snd_next(i) = snd_vol(i)
Dim num_steps_up = snd_in(i) * snd_speed
Dim num_steps_down = snd_out(i) * snd_speed
Dim diff = snd_vol(i) - snd_startvol(i)
Dim small_step As Single
If diff > 0 Then
small_step = diff / num_steps_up
ElseIf diff < 0 Then
small_step = diff / num_steps_down
End If
snd_steps(i) = small_step
timer_snd_fade.Tag = 0
timer_snd_fade.Enabled = True
End If
timer_snd_master.Tag = 0 'resets the tag to 0
timer_snd_master.Enabled = True 'Starts timer
End If
Next
End Sub
Private Sub timer_snd_master_Tick(sender As Object, e As EventArgs) Handles timer_snd_master.Tick
If sender.Tag = snd_delay(0) Then
Player1.Ctlcontrols.play() 'This is the only play command in the program
Debug.Print("tag " & sender.Tag) 'These print after the delay
Debug.Print("delay " & snd_delay(0))
End If
sender.Tag += 1
End Sub
Inspect the:
AxWindowsMediaPlayer player1 = ...; // get the player from UI
IWMPSettings sett = player.settings;
sett.autoStart == ??
see the docs.
Probably it is set to true, as it's default value. Simply set it to false it the player will not play until Ctlcontrols.play() is invoked.

Insertion sort and taking related arrays with it

I need a bit of help with this insertion sort, The code I have so far is this:
Private Sub SortedList_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim currentitem As Integer = 2
While currentitem <= numitems
currentdataitem = frmEntry.starname(currentitem)
comparison = 1
finish = False
While comparison < currentitem And finish = False
If currentdataitem < frmEntry.starname(comparison) Then
shuffleitem = currentitem
While shuffleitem > comparison
frmEntry.starname(shuffleitem) = frmEntry.starname(shuffleitem - 1)
shuffleitem = shuffleitem - 1
End While
frmEntry.starname(comparison) = currentdataitem
finish = True
End If
comparison = comparison + 1
End While
currentitem = currentitem + 1
End While
arrayindex = 0
For Me.arrayindex = 1 To numitems
lstsorted.Items.Clear()
lstsorted.Items.Add(frmEntry.starname(arrayindex))
lstsorted.Items.Add(frmEntry.DOB(arrayindex))
lstsorted.Items.Add(frmEntry.rank(arrayindex))
Next
End Sub
This insertion sorts their names, but I also need to take their DOB and their rank with it, at what point in my visual basic code do I put this?
You can move the corresponding elements of DOB and Rank whenever you move the elements of starname.

Trouble with Timer_tick not stopping

I'm very new to programming and vb.net, trying to self teach more so as a hobby, as I have an idea for a program that I would find useful, but I am having trouble getting past this issue and I believe it is to do with the timer.
I have a form of size.(600,600) with one button of size.(450,150) that is set location(100,50) on the form. When clicked I want to move down it's own height, then add a new button in it's place. The code included below works as desired for the first two clicks, but on the third click the button keeps moving and the autoscroll bar extends. I initially thought it was the autoscroll function or the location property, but realised that as the button keeps moving, the timer hasn't stopped. I am aware that the code is probably very clunky in terms of achieving the outcome, and that there are a few lines/variables that are currently skipped over by the compiler (these are from older attempts to figure this out).
I have looked around and can't find the cause of my problem. Any help would be greatly appreciated. Apologies if the code block looks messy - first go.
Public Class frmOpenScreen
Dim intWButtons, intCreateButtonY, intCreateButtonX 'intTimerTick As Integer
Dim arrWNames() As String
Dim ctrlWButtons As Control
Dim blnAddingW As Boolean
Private Sub btnCreateW_Click(sender As System.Object, e As System.EventArgs) Handles btnCreateW.Click
'Creates new Button details including handler
Dim strWName, strWShort As String
Dim intCreateButtonY2 As Integer
Static intNumW As Integer
Dim B As New Button
strWName = InputBox("Please enter the name name of the button you are creating. Please ensure the spelling is correct.", "Create W")
If strWName = "" Then
MsgBox("Nothing Entered.")
Exit Sub
End If
strWShort = strWName.Replace(" ", "")
B.Text = strWName
B.Width = 400
B.Height = 150
B.Font = New System.Drawing.Font("Arial Narrow", 21.75)
B.AutoSizeMode = Windows.Forms.AutoSizeMode.GrowAndShrink
B.Anchor = AnchorStyles.Top
B.Margin = New Windows.Forms.Padding(0, 0, 0, 0)
'Updates Crucial Data (w name array, number of w buttons inc Create New)
If intNumW = 0 Then
ReDim arrWNames(0)
Else
intNumW = UBound(arrWNames) + 1
ReDim Preserve arrWNames(intNumW)
End If
arrWNames(intNumW) = strWShort
intNumW = intNumW + 1
intWButtons = WButtonCount(intWButtons) + 1
'updates form with new button and rearranges existing buttons
intCreateButtonY = btnCreateW.Location.Y
intCreateButtonX = btnCreateW.Location.X
‘intTimerTick = 0
tmrButtonMove.Enabled = True
‘Do While intTimerTick < 16
‘ 'blank to do nothing
‘Loop
'btnCreateW.Location = New Point(intCreateButtonX, intCreateButtonY + 150)
B.Location = New Point(intCreateButtonX, intCreateButtonY)
Me.Controls.Add(B)
B.Name = "btn" & strWShort
intCreateButtonY2 = btnCreateW.Location.Y
If intCreateButtonY2 > Me.Location.Y Then
Me.AutoScroll = False
Me.AutoScroll = True
Else
Me.AutoScroll = False
End If
'MsgBox(intCreateButtonY)
End Sub
Function WButtonCount(ByRef buttoncount As Integer) As Integer
buttoncount = intWButtons
If buttoncount = 0 Then
Return 1
End If
Return buttoncount
End Function
Public Sub tmrButtonMove_Tick(sender As System.Object, e As System.EventArgs) Handles tmrButtonMove.Tick
Dim intTimerTick As Integer
If intTimerTick > 14 Then
intTimerTick = 0
End If
If btnCreateW.Location.Y <= intCreateButtonY + 150 Then
btnCreateW.Top = btnCreateW.Top + 10
End If
intTimerTick += 1
If intTimerTick = 15 Then
tmrButtonMove.Enabled = False
End If
End Sub
End Class
So my current understanding is that the tick event handler should be increasing the timertick variable every time it fires, and that once it has hits 15 it should diable the timer and stop the button moving, but it is not doing so.
Thanks in advance.
IntTimerTick is initialized to 0 at the beginning of every Tick event. This won't happen if you declare it to be static:
Static Dim intTimerTick As Integer