How can I put an extra value? - vb.net

I have a table (DataGridView) like this :
Col1 | Col2 | Col3
3 | Mars | Regular
Here is my code:
For a As Integer = 0 To Form3.DataGridView1.Rows.Count - 1
For b As Integer = 0 To Form3.DataGridView1.Rows.Count - 1
For c As Integer = 0 To Form3.DataGridView1.Rows.Count - 1
If Form3.DataGridView1.Rows(c).Cells(2).Value = "Regular" Then
If Form3.DataGridView1.Rows(b).Cells(1).Value = Form3.MetroComboBox7.Items(0) Then
fair = 7 * Form3.DataGridView1.Rows(a).Cells(0).Value
Label1.Text += fair
End If
End If
Next
Next
Next
I want to set that if Regular is selected on Col3 and Mars on Col2 then the value is 7 and it will multiply by row Col1 and it will be the same every row.

I think you should use the event dtgv.CellMouseClick.
Then you create conditions that you want. I give you an example here :
Public Sub event_select() Handles dtgv.CellMouseClick
Dim row As Integer = dtgv.CurrentRow.Index()
' If the column 2 and 3 are selected
If dtgv.Rows(row).Cells(1).Selected = True And dtgv.Rows(row).Cells(2).Selected = True Then
' If the value of the 2nd column is Mars and the value of the 3rd column is Regular
If dtgv.Rows(row).Cells(1).Value = "Mars" And dtgv.Rows(row).Cells(2).Value = "Regular" Then
Label1.Text = 7 * dtgv.Rows(row).Cells(0).Value
End If
End If
End Sub
You should also check that no other rows have cells selected.

One loop for all rows is enough to calculate "fair" for all rows
Const REGULAR_VALUE As String = "Regular"
Const FAIR_COEFFICENT As Integer = 7
Dim fairSum As Integer = 0
For Each row As DataGridViewRow in DataGridView1.Rows
If REGULAR_VALUE.Equals(row.Cells(2).Value.ToString()) = False Then Continue For
If Equals(MetroComboBox7.Items(0), row.Cells(1).Value) = False Then Continue For
Dim col1Value As Integer = Integer.Parse(row.Cells(1).Value)
Dim fair As Integer = col1Value * FAIR_COEFFICENT
fairSum += fair
Next
Label1.Text = fairSum.ToString()
And set Option Strict On in your project or at least in the code file(first line of file).
This will save you time by giving fast feedback about possible type converting errors during compile time.
Create class which represent your data in strongly typed manner
Public Class Ticket
Public Property Passenger As Integer
Public Property Destination As String
Public Property Status As String
End Class
Then you can add rows to the DataGridView in easy way in your form
Public Class YourForm
Private _tickets As New BindigList(Of Ticket)()
Public Sub New()
InitializeComponent() ' Forms required method
DataGridView1.DataSource = _tickets
End Sub
Private Sub Populate(passenger As Integer, destination As String, Status As String)
Dim newTicket As New Ticket With
{
.Passenger = passenger,
.Destination = destination,
.Status = Status,
}
_ticket.Add(newTicket)
End Sub
'Then you can loop all rows with correct types
Private Sub Calculate()
Dim fairSum As Integer = 0
For Each ticket As Ticket in _tickets
If REGULAR_VALUE.Equals(ticket.Status) = False Then Continue For
If ticket.Destination.Equals(MetroComboBox7.Items(0)) = False Then Continue For
Dim fair As Integer = ticket.Passenger * FAIR_COEFFICENT
fairSum += fair
Next
Label1.Text = fairSum.ToString()
End Sub
End Class

Related

DataTable.Rows.Count always returns 0 - VB.NET

