How to Compute a Database Column in .NET - vb.net

I have a Database named CarsType.accdb there are four fields in the data base Item_Name, Item_Num, Item_Qty, Item_Cost.
I am able to get the database to display my data in VisualBasic but I am not sure how to get the total cost to appear in my label (lblTotalCost). I prefer doing it in VB versus writing in my access program. All I am wanting to do it multiply item_qty * Item_Cost How would I go about doing that?
Public Class frmCarInventory
Private Sub CarInventoryBindingNavigatorSaveItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CarInventoryBindingNavigatorSaveItem.Click
Me.Validate()
Me.CarInventoryBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.CarDataSet)
End Sub
Private Sub frmCarInventory_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'CarDataSet.CarInventory' table. You can move, or remove it, as needed.
Me.CarInventoryTableAdapter.Fill(Me.CarDataSet.CarInventory)
Try
Me.CarInventoryTableAdapter.Fill(Me.CarDataSet.CarInventory)
Catch ex As Exception
MsgBox("The Database Files is Unavailable", , "Error")
End Try
End Sub
Private Sub btnComputeTheTotalValueOfInventory_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnComputeTheTotalValueOfInventory.Click
Dim strSql As String = "SELECT * FROM CarType "
'strPath provides the database type and path of the CarType database.
Dim strPath As String = "Provider=Microsoft.ACE.OLEDB.12.0 ;" & "Data Source=..\CarType.accdb"
Dim odaInventory As New OleDb.OleDbDataAdapter(strSql, strPath)
Dim DatCost As New DataTable
Dim intCount As Integer
Dim decTotalCost As Decimal = 0D
'The DataTable name datCost is filled with the data
odaInventory.Fill(DatCost)
'The connection to the databsise is disconnected
odaInventory.Dispose()
For intCount = 0 To DatCost.Rows.Count - 1
decTotalCost += Convert.ToDecimal(DatCost.Rows(intCount)("Total Inventory Cost"))
Next
Me.lblTotalCost.Visible = True
Me.lblTotalCost.Text = "El Value " & decTotalCost.ToString("C")
End Sub
End Class
Would this be handled like an sql satement?

When you add a new System.Data.DataColumn to a System.Data.DataTable, you can specify an expression, thus creating a computed column. In C# the syntax to do this is:
dataTable.Columns.Add("total_cost", typeof(double), "item_qty * item_cost");
The syntax to do this in VB.NET will be quite similar, but I've left it as an exercise for the reader.

Perhaps you could just use something like this?
Dim TotalCost As String
TotalCost = Me![item_qty] * Me![item_cost]
Me![lblTotalCost].Caption = TotalCost

Related

Data type mismatch VB.net and Access Database

On my Delete button click event I am getting a Additional information: No value given for one or more required parameters. In my Access Database CustNo is a DataType of Short Text
Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
Dim custNumber As String
custNumber = txtCustNo.Text
Dim command As OleDbCommand
Dim deleteQuery As String = "DELETE FROM TblLabelCustom_copy WHERE [CustNo]= #custNo"
command = New OleDbCommand(deleteQuery)
command.Parameters.AddWithValue("#custNo", OleDbType.VarChar).Value = custNumber
ExecuteQuery(deleteQuery)
loadGrid()
End Sub

How to jump to a row of a DataView based on partial match search criteria?

Currently, my application uses the RowFilter property on an expression to search for a user-defined string within a DataView. Currently my code looks something like this:
Public Class MyClass
Private custView As DataView
Private Sub form_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
dsDataSet = <"DataAccessLayer call to SQL Stored Procedure">
custView = New DataView(dsDataSet.Tables(0))
custView.Sort = "Column Name"
Me.C1FlexGrid1.DataSource = custView
End Sub
Private Sub txtSearch_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtSearch.TextChanged
Dim searchText As String = txtSearch.Text
Dim expression As String = "Column Name LIKE '" + searchText + "%'"
custView.RowFilter = expression
Me.C1FlexGrid1.DataSource = custView
End Sub
End Class
My goal is to modify the behavior of this such that instead of filtering out rows that do not meet the search results, it will keep all rows present but jump to the first instance of a partial match as the user types in the search box. If DataView.Find() supported wildcards I would be set, but unfortunately it doesn't.
The solution I've come up with is to use some iteration logic. However this is done on the object the DataView has been bound to and not the DataView itself. Although this code can be modified to do exactly that.
Private Sub txtSearch_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtSearch.TextChanged
'Unselect all
Me.C1FlexGrid1.Select(-1, -1, True)
If txtSearch.Text <> "" And [column index] <> -1 Then
'Typed text
Dim s As String = txtSearch.Text.Trim.ToLower
Dim column As Int32 = [column index] + 1
'Recurse until match in first column is found
For i As Integer = 0 To Me.C1FlexGrid1.Rows.Count - 1
If C1FlexGrid1.GetData(i, column) <> Nothing Then
If C1FlexGrid1.GetData(i, column).ToString.ToLower.StartsWith(s) Then
Me.C1FlexGrid1.Select(i, column, True)
Exit Sub
End If
Else
MsgBox("Error message", vbOKOnly, "NO MATCHES")
'Reset search criteria
Call ResetSearch()
End If
Next
MsgBox("Error message", vbOKOnly, "NO MATCHES")
End If
End Sub

