Fetching Data in GridView Cells/Column - vb.net

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

Related

Filtering Datagridview From Datagridview Not From Database

i want to filter datagridview on my form..
on the form :
1 datagridview
1 label
1 timer
i have loaded database into datagridview (all data to datagridview)
on my datagridview i have 7 column the last column is date with format dd/MM/yyyy, and now how to filtering datagridview with label, i set this label to date like this
Private Sub TimerDate_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TimerDate.Tick
Dim FDate As String = Format(Today, "dd/MM/yyyy")
LblDate.Text = FDate
End Sub
and i want to eliminate the other data.. sooo in the end in my datagridview i have data with the last column same as LblDate.text
i dont want to filter datagridview from database.
can someone help me..? thanks.
sorry for my bad english.
this is how i populating data to datagrid
Public Class FrmJadwalSidang
Dim ConnString As String = ("Dsn=SqlConn;Server=192.168.100.1;uid=XXX;pwd=XXX;database=DBXXX;port=3306")
Public Function FillData(ByVal Sqlstring As String)
Dim OdbcConn As OdbcConnection = New OdbcConnection(ConnString)
OdbcConn.Open()
Dim MyDataSet As DataSet = New DataSet()
Dim MyOdbcdAdapter As OdbcDataAdapter = New OdbcDataAdapter()
MyOdbcdAdapter.SelectCommand = New OdbcCommand(Sqlstring, OdbcConn)
MyOdbcdAdapter.Fill(MyDataSet)
Me.DATAGRIDVIEW.DataSource = MyDataSet.Tables(0)
MyOdbcdAdapter.Dispose()
MyDataSet.Dispose()
OdbcConn.Close()
OdbcConn.Dispose()
End Function
Private Sub FrmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
FillData("Select nomor_perkara, jam_sidang, para_pihak, majelis_hakim_text, panitera_pengganti_text, agenda, tanggal_sidang from v_jadwal_sidang")
End Sub
End Class
SOLVED
Private Sub FrmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
FillData("Select nomor_perkara, jam_sidang, para_pihak, majelis_hakim_text, panitera_pengganti_text, agenda, tanggal_sidang from v_jadwal_sidang WHERE jadwal_sidang='" & LblDate.text.tostring & "'")
end sub
it work. in the end i have to filtering by the sql query..
thanks to someone who gives me the answer.
if you are using a SqlDataSource, set the FilterExpression of the control.
See this: How to: Enable Filtering for the SqlDataSource Control
And this: How to: Connect to an ODBC Database Using the SqlDataSource Control
EDIT : I provided the information for a web application not a winform application. Please read this for info on how to set up filtering for a BindingSource: BindingSource.Filter Property

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)

Pass variable to new form with Datatable and Listbox

I am currently trying to write an application like address book. Listbox works properly, it shows everything corretly. But I need to pass id of chosen listbox item to another form. I got code like this in Form2:
Private myTable As New DataTable()
Public Sub LoadXml(sender As Object, e As EventArgs) Handles Me.Load
With myTable.Columns
.Add("DisplayValue", GetType(String))
.Add("HiddenValue", GetType(Integer))
End With
myTable.DefaultView.Sort = "DisplayValue ASC"
ListBox1.DisplayMember = "DisplayValue"
ListBox1.ValueMember = "HiddenValue"
ListBox1.DataSource = myTable
Dim doc As New Xml.XmlDocument
doc.Load("c:\address.xml")
Dim xmlName As Xml.XmlNodeList = doc.GetElementsByTagName("name")
Dim xmlSurname As Xml.XmlNodeList = doc.GetElementsByTagName("surname")
Dim xmlId As Xml.XmlNodeList = doc.GetElementsByTagName("id")
For i As Integer = 0 To xmlName.Count - 1
Dim nazwa As String = xmlName(i).FirstChild.Value + " " + xmlSurname(i).FirstChild.Value
myTable.Rows.Add(nazwa, xmlId(i).FirstChild.Value)
MsgBox(myTable.Rows(i).Item(1).ToString)
Next i
ListBox1.Sorted = True
End Sub
Later in the code I have event:
Public Sub ListBox1_DoubleClick(sender As Object, e As EventArgs) Handles ListBox1.DoubleClick
End Sub
I would like to know how can I call id from DataTable for selected listbox item. I hope u understand what I mean since my english is not perfect :)
Since you have added the XML value id to the data table column HiddenValue and you have assigned HiddenValue as the ValueMember for the listbox, once a record is selected in the listbox, id will be available in the listbox's [SelectedValue][1] member. For example:
Public Sub ListBox1_DoubleClick(sender As Object, e As EventArgs) Handles ListBox1.DoubleClick
MsgBox("Selected Id: " & ListBox1.SelectedValue.ToString())
End Sub

How to Compute a Database Column in .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