I'm trying to populate DataGridView cells with information from two (parent, child tables). Everything works just fine, except for this part table.Rows.Count. It always returns 0, no matter that I have one record in the table.
This is the code:
Private Sub Query__tbl_purchase_order_articlesDataGridView_CellEndEdit(sender As Object, e As DataGridViewCellEventArgs) Handles Query__tbl_purchase_order_articlesDataGridView.CellEndEdit
Dim table As DataTable = Orders_DBDataSet.Tables("tbl_list_of_articles")
Dim selectedRowCount As Integer = Query__tbl_purchase_order_articlesDataGridView.CurrentCell.RowIndex
Dim art_ID As Integer = CInt(Query__tbl_purchase_order_articlesDataGridView.Rows(selectedRowCount).Cells(0).Value)
Dim art_ttl As String
Dim art_ttl_tr As String
Dim mu As String
Dim art_ttl_i As Integer
Dim art_ttl_tr_i As Integer
Dim mu_i As Integer
Dim art_ID_t_i As Integer
Dim art_ttl_t_i As Integer
Dim art_ttl_tr_t_i As Integer
Dim mu_t_i As Integer
Dim i As Integer
'search for column index in DataGridView
For i = 0 To Query__tbl_purchase_order_articlesDataGridView.Columns.Count - 1
If Query__tbl_purchase_order_articlesDataGridView.Columns(i).HeaderText.ToString = "article_name" Then
art_ttl_i = i
End If
If Query__tbl_purchase_order_articlesDataGridView.Columns(i).HeaderText.ToString = "article_name_tr" Then
art_ttl_tr_i = i
End If
If Query__tbl_purchase_order_articlesDataGridView.Columns(i).HeaderText.ToString = "masurement_unit" Then
mu_i = i
End If
Next
'search for column index in "table"
For i = 0 To table.Columns.Count - 1
If table.Columns(i).ColumnName.ToString = "article_ID" Then
art_ID_t_i = i
End If
If table.Columns(i).ColumnName.ToString = "article_name" Then
art_ttl_t_i = i
End If
If table.Columns(i).ColumnName.ToString = "article_name_tr" Then
art_ttl_tr_t_i = i
End If
If table.Columns(i).ColumnName.ToString = "masurement_unit" Then
mu_t_i = i
End If
Next
For i = 0 To table.Rows.Count
If art_ID = CInt(table.Rows(i).Item(art_ID_t_i).ToString()) Then
art_ttl = table.Rows(i).Item(art_ttl_t_i).ToString()
art_ttl_tr = table.Rows(i).Item(art_ttl_tr_t_i).ToString()
mu = table.Rows(i).Item(mu_t_i).ToString()
Query__tbl_purchase_order_articlesDataGridView.Rows(selectedRowCount).Cells(art_ttl_i).Value = art_ttl
Query__tbl_purchase_order_articlesDataGridView.Rows(selectedRowCount).Cells(art_ttl_tr_i).Value = art_ttl_tr
Query__tbl_purchase_order_articlesDataGridView.Rows(selectedRowCount).Cells(mu_i).Value = mu
Exit For
End If
Next
End Sub
Also, I tied to test it like this, but the result is the same. It can find a table index, but always return 0 as a table row count.
'test ========================================
Dim x, y As Integer
For x = 0 To Orders_DBDataSet.Tables.Count - 1
If Orders_DBDataSet.Tables(x).TableName.ToString = "tbl_list_of_articles" Then
y = x
End If
Next
x = 0
For Each row As DataRow In table.Rows
x = x + 1
Next
'============================================
x = Orders_DBDataSet.Tables(y).Rows.Count
Most of the times this happened to me because I was not actually using the instance of the dataset "connected" to the form. What does this mean? You either don't populate the dataset instance tied to the form in the Load event, or you are populating it but you are somehow using other instance of it. This has a higher chance of happening if you are sending data between forms as well.

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

Add quantity if the DataGridView item already exists

