Visual Basic Generate a Form - vb.net

I need to build a number of forms in Visual Basic, but doing it manually take a lot of time. As an experiment I wound like to find out if I could generate forms with a number of Parameters, but I can't find a way to Code a Form. For example how would I Declare and Initialize Buttons, Label, Text Boxes, etc. and code them into Flow Layout or Table Layout. Do I build it in a Class or Form.vb or Module?
Please let me know, if its is possible or not.

Here is an example of how to create controls dynamically in WinForms and add them to a container control. I also show you how to hook up an event handler. To test the code, create a new Form and add a panel to it called "Panel1". Then paste this code into the .vb file. You could add support for a lot more control types.
This extension method is useful, to make sure WinForms destroys the controls when you clear them from the container (needs to go into its own file)
Module ExtensionMethods
<Extension()>
Sub Clear(ByVal controls As Control.ControlCollection, ByVal dispose As Boolean)
For ix As Integer = controls.Count - 1 To 0
If dispose Then
controls(ix).Dispose()
Else
controls.RemoveAt(ix)
End If
Next
End Sub
End Module
This code shows how to create controls dynamically
''' <summary>
''' Function for creating a textbox and adding it to a control
''' </summary>
''' <param name="Container">The container control to add the textbox to</param>
''' <param name="Name">The Name (Id) of the TextBox (must be unique)</param>
''' <param name="LabelText">The text of the label to create to go with it</param>
''' <param name="Top">The Top (y) position of the TextBox</param>
''' <param name="Left">The Left (x) position of the TextBox</param>
''' <param name="Value">The value of the TextBox</param>
''' <returns></returns>
Private Function AddTextBox(ByRef Container As Control, Name As String, LabelText As String, Top As Integer, Left As Integer, Value As String) As TextBox
Dim tb As New TextBox With {.Name = Name, .Top = Top, .Left = Left, .Text = Value}
Dim lbl As New Label With {.Name = Name & "_lbl", .Top = Top, .Left = Left - 150, .Text = LabelText}
Container.Controls.Add(lbl)
Container.Controls.Add(tb)
Return tb
End Function
''' <summary>
''' Function for creating a button and adding it to a control
''' </summary>
''' <param name="Container">The container control to add the button to</param>
''' <param name="Name">The Name (Id) of the Button (must be unique)</param>
''' <param name="Text">The Text of the Button</param>
''' <param name="Top">The Top (y) position of the Button</param>
''' <param name="Left">The Left (x) position of the Button</param>
''' <returns></returns>
Private Function AddButton(ByRef Container As Control, Name As String, Text As String, Top As Integer, Left As Integer) As Button
Dim btn As New Button With {.Name = Name, .Text = Text, .Top = Top, .Left = Left, .Visible = True, .AutoSize = True}
Container.Controls.Add(btn)
Return btn
End Function
''' <summary>
''' A click handler for our Button
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
Private Sub button_Click(sender As Object, e As EventArgs)
Dim tb_Name As TextBox = Panel1.Controls.Find("tb_Name", False)(0)
Dim tb_EmailAddress As TextBox = Panel1.Controls.Find("tb_EmailAddress", False)(0)
MessageBox.Show("Name: " & tb_Name.Text & " Email Address: " & tb_EmailAddress.Text)
End Sub
''' <summary>
''' A sub for building our form
''' </summary>
Private Sub BuildForm()
' Clear existing controls
' This is only really needed in an ASP.NET solution where
' you are re-rendering the controls in the PreRender
' event because things have changed since the OnInit event.
' Although, if you need to change the form based on what
' was put into it (like a dynamic questionnaire) then this would
' also be applicable in a WinForms scenario.
Panel1.Controls.Clear(True)
' Create a "Name" textbox
AddTextBox(Panel1, "tb_Name", "Your Name", 10, 200, "")
' Create an "EmailAddress" textbox
AddTextBox(Panel1, "tb_EmailAddress", "Your EmailAddress", 40, 200, "")
' Create a button to Save Changes
Dim SaveButton As Button = AddButton(Panel1, "btn_Save", "Save Changes", 70, 200)
' Add a handler to the button click event
AddHandler SaveButton.Click, AddressOf button_Click
End Sub
''' <summary>
''' Build the form as soon as it's shown
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
Private Sub Form1_Shown(sender As Object, e As EventArgs) Handles Me.Shown
BuildForm()
End Sub

Related

