How to do this effect in VB? It works in Python - vb.net

how can i fix this problem, in line with ">>" , in python it works, how does it work in vb
Public Class frmCafeOrder
Public ingredients = {{"Apple", 10.0},
{"Lettuce", 12.5},
{"Tomato", 8.5},
{"Ham", 20.0},
{"Tuna", 18.5},
{"Grain Wheet", 8.0},
{"Honey Oat", 10.5}}
Public priceControls = {{chkApple, lblApplePrice},
{chkLettuce, lblLettucePrice},
{chkTomato, lblTomatoPrice},
{chkHam, lblHamPrice},
{chkTuna, lblTunaPrice},
{rbGrainWheet, lblGrainWheetPrice},
{rbHoneyOat, lblHoneyOatPrice}}
Private Sub frmCafeOrder_Load(sender As Object, e As EventArgs) Handles MyBase.Load
init()
For i As Integer = 0 To ingredients.GetLength(0)
Dim ingredient = ingredients(i, 0)
>>Dim controls = priceControls(i)
Dim price = ingredients(i, 1)
>>priceControls = controls(i)
>>priceControls = String.Format("HK$ {0}", price)
Next
End Sub
End Class

First, you are trying to use a 2D array without specifying the other dimension.
You specify these perfectly:
Dim ingredient = ingredients(i, 0)
Dim price = ingredients(i, 1)
but are failing to do that with this:
Dim controls = priceControls(i) 'notice it's missing the second dimension
Secondly.... this... whatever this is...
Dim controls = priceControls(i)
priceControls = controls(i)
You are setting controls to priceControls and then trying to set it to itself, but with an added (i), where on earth did the (i) in controls come from?
and then for a little added confusion.
priceControls = controls(i)
priceControls = String.Format("HK$ {0}", price)
why set it to one thing when you are just going to set it to another?
What I am guessing you are trying to do is this:
Go through the list of ingredients in Ingredients()
Populate the right lbl.text field with the corresponding price
For i As Integer = 0 To ingredients.GetLength(0)
Dim ingredient as String = ingredients(i, 0)
Dim price as String = ingredients(i, 1)
Dim lbl as Label = DirectCast(priceControls(i, 1), Label)
lbl.text = String.Format("HK$ {0}", price)
Next
You haven't really specified the problem directly or what you are looking to do, so this is really just my guess at both.

Related

Read data from dynamically created text-box