I have created a cart using a DataGridView and on the add to cart button I have this code:
Dim a As Integer
Dim total As Integer
Dim b As Integer
a = TextBox2.Text
b = NumericUpDown56.Value
total = a * b
ShoppingCart.DataGridView1.Rows.Add(Me.Label11.Text, Me.TextBox2.Text, Me.NumericUpDown56.Value, total)
Me.Hide()
ShoppingCart.Show()
How can I add quantity if I re-added the same item?
It is a little hard to answer this without knowing quite what the textbox and updowncounter do... but assuming you only expect the updown counter to change...
You can iterate through the data and hunt for the same text in the first column
Dim a As Integer
Dim total As Integer
Dim b As Integer
a = TextBox2.Text
b = NumericUpDown56.Value
total = a * b
Dim Updated As Boolean
For Each row As DataGridViewRow In ShoppingCart.DataGridView1.Rows
If CType(row.Cells(0).Value, String) = Me.Label11.text Then
row.Cells(2).Value = CType(row.Cells(0).Value, Integer) + b
row.Cells(3).Value = CType(row.Cells(3).Value, Integer) + total
Updated = True
Exit For
End If
Next
If Not Updated Then ShoppingCart.DataGridView1.Rows.Add(Me.Label11.Text, Me.TextBox2.Text, Me.NumericUpDown56.Value, total)
Me.Hide()
ShoppingCart.Show()
Though personally I'd bind the datagridview to a of List(of T) (t = a class that retains your properties) and search / modify that instead, then rebind the list.
Something along these lines...
Private Class cls_Cart_Item
Public Property Item_Name As String
Public Property Whatever_TExtbox2_IS_SUpposed_to_be As Integer
Public Quantity As Integer
Public Sub New(wName As String, wWhatever_TExtbox2_IS_SUpposed_to_be As Integer, wQuantity As Integer)
Item_Name = wName
Whatever_TExtbox2_IS_SUpposed_to_be = wWhatever_TExtbox2_IS_SUpposed_to_be
Quantity = wQuantity
End Sub
Public ReadOnly Property Total As Integer
Get
Return Whatever_TExtbox2_IS_SUpposed_to_be * Quantity
End Get
End Property
End Class
Private Cart As New List(Of cls_Cart_Item)
Private Sub Add_Or_Update()
ShoppingCart.datagridview1.datasource = Nothing
Dim a As Integer
Dim total As Integer
Dim b As Integer
a = TextBox2.Text
b = NumericUpDown56.Value
Dim Item As New cls_Cart_Item = Cart.Find(Function(x) x.Item_Name = Me.Label11.Text)
If Item Is Nothing Then
Cart.Add(New cls_Cart_Item(Me.Label11.Text, a, b))
Else
Item.Quantity += b
End If
Me.Hide()
ShoppingCart.datagridview1.datasource = Cart
End Sub
Though it's hard to tell from your question where this code is coming from relative to the daraviewgrid.

Visual Basic: How can i display the prime numbers between 1 and the inputted number

Hello everyone so i'm trying to find the prime numbers of any input. I want them to be in a listbox and the input in a text box. I would like to use two arguments but i don't know how to. this is the code i have i need dire help. I am not the best at visual basic i just need some guidance. My code isn't working but display a drop down box when i press display.
Public Class Form1
Private Sub Button3_Click_1(sender As Object, e As EventArgs) Handles Button3.Click
Dim prim As Integer
Dim test As Integer
Dim imPrime As Boolean = False
prim = CInt(txtNum.Text)
test = prim
If prim = 1 Then
imPrime = False
MessageBox.Show("Enter a number greater than one please")
Else
Do While prim >= 2
For i As Integer = 2 To prim
If prim Mod i = 0 Then
imPrime = False
Exit For
Else
imPrime = True
lstPrime.Items.Add(prim)
End If
Next
Loop
End If
If imPrime = True Then
lstPrime.Items.Add(prim)
End If
End Sub
End Class
This is my fastest VBA code to generate prime numbers between two numbers.
The generated prime numbers are put in clipboard. You will need to open
your ms office word and type Ctrl+V to view all the generated prime numbers.
Sub generateprimenumbersbetween()
Dim starting_number As Long
Dim last_number As Long
Dim primenumbers As Variant
Dim a As Long
Dim b As Long
Dim c As Long
starting_number = 1 'input value here
last_number = 1000000 'input value here
primenumbers = ""
For a = starting_number To last_number
c = Round(Sqr(a)) + 1
For b = 2 To c
If a = 1 Or (a Mod b = 0 And c <> b) Then
Exit For
Else
If b = c Then
primenumbers = primenumbers & " " & a
Exit For
End If
End If
Next b
Next a
Dim answer As DataObject
Set answer = New DataObject
answer.SetText primenumbers
answer.PutInClipboard
End Sub
I think the while loop is not working as you intend. You need two loops, the first one counting up to the possible prime, and an inner one counting up to the counter in the outer loop.
You can find examples everywhere... here's one implemented in C#, but since your question was specifically about a listbox, I've translated it to VB.
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
calculatePrimes()
End Sub
Private Sub calculatePrimes()
Dim prim As Integer
Dim count As Integer = 0
prim = CInt(Me.TextBox1.Text)
If prim < 3 Then
MsgBox("Please enter a bigger number")
Return
End If
Me.ListBox1.Items.Clear()
For i As Integer = 1 To prim
Dim isPrime As Boolean = True
For j As Integer = 2 To i
If (i Mod j <> 0) Then count = count + 1
Next
If count = (i - 2) Then Me.ListBox1.Items.Add(i)
count = 0
Next
End Sub
End Class
(This assumes you have a textbox for input called TextBox1 and a listbox for display called ListBox1)