Change the colour of some letters in a particular column in datagridview

I have a datagridview and a textbox. I want to do something like this.
If (textboxsearch.text.contains) any letter/character in (datagridview1. Columns (6).value.tostring) Then the colour of that particular latter/character in datagridview1. Columns (6) will turn into green.
I searched in internet but I failed. Help please. I am using vb.net 2019. Thanks.
I didn't expect you to get the whole way yourself but I did hope to see you put some effort into coming up with your own solution. I did some testing myself, using the link I provided in the comments as a starting point, and I came up with something that works. It's relatively complex so I figured that I'd just provide it as is, rather than waiting around to see how far you can get on your own.
Firstly, here's a useful type:
''' <summary>
''' Represents a section of a <see cref="String"/> that can be highlighted.
''' </summary>
Public Structure HighlightableSubstring
''' <summary>
''' The index at which the substring starts.
''' </summary>
''' <returns>
''' An <see cref="Int32"/> that represents the start index of the substring.
''' </returns>
Public ReadOnly Property StartIndex As Integer
''' <summary>
''' The number of characters in the substring.
''' </summary>
''' <returns>
''' An <see cref="Int32"/> that represents the length of the substring.
''' </returns>
Public ReadOnly Property Length As Integer
''' <summary>
''' Indicates whether or not the substring is highlighted.
''' </summary>
''' <returns>
''' <b>True</b> if the substring is highlighted; otherwise, <b>False</b>.
''' </returns>
Public ReadOnly Property IsHighlighted As Boolean
''' <summary>
''' Creates a new instance of the <see cref="HighlightableSubstring"/> class.
''' </summary>
''' <param name="startIndex">
''' The index at which the substring starts.
''' </param>
''' <param name="length">
''' The number of characters in the substring.
''' </param>
''' <param name="isHighlighted">
''' Indicates whether or not the substring is highlighted.
''' </param>
Public Sub New(startIndex As Integer, length As Integer, isHighlighted As Boolean)
Me.StartIndex = startIndex
Me.Length = length
Me.IsHighlighted = isHighlighted
End Sub
End Structure
Here's the method that makes use of that type and does the drawing:
''' <summary>
''' Draws text with instances of a specific substring highlighted.
''' </summary>
''' <param name="g">
''' The object with which to draw the text.
''' </param>
''' <param name="text">
''' The text to draw.
''' </param>
''' <param name="highlightText">
''' The substring to highlight in the drawn text.
''' </param>
''' <param name="defaultColour">
''' The default colour in which to draw the text.
''' </param>
''' <param name="highlightColour">
''' The colour in which to draw the highlighted sections of the text.
''' </param>
''' <param name="font">
''' The font in which to draw the text.
''' </param>
''' <param name="location">
''' The location of the top-left corner of the bounds within which to draw the text.
''' </param>
Private Sub DrawTextWithHighlights(g As Graphics,
text As String,
highlightText As String,
defaultColour As Color,
highlightColour As Color,
font As Font,
location As PointF)
If String.IsNullOrWhiteSpace(text) Then
Return
End If
Dim textLength = text.Length
Dim highlightTextLength = highlightText.Length
'The sections of the text that are highlighted and not highlighted.
Dim sections As New List(Of HighlightableSubstring)
'The index at which to start searching for the highlight text.
Dim startIndex = 0
If Not String.IsNullOrWhiteSpace(highlightText) Then
'Find the first instance of the highlight text.
Dim highlightIndex = text.IndexOf(highlightText)
'Keep searching until no more instances of the highlight text can be found.
Do Until highlightIndex = -1
'Check whether there is text before the found instance of the highlight text.
If highlightIndex > startIndex Then
'Add a section for the non-highlighted text.
sections.Add(New HighlightableSubstring(startIndex, highlightIndex - startIndex, False))
End If
'Add a section for the highlighted text.
sections.Add(New HighlightableSubstring(highlightIndex, highlightTextLength, True))
'Find the next instance of the highlight text.
startIndex = highlightIndex + highlightTextLength
highlightIndex = text.IndexOf(highlightText, startIndex)
Loop
End If
'Check whether there is text after the last instance of the highlight text.
If startIndex < textLength Then
'Add a section for the non-highlighted text.
sections.Add(New HighlightableSubstring(startIndex, textLength - startIndex, False))
End If
Dim format As New StringFormat
'Set a range for each section of the text.
format.SetMeasurableCharacterRanges(sections.Select(Function(hs) New CharacterRange(hs.StartIndex, hs.Length)).ToArray())
'Get the box that the text would normally occupy.
Dim layoutRect As New RectangleF(location, g.MeasureString(text, font))
'Get the regions occupied by the sections of the text.
Dim regions = g.MeasureCharacterRanges(text, font, layoutRect, format)
'Create brushes for the specified colours.
Using defaultBrush As New SolidBrush(defaultColour),
highlightBrush As New SolidBrush(highlightColour)
For i = 0 To regions.GetUpperBound(0)
'Get the current section.
Dim section = sections(i)
'Get the bounds for the current section.
Dim bounds = regions(i).GetBounds(g)
'Draw the current section of the text using the appropriate colour.
g.DrawString(text.Substring(section.StartIndex, section.Length),
font,
If(section.IsHighlighted,
highlightBrush,
defaultBrush),
bounds.X,
bounds.Y)
Next
End Using
End Sub
Here's how I initially tested that code, without a DataGridView:
Private Sub Form1_Paint(sender As Object, e As PaintEventArgs) Handles Me.Paint
e.Graphics.DrawString("highlight", Font, Brushes.Black, 100, 50)
DrawTextWithHighlights(e.Graphics, "highlight", "ig", Color.Black, Color.Red, Font, New PointF(100, 70))
e.Graphics.DrawString("abcdababefab", Font, Brushes.Black, 100, 150)
DrawTextWithHighlights(e.Graphics, "abcdababefab", "ab", Color.Black, Color.Red, Font, New PointF(100, 170))
End Sub
I used the second text to test how the code behaved when the highlight text was found at the beginning and end of the text and when two instances were found together and it worked as expected. If you run that code then you'll see that there's a slight offset between the horizontal position of the text drawn with a single call to DrawString and that containing the highlighting. I don't think that it's enough to be a problem but you can address it if you want to.
To use that method with a DataGridView, I did this:
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
DataGridView1.Refresh()
End Sub
Private Sub DataGridView1_CellPainting(sender As Object, e As DataGridViewCellPaintingEventArgs) Handles DataGridView1.CellPainting
If e.ColumnIndex >= 0 AndAlso e.RowIndex >= 0 Then
'Draw all the required parts of the cell except the text.
e.Paint(e.ClipBounds, e.PaintParts And Not DataGridViewPaintParts.ContentForeground)
'Draw the text.
DrawTextWithHighlights(e.Graphics,
e.FormattedValue?.ToString(),
TextBox1.Text,
DataGridView1.ForeColor,
Color.Red,
DataGridView1.Font,
e.CellBounds.Location)
e.Handled = True
End If
End Sub
In my testing, that worked to properly highlight the text when making changes in the grid or in the TextBox. The one issue with that is where the text gets drawn in the cell. I'll leave it to you to figure out that detail.

How to use extender provider in vb.net

I have this code I want to use it in my form
how to do it?
Imports System.ComponentModel
'...
<ProvideProperty("NullableTextBox", typeof(TextBox) Is )>
Partial Public Class NullableTextBox
Inherits Component
Implements IExtenderProvider
Dim _nullables As Dictionary(Of Control, Boolean) = New Dictionary(Of Control, Boolean)
''' <summary>
''' This is the get part of the extender property.
''' It is actually a method because it takes the control.
''' </summary>
''' <param name="control"></param>
<DefaultValue(False), _
Category("Data")> _
Public Function GetNullableBinding(ByVal control As Control) As Boolean
Dim nullableBinding As Boolean = False
_nullables.TryGetValue(control, nullableBinding)
Return nullableBinding
End Function
''' <summary>
''' This is the set part of the extender property.
''' It is actually a method because it takes the control.
''' </summary>
''' <param name="control"></param>
''' <param name="nullable"></param>
Public Sub SetNullableBinding(ByVal control As Control, ByVal nullable As Boolean)
If _nullables.ContainsKey(control) Then
_nullables(control) = nullable
Else
_nullables.Add(control, nullable)
End If
If nullable Then
' Add a parse event handler.
AddHandler control.DataBindings("Text").Parse, AddressOf Me.NullableExtender_Parse
End If
End Sub
''' <summary>
''' When parsing, set the value to null if the value is empty.
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
Private Sub NullableExtender_Parse(ByVal sender As Object, ByVal e As ConvertEventArgs)
If (e.Value.ToString.Length = 0) Then
e.Value = Nothing
End If
End Sub
End Class