I'm trying to collect data after creating dynamic text-box with vb.net
Private Sub btn_OK_lines_number_Click(sender As Object, e As EventArgs)
Handles btn_OK_lines_number.Click
Dim i As Integer
Dim x As Integer
Dim Z As Integer
Z = 150
If IsNumeric(txt_lines_number.Text) Then
Int32.TryParse(txt_lines_number.Text, x)
For i = 1 To x
Dim newTB As New TextBox
Dim newLB As New Label
newLB.Name = "lbl_workstation_number_line" & i
newLB.Text = "Nbr Work Station in Line" & i
newLB.Size = New Size(190, 20)
newLB.ForeColor = Color.White
newLB.Font = New Font("consolas", 12, FontStyle.Regular, GraphicsUnit.Pixel)
newLB.Location = New Point(20, Z + i * 30)
newTB.Name = "Textbox" & i
newTB.Size = New Size(170, 20)
newTB.Location = New Point(200, Z + i * 30)
Me.Controls.Add(newTB)
Me.Controls.Add(newLB)
Next
i = i + 1
Else
MessageBox.Show("please enter a number")
txt_lines_number.Text = ""
End If
End Sub
Let's say you just have one row, and only create one TextBox. You set the name here:
newTB.Name = "Textbox" & i
where the resulting TextBox is named Textbox1. The problem is you can't just reference the identifier Textbox1 directly in your code, as you do with txt_lines_number. You can't even reference it as a member of the class (Me.Textbox1). This name didn't exist at compile time, and so it's not an identifier you can use, and it's not a member of the class at all. There was never a matching Dim statement for that name.
What you can do, though, is look again in the Controls collection where you added the TextBox to the form:
Me.Controls("Textbox1")
or
Me.Controls("Textbox1").Text
You may also need to cast the value to a TextBox:
Dim box As TextBox = DirectCast(Me.Controls("Textbox1"), TextBox)
MessageBox.Show(box.Text)
Remember that case matters here.
Further saving this in a DB is out of scope for one question. There are as many ways to do that as there are programmers in the world. You should make your own attempt first, and come back here with a new question when you run into specific problems.
Thank you,
this is my attempt and it is done !
Dim userInput As TextBox = Form1.Controls.Item("TextBox" & i.ToString)
mycommand.Parameters.AddWithValue("#workstation", userInput.Text)
:D
Because you creating dynamic amount of input controls, right tool for the job will be DataGridView control.
Create a class to represent your data
Public Class LineInfo
Public Property Number As Integer
Public Property WorkStationNumber As Integer
End Class
Create `DataGridView in the form designer.
Private Sub btn_OK_lines_number_Click(sender As Object, e As EventArgs) Handles btn_OK_lines_number.Click
Dim linesAmount As Integer
If Integer.TryParse(txt_lines_number.Text, linesAmount) = False Then
MessageBox.Show("please enter a number")
txt_lines_number.Text = ""
Exit Sub
End If
' Create class instance for every line
Dim lines =
Enumerable.Range(1, linesAmount)
.Select(Function(i) New LineInfo With { .Number = i })
.ToList()
'Set lines as DataSource to the DataGridView
Me.DataGridView1.DataSource = lines
End Sub
DataGridView will display all lines and provide input fields to update work station numbers.
You can access updated lines later by casting DataSource back to the List
Dim lines = DirectCast(Me.DataGridView1.DataSource, List(Of LineInfo))
' Now you can access all data and save it to the database
Dim parameters =
lines.Select(Function(line)
Return new SqlParameter With
{
.ParameterName = $"#workstation{line.Number}",
.SqlDbType = SqlDbType.Int,
.Value = line.WorkStationNumber
}
End Function)
.ToList()
myCommand.Parameters.AddRange(parameters)
You can freely change style, font colors of different columns in the datagridview.

Null Exception while loading my file to listbox.

I have a problem. I'm trying to load data to listbox , but when I click start I get an unhandled exception that states values cannot be null. I've bolded where the issue is.
I'm trying to create a library database, and would really appreciate if someone could help me fix this issue. Thanks!
Public Class frmLibrary
Structure BookData
Dim Title As String
Dim Author As String
Dim ISBN As Integer
Dim YearPublished As Integer
End Structure
Dim bookinfo() As BookData 'Array
Private Sub frmLibrary_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim bookfiles() As String = IO.File.ReadAllLines("LibraryDatabase.txt")
Dim n As Integer = bookfiles.Count - 1
ReDim bookinfo(n)
Dim line As String
Dim books() As String 'books are the parts
'use the split methods to assign values to the members of the structure variable.
For i As Integer = 0 To n ---**>Why is this value null???????**
line = bookfiles(i)
books = line.Split(","c) '
bookinfo(i).Title = books(0)
bookinfo(i).Author = books(1)
bookinfo(i).ISBN = books(2)
bookinfo(i).YearPublished = books(3)
Next
Dim query = From book In bookinfo
Select book.Title, book.Author, book.ISBN, book.YearPublished
DGVBookInfo.DataSource = query.ToList
DGVBookInfo.Columns("Title").HeaderText = "Title"
DGVBookInfo.Columns("Author").HeaderText = "Author"
DGVBookInfo.Columns("ISBN").HeaderText = "ISBN"
DGVBookInfo.Columns("Year Published").HeaderText = "Year Published"
DGVBookInfo.AutoResizeColumns()
DGVBookInfo.RowHeadersVisible = False
End Sub

Problems with generating labels

The Problem: I'm programmatically generating labels but am having trouble referencing them in code because they don't exist at runtime.
The Context: For a game, I've generated a 10x10 grid of labels with the following:
Public lbl As Label()
Dim tilefont As New Font("Sans Serif", 8, FontStyle.Regular)
Private Sub Lucror_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim i As Integer = 0
Dim a As Integer = 0
Dim height As Integer
Dim width As Integer
height = 30
width = 30
ReDim lbl(99)
For i = 0 To 99
lbl(i) = New Label
lbl(i).Name = i
lbl(i).Size = New System.Drawing.Size(30, 30)
lbl(i).Location = New System.Drawing.Point((width), height)
lbl(i).Text = i
lbl(i).Font = tilefont
Me.Controls.Add(lbl(i))
width = width + 30
a = a + 1 'starting new line if required
If (a = 10) Then
height = height + 30
width = 30
a = 0
End If
Next
End Subenter code here
This worked fine but the labels function as tiles in the game and game tiles need to store 2-3 integers each as well as be able to be referenced through event handlers. I figured a possible way to store integers would be to generate 100 arrays, each named after a label and each holding the 2-3 integers, but that seems very redundant.
What I need:
On click and on hover event handlers for every label
An array (or dictionary?) to store 2-3 integers for every label
Labels have to reference each others names ie. do something to label with name (your name + 1).
The Question: Is there a simple way to achieve these three things with the current way I generate labels (and if so, how?) and if not, how else can I generate the 100 labels to make achieving these things possible?
Any help is much appreciated.
Your labels do exist at runtime, but not at compile time. Attaching events is a little different at runtime, you must use AddHandler.
Below is some sample code that should illustrate everything you're asking for. I've introduced inheritance as a way of saving data that is pertinent to each tile. The GameTile type behaves exactly as a label, and we've added some functionality for storing integers and naming the control.
Public Class Form1
Dim tilefont As New Font("Sans Serif", 8, FontStyle.Regular)
Public Property GameTiles As List(Of GameTile)
Private Sub Lucror_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim a As Integer = 0
Dim xPosition As Integer = 30
Dim yPosition As Integer = 30
GameTiles = New List(Of GameTile)
For i = 0 To 99
Dim gt As New GameTile(i.ToString)
gt.Size = New System.Drawing.Size(30, 30)
gt.Location = New System.Drawing.Point((yPosition), xPosition)
gt.Font = tilefont
gt.Integer1 = i + 1000
gt.Integer2 = i + 2000
gt.Integer3 = i + 3000
Me.Controls.Add(gt)
AddHandler gt.Click, AddressOf TileClickHandler
GameTiles.Add(gt)
yPosition = yPosition + 30
a = a + 1 'starting new line if required
If (a = 10) Then
xPosition = xPosition + 30
yPosition = 30
a = 0
End If
Next
End Sub
Private Sub TileClickHandler(sender As Object, e As EventArgs)
Dim gt = CType(sender, GameTile)
MsgBox("This tile was clicked: " & gt.Text &
Environment.NewLine & gt.Integer1 &
Environment.NewLine & gt.Integer2 &
Environment.NewLine & gt.Integer3)
End Sub
End Class
Public Class GameTile
Inherits Label
'this class should be in a separate file, but it's all together for the sake of clarity
Public Property Integer1 As Integer
Public Property Integer2 As Integer
Public Property Integer3 As Integer
Public Sub New(NameText As String)
MyBase.New()
Name = NameText
Text = NameText
End Sub
End Class

'AddRange' is not a member of... (while i attempt to save column order of a DataGridView

I'm trying to save and load the data grid view column order.
I'm using this code that i suppose is also right.
Private Sub SaveColumnOrder()
Dim upperBound As Integer = Me.DataTable1DataGridView.ColumnCount - 1
Dim columnIndexes(upperBound) As String
For index As Integer = 0 To upperBound
Dim column As DataGridViewColumn = Me.DataTable1DataGridView.Columns(index)
columnIndexes(column.DisplayIndex) = index.ToString()
Next
My.Settings.GridColumnIndexes = New StringCollection
My.Settings.GridColumnIndexes.AddRange(columnIndexes)
End Sub
Private Sub LoadColumnOrder()
Dim columnIndexes As StringCollection = My.Settings.GridColumnIndexes
For displayIndex As Integer = 0 To columnIndexes.Count - 1
Dim index As Integer = CInt(columnIndexes(displayIndex))
Me.DataTable1DataGridView.Columns(index).DisplayIndex = displayIndex
Next
End Sub
Problem is that i don't know how to set the GridColumnIndexes inside project property settings.
I set to string and other "data" options but i always get the error: 'AddRange' is not a member of... {option selected}
Which is the right option in settings to make it finally work? Thank you :)

Send text from textboxes to datagrid

I have for textboxes on my form and I would like the text there to be send to a datagrid. I wrote the following:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim itemName As String = txtItem.Text
Dim qty As Double = CDbl(txtQTY.Text)
Dim price As Double = CDbl(txtPrice.Text)
Dim Total As Double = price * qty
txtTotal.Text = Convert.ToString(Total)
Dim row As Integer = grdNewInvoice.Rows.Count
Dim data As TextBox() = New TextBox() {txtItem, txtQTY, txtPrice, txtTotal}
grdNewInvoice.Rows.Add()
For i As Integer = 0 To data.Length - 1
grdNewInvoice(i, row).Value = data(0)
Next
End Sub
But I get the following on my datagrid row: System.Windows.Forms.TextBox, Text: [textbox string]
I tried the following code as well to make sure there was nothing wrong with my settings on my datagrid:
'grdNewInvoice.Rows(0).Cells(0).Value = itemName
'grdNewInvoice.Rows(0).Cells(1).Value = qty
'grdNewInvoice.Rows(0).Cells(2).Value = price
'grdNewInvoice.Rows(0).Cells(3).Value = Total
That worked fine and the text went in as expected but since I will be writing to multiple lines on the datagrid, I will need to use a loop.
What am I doing wrong here?
One way to do this is to use a list of string array.
Dim row As Integer = grdNewInvoice.Rows.Count
Dim data As New List(Of String())
data.Add({txtItem.Text, txtQTY.Text, txtPrice.Text, txtTotal.Text})
data.Add({"Item2", "qtr2", "price2", "total2"})
data.Add({"Item3", "qty3", "price3", "total3"})
For i As Integer = 0 To data.Count - 1
grdNewInvoice.Rows.Add(data(i))
Next