Public variable used for form opening not feeding through to from

Having some issues getting a form to populate based on a variable determined in current form.
I have a search result form that has a datagrid with all results, with an open form button for each row. When the user clicks this, the rowindex is used to pull out the ID of that record, which then feeds to the newly opened form and populates based on a SQL stored procedure run using the ID as a paramter.
However, at the moment the variable is not feeding through to the form, and am lost as to why that is. Stored procedure runs fine if i set the id within the code. Here is my form open code, with sci
Public Class SearchForm
Dim Open As New FormOpen
Dim data As New SQLConn
Public scid As Integer
Private Sub Search_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim sql As New SQLConn
Call sql.SearchData()
dgvSearch.DataSource = sql.dt.Tables(0)
End Sub
Private Sub dgvSearch_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvSearch.CellContentClick
Dim rowindex As Integer
Dim oform As New SprinklerCardOpen
rowindex = e.RowIndex.ToString
scid = dgvSearch.Rows(rowindex).Cells(1).Value
TextBox1.Text = scid
If e.ColumnIndex = 0 Then
oform.Show()
End If
End Sub
End Class
The form opening then has the follwing:
Private Sub SprinklerCard_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Populate fields from SQL
Try
Call Populate.SprinklerCardPopulate(ID)
cboInsured.Text = Populate.dt.Tables(0).Rows(0).Item(1)
txtAddress.Text = Populate.dt.Tables(0).Rows(0).Item(2)
txtContactName.Text = Populate.dt.Tables(0).Rows(0).Item(3)
txtContactPhone.Text = Populate.dt.Tables(0).Rows(0).Item(4)
txtContactEmail.Text = Populate.dt.Tables(0).Rows(0).Item(5)
numPumps.Value = Populate.dt.Tables(0).Rows(0).Item(6)
numValves.Value = Populate.dt.Tables(0).Rows(0).Item(7)
cboLeadFollow.Text = Populate.dt.Tables(0).Rows(0).Item(8)
cboImpairment.Text = Populate.dt.Tables(0).Rows(0).Item(9)
txtComments.Text = Populate.dt.Tables(0).Rows(0).Item(10)
Catch ex As Exception
MsgBox(ex.ToString & "SCID = " & ID)
End Try
End Sub
Set the ID variable in the form before you open it.
If e.ColumnIndex = 0 Then
oform.ID = scid
oform.Show()
End If

read single word from listbox vb