Adding a progress bar to show how much percentage of form had been loaded

I've a form having certain lines of code on the form_load event and thus it takes some time to be shown. I want to add a progress bar to show how much percentage of form has been loaded. How can I do so ..?
In short:- Like while browsing the web pages the progress as shown in web browser indicate the value of page has been loaded. I want to do so in vb.net.
How can I do so .?
You'll need to move your long running code into the form's .Shown event handler.
I would suggest adding a StatusStrip to your form and add a ToolStripProgressBar to that. I did this in a program I wrote and used the following bit of code work on it.
It's all pretty self explanatory :-)
''' <summary>
''' Sets minimum and maximum values for ToolStripProgressBar and shows it
''' </summary>
''' <param name="min">Minimum Value</param>
''' <param name="max">Maximum Value</param>
''' <param name="labeltext">Text to show in ToolStripLabel</param>
Private Sub SetAndShowProgressBar(min As Integer, max As Integer, labeltext As String)
ToolStripStatusLabel1.Text = labeltext
ToolStripProgressBar1.Minimum = min
ToolStripProgressBar1.Maximum = max + 5
ToolStripProgressBar1.Value = 1
ToolStripProgressBar1.Visible = True
StatusStrip1.Update()
End Sub
''' <summary>
''' Hides ToolStripProgressBar
''' </summary>
Private Sub HideProgressBar()
ToolStripStatusLabel1.Text = ""
ToolStripProgressBar1.Visible = False
StatusStrip1.Update()
End Sub
Private Delegate Sub incprogressbarDelegate()
Private Sub IncrementProgressBar()
If Me.InvokeRequired Then
Dim d As New incprogressbarDelegate(AddressOf IncrementProgressBar)
Me.Invoke(d, New Object())
Else
Me.ToolStripProgressBar1.Value += 1
StatusStrip1.Update()
End If
End Sub
Private Delegate Sub SetProgressBarDelegate(i As Integer)
Private Sub SetProgressBarValue(i As Integer)
If Me.InvokeRequired Then
Dim d As New SetProgressBarDelegate(AddressOf SetProgressBarValue)
Me.Invoke(d, New Object() {i})
Else
Me.ToolStripProgressBar1.Value = i
End If
End Sub

XNA - How to open a new window?

How do I open a win forum in XNA?
My code:
''' <summary>
''' This is the main type for your game
''' </summary>
Public Class Game1
Inherits Microsoft.Xna.Framework.Game
Private ATO_Main As New ATO_Main
Private WithEvents graphics As GraphicsDeviceManager
Private WithEvents spriteBatch As SpriteBatch
Public Sub New()
graphics = New GraphicsDeviceManager(Me)
Content.RootDirectory = "Content"
End Sub
''' <summary>
''' Allows the game to perform any initialization it needs to before starting to run.
''' This is where it can query for any required services and load any non-graphic
''' related content. Calling MyBase.Initialize will enumerate through any components
''' and initialize them as well.
''' </summary>
Protected Overrides Sub Initialize()
' TODO: Add your initialization logic here
MyBase.Initialize()
graphics.PreferredBackBufferHeight = 1024
graphics.PreferredBackBufferWidth = 768
graphics.ApplyChanges()
graphics.PreferredBackBufferWidth = GraphicsDevice.DisplayMode.Width
graphics.PreferredBackBufferHeight = GraphicsDevice.DisplayMode.Height
graphics.IsFullScreen = True
graphics.ApplyChanges()
End Sub
''' <summary>
''' LoadContent will be called once per game and is the place to load
''' all of your content.
''' </summary>
Protected Overrides Sub LoadContent()
' Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = New SpriteBatch(GraphicsDevice)
' TODO: use Me.Content to load your game content here
ATO_Main.Show()
ATO_Main.BringToFront()
End Sub
''' <summary>
''' UnloadContent will be called once per game and is the place to unload
''' all content.
''' </summary>
Protected Overrides Sub UnloadContent()
' TODO: Unload any non ContentManager content here
End Sub
''' <summary>
''' Allows the game to run logic such as updating the world,
''' checking for collisions, gathering input, and playing audio.
''' </summary>
''' <param name="gameTime">Provides a snapshot of timing values.</param>
Protected Overrides Sub Update(ByVal gameTime As GameTime)
' Allows the game to exit
If GamePad.GetState(PlayerIndex.One).Buttons.Back = ButtonState.Pressed Then
Me.Exit()
End If
' TODO: Add your update logic here
MyBase.Update(gameTime)
End Sub
''' <summary>
''' This is called when the game should draw itself.
''' </summary>
''' <param name="gameTime">Provides a snapshot of timing values.</param>
Protected Overrides Sub Draw(ByVal gameTime As GameTime)
GraphicsDevice.Clear(Color.CornflowerBlue)
' TODO: Add your drawing code here
MyBase.Draw(gameTime)
End Sub
End Class
Figured it out I need this:
ATO_Main = New ATO_Main
ATO_Main.ShowDialog()

How do I convert a two-dim array to a one-dim?

the problem is that I first have to convert the two-dim to a one-dim, then find the selected index and then convert again and then save the new index. after that I have to use the right string.format to show the right output.. I'm just confused =(
In the program there are two text boxes that ask for "row" and "col" size and then you press the button and a list box shows
...............................................................................................................................
Row...Col.......................................................................................................................................
1------1----Vacant ........................................................................
1......2.......Vacant...................................................................................................
1......3.......Vacant....................................................................................................................................
2------1----Vacant.........................................................................................................................
2......2.......Vacant....................................................................................................................................
2......3.......Vacant..........................................................................................................................................................
3------1----Vacant....................................................................................................................................
etc.............................................................................................................................................................
and when I double click one line it has to say "Reserved"
Can someone help me what to do this please?
This is my project folder so far here you can see my failed code and this is my assignment
This is how the program is supposed to look like in the end
'Created by: Hans Elias Juneby
'Started: July 10, 2010 Completed July 0, 2010
Public Class MainFrame
'''<summary>
''' Enum used for choices of showing results
''' </summary>
'''<remarks></remarks>
Private Enum UpdateOptions
ShowAllSeats 'reserved and vacant seats
ShowOnlyVacantSeats 'Only vacant seats
ShowOnlyReservedSeats 'Only reserved seats
End Enum
'Instance variables
Private bookingObj As SeatBooking = New SeatBooking()
Private showOptions As UpdateOptions = UpdateOptions.ShowAllSeats
'''<summary>
''' Default constructor
''' Initialize components and do other preparations.
''' This method is called automatically before the form is made visible
''' </summary>
''' <remarks></remarks>
Public Sub New()
' This call is required by the Windows Form Designer.
InitializeComponent()
' My initialization
InitializeControlvalues()
UpdateResults()
End Sub
'''<summary>
''' Organize initiations
''' Fill comboboxes with options (strings), set default values, etc
''' </summary>
'''<remarks></remarks>
Private Sub InitializeControlvalues()
FillUnitTypeList()
lstUnits.SelectedIndex = -1
cmbShowOptions.Items.AddRange([Enum].GetNames(GetType(UpdateOptions)))
cmbShowOptions.SelectedIndex = 0
rbtnLetters.Checked = True
' txtNumOfSeats.Text = bookingObj.GetMaxCols.ToString() 'default values
' txtNumOfRows.Text = bookingObj.GetMaxRows.ToString() 'default values
lblNumVacants.Text = String.Empty 'default values
lblTotal.Text = String.Empty 'default values
lblPercent.Text = String.Empty 'default values
End Sub
''' <summary>
''' Clear listbox, format new strings with the help of the bookingObj and
'''fill in the box.
''' </summary>
''' <remarks></remarks>
Private Sub UpdateResults()
End Sub
'''<summary>
''' Helper function that returns a string containing a string "** Reserved **" or
'''"Vacant" or no text according the value in showOptions. THe UpdateResults
''' calls this function in detecting which string to show in the listbox
''' </summary>
''' <param name="row">Input</param>
''' <param name="col">Input</param>
''' <returns>A formatted string as explained above</returns>
'''<remarks></remarks>
Private Function GetReservationStatusString()
Select Case (cmbShowOptions.SelectedIndex)
Case 0
Case 1
Case 2
End Select
End Function
'Fills values in the combobox
Private Sub FillUnitTypeList()
Dim units As String() = {"Bus Seats", "Train Seats", "Plane Seats"}
cmbUnitType.Items.AddRange(units)
cmbUnitType.SelectedIndex = 0
End Sub
Private Sub cmbShowOptions_SelectedIndexChange(ByVal sender As System.Object, ByVal e As System.GC)
showOptions = DirectCast(cmbShowOptions.SelectedIndex, UpdateOptions)
UpdateResults()
End Sub
Private Sub btnMatrix_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnMatrix.Click
Dim SeatBooking As New SeatBooking
bookingObj.GetMaxRows.ToString()
bookingObj.GetMaxCols.ToString()
lblTotal.Text = txtNumOfRows.Text * txtNumOfSeats.Text
End Sub
''' <summary>
''' Event-handler for the double-click event.
''' Reserve/cancel the seat chosen in the listbox (call bookingObj.SetRowAndCOlumnValue),
''' only if the showOption is Show ALL; otherwise, give an error message and do nothing.
''' </summary>
''' <param name="sender">sender-object from the caller</param>
''' <param name="e">EventArgs object from the caller</param>
''' <remarks></remarks>
Private Sub lstUnits_DoubleClick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lstUnits.DoubleClick
lblNumVacants.Text = lblTotal.Text - 1
Return
End Sub
''' <summary>
''' Event-handler method for change in the radiobutton
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
''' <remarks></remarks>
Private Sub rbtnLetters_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rbtnLetters.CheckedChanged
UpdateResults()
Dim A As Integer = 65
Dim myChar As Char
Dim col As Integer = 0
myChar = Convert.ToChar((A + col))
End Sub
Private Sub UpdateUnit()
'Dim strText As String = bookingObj.GetUnitName(cmbUnitType.SelectedIndex)
' lblVacantUnits.Text
End Sub
End Class
then the SeatBook class:
'Created by: Hans Elias Juneby
'Started: July 10, 2010 Completed July 0, 2010
Public Class SeatBooking
Private array As Double() 'Declaration of the array
Private lastIndex As Integer = 0 'last filled position (lastIndex+1 = number of items
'''<summary>
''' Create (or recreate) the matrix with the given size
''' </summary>
'''<param name="rowSize">Number of rows</param>
''' <param name="colSize">Number of columns</param>
'''<remarks></remarks>
Public Sub CreateArray(ByVal rowSize As Integer, ByVal colSize As Integer)
Debug.Assert(rowSize >= 0) 'Program execution halts here in case size is <0;
array = New Double(rowSize - 1) {}
Debug.Assert(colSize >= 0) 'Program execution halts here in case size is <0;
array = New Double(colSize - 1) {}
Dim seatMatrix As Boolean(,)
seatMatrix = New Boolean(rowSize, colSize) {}
End Sub
'''<summary>
''' Calculate the total number of elements(row*col)
''' </summary>
'''<returns>The total number of elements</returns>
'''<remarks></remarks>
Public Function GetMaxCount() As Integer
End Function
'''<summary>
''' Check if a seat in a specific row and column is reserved.
''' </summary>
'''<param name="row">given row</param>
'''<param name="col">given col</param>
'''<returns>True if the seat is reserved and false otherwise</returns>
'''<remarks></remarks>
Public Function IsReserved(ByVal row As Integer, ByVal col As Integer)
End Function
'''<summary>
''' Make a new reservation or cancel an existing. This process is onde by
''' reversing the boolean value in the given position in the matrix, from true to
''' false (reverse the seat) or vice versa(Cancel the reservation)
''' </summary>
'''<param name="row">given row</param>
'''<param name="col">given col</param>
'''<remarks></remarks>
Public Sub Reserve(ByVal row As Integer, ByVal col As Integer)
End Sub
'''<summary>
''' Thenumber of rows in the Matrix
''' </summary>
''' <returns>The number of rows</returns>
''' <remarks></remarks>
Public Function GetMaxRows() As Integer
Dim colsize As Integer = MainFrame.txtNumOfSeats.Text
Dim rowsize As Integer = MainFrame.txtNumOfRows.Text
CreateArray(colsize, rowsize)
For i As Integer = 0 To array.Length - 1
MainFrame.lstUnits.Items.Add("----" & i & "---" & GetMaxCols.ToString.Length)
Next
End Function
'''<summary>
''' Thenumber of columns in the Matrix
''' </summary>
''' <returns>The number of columns</returns>
''' <remarks></remarks>
Public Function GetMaxCols() As Integer
Dim colsize As Integer = MainFrame.txtNumOfSeats.Text
Dim rowsize As Integer = MainFrame.txtNumOfRows.Text
CreateArray(rowsize, colsize)
For h As Integer = 0 To array.Length - 1
Next
End Function
'''<summary>
''' The method first finds the first vacant pos in the matrix (row, col)
''' and then calls another method MatrixIndexToVectorialIndex that determines which
''' position the element has if the matrix was rolled out into a one-dimensional
''' array. In a 3x3 matrix, the element in position (1,1) has an index 4 in
''' one-dimensional array. The method is useful when updating the listbox in the
''' GUI which contains a one-dimensional array of strings. The method determines which
''' position (row,col) in the matrix corresponds to an item (row) in the listbox.
''' </summary>
'''<returns>The index, considering the matrix as one long vector, to the first vacant
''' position ( the first False value). A value -1 is returned if no vacant element is
''' found</returns>
'''<remarks></remarks>
Public Function GetFirstVacantPosition() As Integer
End Function
''' <summary>
''' Determine a corresponding index for an element at (row,col) in a one-dimensional
''' presentation of the matrix. Think of the matrix as beeing rolled out into a one-dim
''' array. In a 3x3 matrix, the element in position (1,1) has an index 4 in
''' one-dimensional array.
''' 20 11 22
''' 33 41 55
''' 60 7 99 Consider value (1,1)=41
''' The above matrix can now be represented as one dimensional array. This makes it
''' easier to update the listbox in the GUI.
''' 20 11 22 33 41 55 60 7 99 value(4)=41
''' Index 0 1 2 3 4 5 6 7 8
'''Hence, index (1,1) in the matrix corresponds to row 4 in the listbox (one-dim array)
''' </summary>
''' <param name="row"></param>
''' <param name="col"></param>
''' <returns>The new index as explained above</returns>
''' <remarks></remarks>
Public Function MatrixIndexToVectorIndex(ByVal row As Integer, ByVal col As Integer)
End Function
''' <summary>
''' Determines the index in the matrix (row,col) that corresponds to a given
''' index in a one-dim array (listbox). This method actually is reverse process of
''' the method MatrixIndexToVectorIndex (see above). The parameter row contains
''' the input, i.e. index of the element in a one-dim array. The results (row and col)
''' are saved and sent back to the caller via the ref variables row,col.
''' </summary>
''' <param name="row">Input and output parameter</param>
''' <param name="col">Output parameter</param>
''' <remarks></remarks>
Public Sub VectorIndexToMatrixIndex(ByRef row As Integer, ByRef col As Integer)
End Sub
''' <summary>
''' This function receives an index in a one-dim array (e.g. listbox) and calls
''' the method VectorIndexToMatrixIndex to fin the same position in the matrix.
''' It then calls the function Reserve to either reserve or cancel a booking.
''' (If False value is saved in the element, it reserves the seat by changing
''' the value to True, and vice-versa).
''' </summary>
''' <param name="oneDimListIndex"></param>
''' <remarks></remarks>
Public Sub SetRowAndColumnValue(ByVal oneDimListIndex As Integer)
End Sub
''' <summary>
''' Calculate the total number of the reserved seats, i.e. the total
''' number of the True values in the matrix.
''' </summary>
''' <returns>Number of reserved seats</returns>
''' <remarks></remarks>
Public Function GetNumOfReservedSeats() As Integer
End Function
''' <summary>
''' Calculate the total number of the vacant seats, i.e the total
''' number of the False values in the matrix.
''' </summary>
''' <returns>number of vacant seats</returns>
''' <remarks></remarks>
Public Function GetNumOfVacantSeats() As Integer
End Function
''' <summary>
''' Relation between the reserved seats and the total number of seats in percent.
''' </summary>
''' <returns>Percent of Reservation</returns>
''' <remarks></remarks>
Public Function PercentOfReservation() As Double
End Function
End Class
Personally I would rather use a hash table for this task [personal preference for speed] but as you need to either use a two-dimensional array or matrix according to your project specs it may be easier to accomplish this by using a 2-dimensional array of type Boolean
Dim ReservationArray(NumRows - 1, NumColumns - 1) as Boolean
These values will default to false indicating that seat is vacant and to reserve the seat all you do is change this value to true
I've done basically the same project a while back for a course I was studying at the time you're welcome to look through the coding and modify it as suits your needs
You can download my project from the link below (Visual Studio 2008 Project)
A big difference between our projects is the use of a datagridview instead of a listbox :) have a look at how this simplifies your task
Reservation_Project.zip