VB.NET: How to dynamically select a list view item?

I need to dynamically select an item in a listview based on what was selected previously.
The items that have been selected in the past are retrieved from a database and added to an Arraylist. These items then need to be selected from a number of different listviews.
Doing this by index like so listRef1.Items(2).Checked = True is no problem but I need to do it by the item text, i.e. one of the strings in the array.
So far I have this:
For i As Integer = 0 To refsArr.Count - 1
'find the correct category id
Dim cmdRefCat As New SqlCommand("SELECT RefID from ReferencesListTable WHERE RefName = '" & refsArr(i) & "'", conn)
Dim refid As Integer = cmdRefCat.ExecuteScalar()
If refid = 1 Then
listRef1.Items(refsArr(i)).Checked = True
ElseIf refid = 2 Then
listRef2.Items(refsArr(i)).Selected = True
listRef2.Select()
ElseIf refid = 3 Then
listRef3.Items.Item(refsArr(i)).Selected = True
listRef2.Select()
ElseIf refid = 4 Then
listRef4.Items.Item(refsArr(i)).Selected = True
End If
Next
Has anyone got any ideas on this? Thanks.
You'll need to loop through each item in the listview list:
For I as Integer = 0 to ListView.Items.Count - 1 Do
If ListView.Items(i).Text = "Text" then
ListView.Items(i).Selected = true
End If
End For
You can try this ...
For i As Integer = 0 To refsArr.Count - 1
'find the correct category id
Dim cmdRefCat As New SqlCommand("SELECT RefID from ReferencesListTable WHERE RefName = '" & refsArr(i) & "'", conn)
Dim refid As Integer = cmdRefCat.ExecuteScalar()
Select case refid
case 1
CheckIt(refsArr(i),listRef1)
case 2
CheckIt(refsArr(i),listRef2)
case 3
CheckIt(refsArr(i),listRef3)
case 4
CheckIt(refsArr(i),listRef4)
End Select
Next
And Sub CheckIt
Sub CheckIt(ByVal sRef as String, ByRef lvw as Listview)
Dim x as Integer
For x = 0 to lvw.Items.Count - 1
If lvw.Items(x).Text = sRef then
lvw.Items(x).Selected = true
exit for '-- if only 1 record
End If
Next
End Sub
The code to select an item dynamically from the listview control can be as follows for vb.net.
Let lvwomominiChair1 is the name of the listview control.
Set its fullrowselect property as true.
The code will select the text in the first column of the listview control.
Private Sub lvwomominiChair1_Click(sender As Object,e As EventArgs) Handles lvwomominiChair1.Click
Dim lvwitem as ListViewItem
lvwitem = lvwomominiChair1.SelectedItems.Item(0)
MsgBox("Selected item is " + lvwitem.Text)
End Sub
There may be situations where we need to get all items in a row of a ListView control.The following code may be used for the purpose.It is assumed that there are five columns of data in a raw and are of the text data type.This can be done with a For..Next loop as follows.Let 0,1,2,3 and 4 are the five column indices.
Private Sub lvwomominiChair1_Click(sender As Object,e As EventArgs) Handles lvwomominiChair1.Click
Dim i As Int32
Dim str As String
str =""
For i =0 To 4
str = str + " " + lvwomominiChair1.SelectedItems(0).SubItems(i).Text
Next
MsgBox("Selected items of the five columns of the row are " + str)
End Sub
Or you can do this, works perfect for me:
ListView.Items(0).Selected = True
ListView.Select()