I have an order form I created in VB.NET and I have a ListBox that is populated by order. You can double click on the order and it populates the order number in the order form. The problem I'm having is that it populates the TextBox with both the order number and the persons name. How can I use a delimiter to only pull out the order number and not the name also.
Imports Business_Objects
Public Class frmSummary
Private ctrl As Controller
Dim listID As ArrayList
Private Sub frmSummary_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
ctrl = CType(MdiParent, frmMain).ctrl
Dim list As ArrayList
list = ctrl.GetOrders
Dim order As Business_Objects.Order
For Each order In list
lstOrders.Items.Add(order.ID & "," & " " & order.Server)
Next
End Sub
Private Sub lstOrders_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles lstOrders.DoubleClick
Dim result As Boolean = False
If lstOrders.Text <> "" Then
result = True
Dim frm As New OrderForm
frm.MdiParent = Me.MdiParent
frm.Show()
frm.txtOrderNo.Text = lstOrders.Text
frm.btnFetch.PerformClick()
Else
MessageBox.Show("there are no orders here to click")
End If
End Sub
Private Sub btnRefresh_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRefresh.Click
lstOrders.Items.Clear()
ctrl = CType(MdiParent, frmMain).ctrl
Dim list As ArrayList
list = ctrl.GetOrders
Dim order As Business_Objects.Order
For Each order In list
lstOrders.Items.Add(order.ID & " " & order.Server)
Next
End Sub
End Class
If all of your data is being stored as a single field, or something like:
4322305 John Smith Carrots $3.00
845825 Sam White Oranges $1.25
Then you can read each record as a string, and then use split that into an array based on " " as your delimiter.
The code would look something like:
dim myArray as string() = myLongTextRecord.Split(" ")
And in that format,
textBoxName.Text = myArray[1]
You're almost there. You could use the split function, but another approach would be to add the Order object directly to the listbox and not text.
Private Sub frmSummary_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
ctrl = CType(MdiParent, frmMain).ctrl
Dim list As ArrayList
list = ctrl.GetOrders
Dim order As Business_Objects.Order
For Each order In list
lstOrders.Items.Add(order)
Next
End Sub
Private Sub lstOrders_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles lstOrders.DoubleClick
Dim result As Boolean = False
If lstOrders.Text <> "" Then
result = True
Dim frm As New OrderForm
frm.MdiParent = Me.MdiParent
frm.Show()
frm.txtOrderNo.Text = DirectCast(lstOrders.SelectedItem, Order).ID.ToString
frm.btnFetch.PerformClick()
Else
MessageBox.Show("there are no orders here to click")
End If
End Sub
You'll need to go into the Order object and override the .ToString function so that the text in the Listbox displays whatever value you want (ie. Return ID & "," & " " & Server)

Fetching Data in GridView Cells/Column

I am a newbie in VB.net(programming). I need your advice regarding Gridview control.
I have a gridview loaded with two columns-one column(Name)is with some Text,another(Price) is empty.
I have got a TextBox with the data of Name and Price.
Now,I would like to loop through the Textbox,and see if the Data/symbols of the Column(Name) of GridView Control matches with the Data in Textbox.
If the Names of the GridView’s First Column’s data matches with the names of the Textbox,then the Price data should be fetched in the Second Column(Price) of GridView.
To make it more clear,say :
I have the following data in Textbox :
Name- Price
AB- 50
DE- 80
And I have two columns in GridView with following setups :
Name(column1) – Price(column2)
AB- Empty
DE- Empty
Now,how can I get the Price Data of Textbox,and fetch them into the Column2 of Gridview matching the Names of Column1. So,the output in GridView should be :
Name(column1) – Price(column2)
AB- 50
DE- 80
So far,I have been able to just loop through the first column of GridView…..I’m not sure how to get the data from Textbox and fetch the data into Column2 of GridView.
Any suggestion would be highly appreciated.
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Data of GridView
Dim dt As New DataTable()
dt.Columns.Add("Name")
dt.Columns.Add("Price")
dt.Rows.Add(New [Object]() {"AB"})
dt.Rows.Add(New [Object]() {"DE"})
Me.DataGridView1.DataSource = dt
'Data of Textbox
TextBox1.Text = "AB, 50" & vbNewLine & "DE, 100"
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'loop through the gridview
Dim marketvalue As String
For Each r As DataGridViewRow In Me.DataGridView1.Rows
marketvalue = r.Cells(0).Value
MessageBox.Show(marketvalue)
Next
End Sub End Class
I would use a separate function to get the price from your TextBox
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'loop through the gridview
Dim marketvalue As String
Dim price As String
For Each r As DataGridViewRow In Me.DataGridView1.Rows
marketvalue = r.Cells(0).Value
MessageBox.Show(marketvalue)
'Get the price by calling a function and update it back to the DataGrid
price = get_price(marketvalue)
r.Cell(1).Value = price
Next
End Sub
The following function can return you the price by passing the name parameter, otherwise empty if the name is not found
Private Function get_price(ByVal strName As String) As String
Dim string_array() As String = TextBox1.Text.Split(System.Environment.vbNewLine)
For Each s As String In string_array
Dim string_detail() As String = s.Split(",")
If string_detail(0) = strName Then
Return Trim(string_detail(1))
End If
Next
Return ""
End Function