Adding dynamic Button and changing its Property text. VB.NET - vb.net

I have this problem by changing the text of added dynamically button.
I want to change the button text from "Select" to "Update".
this is my code.
dim oButton as button
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim dr As SqlDataReader
Dim cn As SqlConnection = New SqlConnection("Data Source=server;Initial Catalog=testDB;Integrated Security=True;MultipleActiveResultSets=true;")
cmd.Connection = cn
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "votecand"
Dim stream As New MemoryStream()
cn.Open()
dr = cmd.ExecuteReader
If dr.HasRows = True Then
while dr.read
oButton = New Button
oButton.Enabled = True
oButton.Font = New Font("Tahoma", 11, FontStyle.Regular)
oButton.Location = New Point(ButtonNumber * 30, ButtonNumber * 30)
oButton.Name = "MyButton" & ButtonNumber.ToString
oButton.Size = New Size(134, 34)
oButton.BackColor = Color.MediumSeaGreen
oButton.FlatStyle = FlatStyle.Flat
oButton.ForeColor = Color.White
oButton.Text = "Select"
oButton.Visible = True
oButton.Dock = DockStyle.Bottom
oButton.Tag = ButtonNumber
AddHandler oButton.Click, AddressOf onButtonClick
Me.Controls.Add(oButton)
End while
End if
End sub
this code is MyFunc Function
Private Sub MyFunc(ByVal ButtonNumber As Integer)
Dim cn As SqlConnection = New SqlConnection("Data Source=server;Initial Catalog=testDB;Integrated Security=True;MultipleActiveResultSets=true;")
Dim command As New SqlCommand
command = New SqlCommand("select first_name,middle_name,last_name,position,gender,course,year_level,aff,student_id from tbl_cand where id=#id", cn)
command.Parameters.AddWithValue("#id", SqlDbType.VarChar).Value = ButtonNumber.ToString
Dim dt As New DataTable()
Dim adapater As New SqlDataAdapter(command)
adapater.Fill(dt)
Dim fname As String = dt.Rows(0).ItemArray(0).ToString
Dim mname As String = dt.Rows(0).ItemArray(1).ToString
Dim lname As String = dt.Rows(0).ItemArray(2).ToString
Dim gender As String = dt.Rows(0).ItemArray(3).ToString
Dim course As String = dt.Rows(0).ItemArray(4).ToString
Dim year As String = dt.Rows(0).ItemArray(5).ToString
Dim aff As String = dt.Rows(0).ItemArray(6).ToString
Dim studid As String = dt.Rows(0).ItemArray(7).ToString
lblfname.Text = fname
lblmname.Text = mname
lbllname.Text = lname
lblgender.Text = gender
lblyear.Text = year
lblmajor.Text = course
lblaff.Text = aff
connect()
sql = "INSERT INTO tbl_castvote(can_id,fname,img,student_id)"
sql = sql + "VALUES(#canid,#fname,#pos,#img,#voterid,#stdid)"
cmd = New SqlCommand(sql, con)
With cmd
.Parameters.AddWithValue("canid", studid)
.Parameters.AddWithValue("fname", fname)
Dim ms As New MemoryStream()
pb.Image.Save(ms, pb.Image.RawFormat)
Dim data As Byte() = ms.GetBuffer()
Dim p As New SqlParameter("#img", SqlDbType.VarBinary)
p.Value = data
.Parameters.Add(p)
.Parameters.AddWithValue("stdid", studentid.Text)
End With
If MsgBox("You have selected" & " '" & fname & " " & mname & " " & lname & "' " & "as" & " '" & pos & "' ", vbOKCancel + vbInformation, "Voting System") = vbOK Then
cmd.ExecuteNonQuery()
oButton.Text = "Update" --> this line is my problem. Can't change the oButton.text "Select" to "Update"
End If
End Sub
and this is my button click handler
Private Sub onButtonClick(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim ButtonNumber As Integer
If CType(sender, Button).Tag IsNot Nothing Then
If Integer.TryParse(CType(sender, Button).Tag.ToString, ButtonNumber) Then
MyFunc(ButtonNumber)
End If
End If
End Sub
pls help me. thank you

A couple of issues. You need to increment your ButtonNumber value inside your loop:
while dr.read
ButtonNumber += 1
oButton = New Button
oButton.Name = "MyButton" & ButtonNumber.ToString
Then in your function, you have to find your button to update it:
cmd.ExecuteNonQuery()
Dim btn As Button = Me.Controls.OfType(Of Button).
Where(Function(x) x.Name = "myButton" & btnNumber.ToString).
FirstOrDefault()
If btn IsNot Nothing Then
btn.Text = "Update"
End If
Change your function parameter to be unique:
Private Sub MyFunc(btnNumber As Integer)

You are using one reference for multiple buttons. You have two options from the above code.
1. Save your added button references in a list
Private Buttons As List(of Button)
Before you start your loop
Buttons = New List(of Button)
in your loop
Dim oButton = New Button
ButtonNumber = Buttons.Count '<-- use the collection count as the number
...blah blah blah...
Buttons.Add(oButton)
Then in myFunc simply use
Buttons(ButtonNumber).Text = "whatever"
2. If this is the only place you reference it, pass the sender along instead.
Private Sub MyFunc(Byref Pressed_Button as Button, ByVal ButtonNumber As Integer)
...blah blah blah...
Pressed_Button.Text = "whatever"
End Sub
Private Sub onButtonClick(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim PressedButton as Button = CType(sender, Button)
Dim ButtonNumber As Integer
If PressedButton.Tag IsNot Nothing Then
If Integer.TryParse(PressedButton.Tag.ToString, ButtonNumber) Then
MyFunc(PressedButton, ButtonNumber)
End If
End If
End Sub
There are also ways to search for the control by name, but keeping your own index is more efficient.

Related

VB Net - How to get cascading drop down list to select self insert row without error?

I have 4 dropdownlist in my web form that is cascading, the value of the 1st dropdownlist will affect the selection of the 2nd dropdownlist and so on.
Protected Sub line_selectedindexchanged(ByVal sender As Object, ByVal e As EventArgs)
Dim level1_ID As Integer = Convert.ToInt32(line.SelectedValue.ToString())
FillProcess(level1_ID)
End Sub
Protected Sub ddlprocess_selectedindexchanged(ByVal sender As Object, ByVal e As EventArgs)
Dim level2_ID As Integer = Convert.ToInt32(ddlprocess.SelectedValue.ToString())
FillEquipment(level2_ID)
End Sub
Protected Sub equipment_selectedindexchanged(ByVal sender As Object, ByVal e As EventArgs)
Dim level3_ID As Integer = Convert.ToInt32(equipment.SelectedValue.ToString())
FillStep(level3_ID)
End Sub
Private Sub FillLine() '1st dropdown
Dim dt As New DataTable
Dim strSql = "select distinct level1_id, [LCODE1]+ ' | '+[LNAME1] as [LCODE1]" _
& " FROM [SQLIOT].[dbo].[ZVIEW_MCM_LEVEL_LOOKUP]"
Using conn As New SqlConnection(ConStr),
cmd As New SqlCommand(strSql, conn)
conn.Open()
dt.Load(cmd.ExecuteReader)
End Using
If dt.Rows.Count > 0 Then
line.DataSource = dt
line.DataTextField = "LCODE1"
line.DataValueField = "level1_id"
line.DataBind()
line.Items.Insert(0, "")
End If
End Sub
Private Sub FillProcess(ByVal level1_ID As Integer) '2nd dropdown
Dim dt As New DataTable
Dim strSql = "select distinct level2_id, [LCODE2]+ ' | '+[LNAME2] as [LCODE2] " _
& "FROM [SQLIOT].[dbo].[ZVIEW_MCM_LEVEL_LOOKUP] where level1_id = #level1_id"
Using conn As New SqlConnection(ConStr),
cmd As New SqlCommand(strSql, conn)
cmd.Parameters.Add("#level1_id", SqlDbType.Int).Value = level1_ID
conn.Open()
dt.Load(cmd.ExecuteReader)
End Using
If dt.Rows.Count > 0 Then
ddlprocess.DataSource = dt
ddlprocess.DataTextField = "LCODE2"
ddlprocess.DataValueField = "level2_id"
ddlprocess.DataBind()
ddlprocess.Items.Insert(0, "")
End If
End Sub
Private Sub FillEquipment(ByVal level2_ID As Integer) '3rd dropdown
Dim dt As New DataTable
Dim strSql = "select distinct level3_id, [LCODE3]+ ' | '+[LNAME3] as [LCODE3] " _
& "FROM [SQLIOT].[dbo].[ZVIEW_MCM_LEVEL_LOOKUP] where level2_id = #level2_id"
Using conn As New SqlConnection(ConStr),
cmd As New SqlCommand(strSql, conn)
cmd.Parameters.Add("#level2_id", SqlDbType.Int).Value = level2_ID
conn.Open()
dt.Load(cmd.ExecuteReader)
End Using
If dt.Rows.Count > 0 Then
equipment.DataSource = dt
equipment.DataTextField = "LCODE3"
equipment.DataValueField = "level3_id"
equipment.DataBind()
equipment.Items.Insert(0, "")
End If
End Sub
Private Sub FillStep(ByVal level3_ID As Integer) '4th dropdown
Dim dt As New DataTable
Dim strSql = "select distinct [LCODE4]+ ' | '+[LNAME4] as [LCODE4] " _
& "FROM [SQLIOT].[dbo].[ZVIEW_MCM_LEVEL_LOOKUP] where level3_id = #level3_id"
Using conn As New SqlConnection(ConStr),
cmd As New SqlCommand(strSql, conn)
cmd.Parameters.Add("#level3_id", SqlDbType.Int).Value = level3_ID
conn.Open()
dt.Load(cmd.ExecuteReader)
End Using
If dt.Rows.Count > 0 Then
[step].DataSource = dt
[step].DataTextField = "LCODE4"
[step].DataBind()
[step].Items.Insert(0, "")
End If
End Sub
The reason I want a blank 1st row is so that when the form loads I want all dropdownlist to start off empty. During testing I thought to try selecting back to blank 1st row after selecting a value. This causes an error to occur at:
'Any one of the selectedindexchanged sub depending on which list I used
Protected Sub line_selectedindexchanged(ByVal sender As Object, ByVal e As EventArgs)
Dim level1_ID As Integer = Convert.ToInt32(line.SelectedValue.ToString()) '--> issue here
FillProcess(level1_ID)
End Sub
Error message being:
Input string was not in a correct format.
Anything I can do to fix this?

UPDATE Database from Listview checked items

Hellos guys.
I'm trying to update my database from only checked/selected items in my listview, so here is my code that is not working because updates all records. I tried everything... Please any help could be great!
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim constring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\bnp\Desktop\Servicios1.mdb"
Dim myconnection As New OleDbConnection(constring)
Dim sql As String = ""
Dim estado As String = "Saved"
myconnection.Open()
If ListView1.CheckedItems.Count > 0 Then
Dim x = ListView1.CheckedItems.ToString
sql = "UPDATE Pedidos SET Ped_est = #estado where x = #x"
Dim acscmd = New OleDb.OleDbCommand(sql, myconnection)
acscmd.Parameters.AddWithValue("#estado", estado)
acscmd.Parameters.AddWithValue("#x", x)
acscmd.ExecuteNonQuery()
End If
myconnection.Close()
End Sub
I'm trying to update my database from only checked/selected items in my listview
if You want to update just Select items You must Make (For)
For II As Integer = 0 To ListView1.SelectedItems.Count - 1
sql = "UPDATE Pedidos SET Ped_est = #estado where x
= '" & ListView1.SelectedItems.Item(II).SubItems(0).Text & "'"
your code Here
Next
i hope this Code good for you
Just solve my problem... Here is the code if someone have the same issue ty ;).
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim constring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\bnp\Desktop\Servicios1.mdb"
Dim myconnection As New OleDbConnection(constring)
Dim sql As String = ""
Dim estado As String = "Saved"
myconnection.Open()
For Each item As ListViewItem In ListView1.Items
If item.Checked Then
Dim x = item.SubItems(0).Text
sql = "UPDATE Pedidos SET Ped_est = #estado WHERE Id = #x"
Dim acscmd = New OleDb.OleDbCommand(sql, myconnection)
acscmd.Parameters.AddWithValue("#estado", estado)
acscmd.Parameters.AddWithValue("#x", x)
acscmd.ExecuteNonQuery()
End If
Next
myconnection.Close()
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
For x As Integer = 0 To ListView1.Items.Count - 1
' For i = 0 To ListView1.Items.Count - 1
If ListView1.Items(x).Checked = True Then
Dim Stradd12 As String = "INSERT INTO `tbl_student_attendence` ([student_id],[Student_Name],[Activities],[pDate],[pDay],[Ptime]) VALUES (student_id,Student_Name,Activities,pDate,pDay,Ptime )"
'Dim Stradd12 As String = "INSERT INTO `tbl_student_attendence` ([student_id]) VALUES (student_id )"
Dim cm12 As OleDbCommand = New OleDbCommand(Stradd12, DBconnection)
cm12.Parameters.AddWithValue("student_id", CType(ListView1.Items(x).SubItems(0).Text, Integer))
cm12.Parameters.AddWithValue("Student_Name", CType(ListView1.Items(x).SubItems(1).Text, String))
cm12.Parameters.AddWithValue("Activities", CType(ListView1.Items(x).SubItems(2).Text, String))
cm12.Parameters.AddWithValue("pDate", CType(DateTimePicker1.Value, String))
cm12.Parameters.AddWithValue("pDay", CType(ComboBox1.Text, String))
cm12.Parameters.AddWithValue("Ptime", CType(ListView1.Items(x).SubItems(3).Text, String))
'cm12.Parameters.AddWithValue("Registration_no", CType(TextBox1.Text, Integer))
cm12.ExecuteNonQuery()
cm12.Parameters.Clear()
End If
' Next
Next
MsgBox("Attendence Updated Successfully.")
End Sub

All my tabpage create in runtime using Tabcontrol can't show 3rd button even i have it in my database

Why all my tabpage created during tuntime using Tabcontrol can't show my 3rd button even it is there in my database? It's like it being limted to show 2 button only but i checked every code in my program, nothing is limiting everythings is ".count - 1"
Imports System.Data.OleDb
Public Class Services
Dim con = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source = Cypher.mdb;"
Dim cnnOledb As New OleDbConnection
Dim cmdload As New OleDbCommand
Dim cmdInsert As New OleDbCommand
Public categoryName As String
Private Sub Services_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.CenterToScreen()
cnnOledb.ConnectionString = con
cnnOledb.Open()
cmdload.CommandText = "Select * From [Services]"
cmdload.Connection = cnnOledb
Max()
Tab()
add_btn()
End Sub
Private Sub Max()
Dim cmdMax As New OleDbCommand
cmdMax.CommandText = "Select MAX(id) from Services"
cmdMax.Connection = cnnOledb
Try
Dim dr As OleDbDataReader = cmdMax.ExecuteReader()
If dr.Read = True Then
If dr(0).ToString = "" Then
txtID.Text = "1"
Else
txtID.Text = dr(0) + 1.ToString
End If
End If
Catch
MsgBox("Error !")
End Try
End Sub
Private Sub Tab()
cobCategory.Items.Clear()
TabCategory.TabPages.Clear()
Dim cmdCategory As New OleDbCommand
cmdCategory.CommandText = "Select * from Category"
cmdCategory.Connection = cnnOledb
Dim dt As New DataTable
dt.Load(cmdCategory.ExecuteReader)
For i As Integer = 0 To dt.Rows.Count - 1
Dim tab As New TabPage()
tab.Name = "tab" + dt.Rows(i).Item(1).ToString
tab.Text = tab.Name.Remove(0, 3)
cobCategory.Items.Add(dt.Rows(i).Item(1).ToString)
TabCategory.TabPages.Add(tab)
Next
TabCategory.TabPages.Add("+")
End Sub
Private Sub add_btn()
Dim dt As New DataTable
dt.Load(cmdload.ExecuteReader)
Dim myFont As System.Drawing.Font
myFont = New System.Drawing.Font("Century Gothic", 12)
For i As Integer = 0 To dt.Rows.Count - 1
Dim btn As New Button()
btn.Name = "btn" + dt.Rows(i).Item(2).ToString
btn.Text = btn.Name.Remove(0, 3)
btn.Height = 30
btn.Width = 90
btn.Location = New Point(0, 10)
If TabCategory.TabPages((dt.Rows(i).Item(1)) - 1).Controls.count <> 0 Then
btn.Left += 100
End If
btn.Font = myFont
TabCategory.TabPages((dt.Rows(i).Item(1)) - 1).Controls.Add(btn)
Next
End Sub
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
Try
cmdInsert.CommandText = "Insert into [Services] values(" & txtID.Text & ", " & cobCategory.SelectedIndex + 1 & ", '" & txtServices.Text & "', " & txtDur.Text & ", " & txtPrices.Text & ");"
cmdInsert.CommandType = CommandType.Text
cmdInsert.Connection = cnnOledb
cmdInsert.ExecuteNonQuery()
Catch ex As Exception
MsgBox("Fail to insert data")
End Try
End Sub
Private Sub TabCategory_Click(sender As Object, e As EventArgs) Handles TabCategory.Click
If TabCategory.SelectedTab Is TabCategory.TabPages(TabCategory.TabPages.Count - 1) Then
New_Category.ShowDialog()
End If
End Sub
Public Sub New_Cate()
Dim cmdMax As New OleDbCommand
cmdMax.CommandText = "Select MAX(ID) from Category"
cmdMax.Connection = cnnOledb
Dim ID As Integer
Try
Dim dr As OleDbDataReader = cmdMax.ExecuteReader()
If dr.Read = True Then
If dr(0).ToString = "" Then
ID = 1
Else
ID = dr(0) + 1
End If
End If
Catch
MsgBox("Error !")
End Try
Dim cmdAddCategory As New OleDbCommand
Try
cmdAddCategory.CommandText = "Insert into [Category] values(" & ID & ", '" & categoryName & "');"
cmdAddCategory.CommandType = CommandType.Text
cmdAddCategory.Connection = cnnOledb
cmdAddCategory.ExecuteNonQuery()
Catch ex As Exception
MsgBox("Fail to insert new category")
End Try
Tab()
End Sub
End Class
The button is there, it's behind the second button. Your code initially places the button at x = 0, then when Tabpage.controls.count > 0, it adds 100. So every button after the first button is at x = 100.
Change this:
btn.Location = New Point(0, 10)
If TabCategory.TabPages((dt.Rows(i).Item(1)) - 1).Controls.count <> 0 Then
btn.Left += 100
End If
To this so it's + 100 to the right of the last button:
btn.Location = New Point(0, 10)
If TabCategory.TabPages((dt.Rows(i).Item(1)) - 1).Controls.count <> 0 Then
btn.Left += TabCategory.TabPages((dt.Rows(i).Item(1)) - 1).Controls(TabCategory.TabPages((dt.Rows(i).Item(1)) - 1).Controls.Count - 1).Left + 100
End If

how to show description when an array combobox is selected

How can i use a handle in this dim as list of i need to handle the newpritemnobox .That is when i choose from newpritemnobox combobox the contain of podesc in certain choose of newpritemnobox will show
Public Class POfrm
Dim newpritemnobox As New List(Of ComboBox)
Dim newpodescbox As New List(Of RichTextBox)
Private Sub controlall(ByVal controlcount As Integer)
Dim boxpritemno As ComboBox
Dim boxpodesc As RichTextBox
For i As Integer = 1 To controlcount
boxpritemno = New ComboBox
boxpritemno.Size = New Drawing.Size(51, 21)
boxpritemno.Location = New Drawing.Point(89, 542 + 58 * (i - 1))
newpritemnobox.Add(boxpritemno)
Me.Controls.Add(boxpritemno)
Next
For i As Integer = 1 To controlcount
boxpodesc = New RichTextBox
boxpodesc.Size = New Drawing.Size(442, 45)
boxpodesc.Location = New Drawing.Point(323, 542 + 58 * (i - 1))
newpodescbox.Add(boxpodesc)
Me.Controls.Add(boxpodesc)
Next
End Sub
Private Sub poitemno_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles poitemno.Click
Dim msgboxresponse As MsgBoxResult
msgboxresponse = MsgBox("Are You Sure of the number of Item you choose?Please Check Again", _
MsgBoxStyle.Question + MsgBoxStyle.YesNo, Me.Text)
If msgboxresponse <> MsgBoxResult.Yes Then
Else
controlall(Val(txtpoitemno.Text))
txtpoitemno.Enabled = False
poitemno.Enabled = False
loadtrypritemno()
Return
End If
End Sub
I guess this is my code for it but it neither show error nor working
Private Sub boxpounitprice_SelectedIndexChanged(ByRef boxpritemno As ComboBox)
datab = "Select pritemno from prpo where pritemno = '" & boxpritemno.Text & "'"
connDB()
cmd = New OleDbCommand(datab, conn)
Dim result As Object
result = cmd.ExecuteScalar()
If result IsNot Nothing Then
boxpoqty.Text = result.ToString()
End If
End Sub
Private Sub loadtrypritemno()
Dim controlall As Integer = Val(txtpoitemno.Text)
'start from 0 because it's 0-based index
For i As Integer = 0 To controlall - 1
' addbuyer(Label(i), itemcode(i), boxes(i), qty(i), combo(i), statusboxes(i), Remarksboxes(i))
boxpounitprice_SelectedIndexChanged(newpritemnobox(i))
AddHandler newpritemnobox(i).SelectedIndexChanged, AddressOf boxpounitprice_SelectedIndexChanged
Next
End Sub
Private Sub boxpounitprice_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)
Dim tb As ComboBox = CType(sender, ComboBox)
tb.SelectAll()
MsgBox()
End Sub
'Private Sub loadamounttext()
' ' addpo()
'End Sub
Private Sub loadprinaccountcode()
Dim datab4 As String
Dim cmd4 As OleDbCommand
Try
Dim ST As String = cmbprno.SelectedText
End Sub
Private Sub loadpritem(ByRef boxpritemno As ComboBox)
Try
datab = "Select pritemno from prpo where prno = '" & cmbprno.Text & "'"
connDB()
cmd = New OleDbCommand(datab, conn)
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
boxpritemno.Items.Clear()
Do While dr.Read = True
' txtdepartadd.Items.Add(dr("Departmentname"))
boxpritemno.Items.Add(dr(0))
Loop
Catch ex As Exception
MsgBox(ex.Message)
Finally
cmd.Dispose()
conn.Close()
End Try
End Sub
End Class
Private Sub boxty()
Dim controlall As Integer = Val(txtpoitemno.Text)
For i As Integer = 0 To controlall - 1
boxpounitprice_SelectedIndexChanged(newpritemnobox(i), newpoqtybox(i))
Next
End Sub
Private Sub boxpounitprice_SelectedIndexChanged(ByRef boxpritemno As ComboBox, ByRef boxpoqty As TextBox)
AddHandler boxpritemno.SelectedIndexChanged, AddressOf boxpritemno_selectedindex
End Sub
Private Sub boxtrytry(ByVal boxpritemno As ComboBox, ByRef boxpoqty As TextBox, ByRef boxpounit As ComboBox, ByRef boxpodesc As RichTextBox)
Dim datab1 As String
Dim cmd1 As OleDbCommand
Dim datab2 As String
Dim cmd2 As OleDbCommand
Try
datab = "Select prqty from prpo where pritemno = '" & boxpritemno.Text & "' and prno = '" & cmbprno.Text & "'"
connDB()
cmd = New OleDbCommand(datab, conn)
Dim result As Object
result = cmd.ExecuteScalar()
If result IsNot Nothing Then
' txtendorsedby.Text = result.ToString()
boxpoqty.Text = result.ToString()
End If
datab1 = "Select pruom from prpo where pritemno = '" & boxpritemno.Text & "' and prno = '" & cmbprno.Text & "'"
connDB()
cmd1 = New OleDbCommand(datab1, conn)
Dim result1 As Object
result1 = cmd1.ExecuteScalar()
If result1 IsNot Nothing Then
' txtendorsedby.Text = result.ToString()
boxpounit.Text = result1.ToString()
End If
datab2 = "Select prdesc from prpo where pritemno = '" & boxpritemno.Text & "' and prno = '" & cmbprno.Text & "'"
connDB()
cmd2 = New OleDbCommand(datab, conn)
Dim result2 As Object
result2 = cmd2.ExecuteScalar()
If result2 IsNot Nothing Then
' txtendorsedby.Text = result.ToString()
boxpodesc.Text = result2.ToString()
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
cmd.Dispose()
conn.Close()
End Try
End Sub
Private Sub loadtrypritemno()
' MessageBox.Show("right")
Dim controlall As Integer = Val(txtpoitemno.Text)
For i As Integer = 0 To controlall - 1
boxtrytry(newpritemnobox(i), newpoqtybox(i), newpounitbox(i), newpodescbox(i))
Next
End Sub

VB: How to bind a DataTable to a DataGridView?

I know this is a basic question that has already been answered thousand times, but I can't make it work.
I am working in Visual Studio 2010 and have two forms in my Windows Application. In the first one (Main.vb), the user enters his inputs and the calculation takes place. In the second one (DataAnalysis.vb) the calculation results are displayed.
In Main.vb, I create the temp table that will contains all the intermediary calculation steps:
Dim tableTempJDL As DataTable = New DataTable("TempJDL")
Dim column As DataColumn
column = New DataColumn("ID", GetType(System.Int32))
tableTempJDL.Columns.Add(column)
column = New DataColumn("PthObjekt", GetType(System.Double))
tableTempJDL.Columns.Add(column)
'further columns are after created using the same method
Then, in DataAnalysis.vb, I try to display the DataTable tableTempJDL into the DataGridViewBerechnung:
Public bindingSourceBerechnung As New BindingSource()
Me.DataGridViewBerechnung.DataSource = Me.bindingSourceBerechnung
But then I don't understand how to fill the DataGridView...
Simply, you can make your table as the datasource of bindingsource in following way:
Me.bindingSourceBerechnung .DataSource = tableTempJDL
Later on, you can bind above binding source in your datagridview in following way:
Me.DataGridViewBerechnung.DataSource = Me.bindingSourceBerechnung
Public Class Form1
Dim CON As New SqlConnection
Dim CMD As New SqlCommand
Dim dt As New DataTable
Public Sub DbConnect()
If CON.State = ConnectionState.Open Then DbClose()
CON.ConnectionString = "Data Source = yourservername;Initial Catalog=your database name;Integrated Security=True"
CON.Open()
End Sub
Public Sub DbClose()
CON.Close()
CON.Dispose()
End Sub
Public Sub enabletext()
TextBox1.Enabled = True
End Sub
Public Sub CLEARFEILDS()
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
TextBox4.Clear()
ComboBox1.DataSource = Nothing
ComboBox1.SelectedIndex = 0
DataGridView2.Rows.Clear()
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ComboBox1.Select()
TextBox4.Enabled = False
DataGridView1.Visible = False
TextBox5.Visible = False
'AUTOSEACH()
DbConnect()
Dim SELECTQUERY As String = "SELECT PROD_CODE FROM TBLPRODUCT"
Dim MYCOMMAND As New SqlCommand(SELECTQUERY, CON)
Dim MYREADER As SqlClient.SqlDataReader
MYREADER = MYCOMMAND.ExecuteReader
Prod_Code.Items.Clear()
While MYREADER.Read
Prod_Code.Items.Add(MYREADER("PROD_CODE"))
End While
DbClose()
End Sub
Public Function InvCodeGen(ByVal CurrCode As String) As String
Dim RightSix As String = Microsoft.VisualBasic.Right(Trim(CurrCode), 3)
Dim AddValue As Integer = Microsoft.VisualBasic.Val(RightSix) + 1
Dim RetValue As String
If Microsoft.VisualBasic.Len(AddValue.ToString) = 1 Then
RetValue = "00" + AddValue.ToString
ElseIf (Microsoft.VisualBasic.Len(AddValue.ToString) = 2) Then
RetValue = "000" + AddValue.ToString
Else
RetValue = AddValue.ToString
End If
Return RetValue
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
CreateNewCode()
TextBox1.Enabled = False
DataGridView1.Visible = False
TextBox5.Visible = False
ComboBox1.Visible = True
AddCustomer()
'GridView2Load(GetDataGridView2())
End Sub
Private Sub CreateNewCode()
Dim CurrCode As String = ""
'Dim NewCode As String = "INV"
Dim NewCode As Integer
Dim mySelectQuery As String = "SELECT MAX(INV_NO) AS INVNO FROM TBLINV_HEADER"
Dim myCommand As New SqlClient.SqlCommand(mySelectQuery, CON)
myCommand.CommandType = CommandType.Text
Dim myReader As SqlClient.SqlDataReader
DbConnect()
myReader = myCommand.ExecuteReader()
Do While myReader.Read()
If IsDBNull(myReader("INVNO")) Then
myReader.Close()
Dim myNewYearQuery As String = "SELECT MAX(INV_NO) AS INVNO FROM TBLINV_HEADER"
Dim myNewYearCommand As New SqlClient.SqlCommand(myNewYearQuery, CON)
myNewYearCommand.CommandType = CommandType.Text
Dim myNewYearReader As SqlClient.SqlDataReader
myNewYearReader = myNewYearCommand.ExecuteReader()
Do While myNewYearReader.Read()
CurrCode = Trim(myNewYearReader("INVNO").ToString)
Loop
myNewYearReader.Close()
Exit Do
Else
CurrCode = Trim(myReader("INVNO").ToString)
myReader.Close()
Exit Do
End If
Loop
DbClose()
NewCode = Trim(InvCodeGen(CurrCode))
TextBox1.Text = CInt(NewCode)
End Sub
Private Sub AddCustomer()
Dim dsCusCode As New DataSet
dsCusCode.Reset()
ComboBox1.Items.Clear()
Dim myCusCodeQuery As String = "SELECT CUST_CODE as Custcode FROM TBLCUSTOMER"
Dim daCusCode As New SqlClient.SqlDataAdapter(myCusCodeQuery, CON)
DbConnect()
daCusCode.Fill(dsCusCode, "TBLCUSTOMER")
DbClose()
Dim x As Integer
For x = 0 To dsCusCode.Tables(0).Rows.Count - 1
ComboBox1.Items.Add(dsCusCode.Tables(0).Rows(x).Item("Custcode").ToString)
'TextBox3.Text = dsCusCode.Tables(0).Rows(x).Item("custname").ToString
Next
ComboBox1.SelectedIndex = -1
x = Nothing
myCusCodeQuery = Nothing
dsCusCode.Dispose()
daCusCode.Dispose()
dsCusCode = Nothing
dsCusCode = Nothing
End Sub
Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
Dim Code As String
Code = ComboBox1.Text
Dim dsCode As New DataSet
dsCode.Reset()
Dim myCodeQuery As String = "SELECT cust_name as custname, cust_add1 as custadd FROM TBLCUSTOMER where Cust_Code = '" & Code & "'"
Dim daCode As New SqlClient.SqlDataAdapter(myCodeQuery, CON)
DbConnect()
daCode.Fill(dsCode, "TBLCUSTOMER")
DbClose()
TextBox2.Text = dsCode.Tables(0).Rows(0).Item("custname").ToString
TextBox3.Text = dsCode.Tables(0).Rows(0).Item("custadd").ToString
myCodeQuery = Nothing
dsCode.Dispose()
daCode.Dispose()
dsCode = Nothing
dsCode = Nothing
End Sub
Private Sub Button8_Click(sender As Object, e As EventArgs) Handles Button8.Click
For I As Integer = 0 To DataGridView2.Rows.Count - 1
Dim MYQUERY As String = "SELECT PROD_DESC , PROD_PRICE FROM TBLPRODUCT WHERE PROD_CODE='" & DataGridView2.Rows(I).Cells(1).Value & "'"
Dim MYCOMMAND As New SqlCommand(MYQUERY, CON)
DbConnect()
Dim MYREADER As SqlClient.SqlDataReader
MYREADER = MYCOMMAND.ExecuteReader
If MYREADER.Read() Then
DataGridView2.Rows(I).Cells(2).Value = MYREADER("PROD_DESC")
DataGridView2.Rows(I).Cells(3).Value = MYREADER("PROD_PRICE")
End If
DbClose()
Next
End Sub
Private Sub DataGridView2_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs) Handles DataGridView2.CellFormatting
DataGridView2.Rows(e.RowIndex).Cells(0).Value = CInt(e.RowIndex + 1)
End Sub
Private Sub DataGridView2_CellEndEdit(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView2.CellEndEdit
For I As Integer = 0 To DataGridView2.Rows.Count - 1
Dim QTY As Double = DataGridView2.Rows(I).Cells(4).Value
Dim PRICE As Double = DataGridView2.Rows(I).Cells(3).Value
Dim AMOUNT As Double = QTY * PRICE
DataGridView2.Rows(I).Cells(5).Value = AMOUNT
Next
' SUM OF AMOUNT TOTAL
Dim COLSUM As Decimal = 0
For Each ROW As DataGridViewRow In DataGridView2.Rows
If Not IsDBNull(ROW.Cells(5).Value) Then
COLSUM += ROW.Cells(5).Value
End If
Next
TextBox4.Text = COLSUM
End Sub
'SAVE
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
If MsgBox("Are you sure want to save this record?", vbYesNo + vbQuestion) = vbYes Then
updateinvheader()
updategridvalue()
CLEARFEILDS()
End If
End Sub
Private Sub updateinvheader()
Dim insertquery1 As String = "insert into TBLINV_HEADER(inv_no,inv_date,inv_cust) values(#inv_no,#inv_date,#inv_cust)"
Dim command As New SqlCommand(insertquery1, CON)
command.Parameters.AddWithValue("#inv_no", TextBox1.Text)
command.Parameters.AddWithValue("#inv_date", DateTime.Now)
command.Parameters.AddWithValue("#inv_cust", ComboBox1.Text)
DbConnect()
command.ExecuteNonQuery()
DbClose()
End Sub
Private Sub updategridvalue()
Dim i As Integer
Dim insertquery2 As String = "insert into TBLINV_detail(inv_lno,inv_no,inv_prod,inv_qty,inv_Price) values(#inv_lno,#inv_no,#inv_prod,#inv_qty,#inv_Price)"
Dim command As New SqlCommand(insertquery2, CON)
For i = 0 To DataGridView2.RowCount - 1
If DataGridView2.Rows(i).Cells(1).Value = "" Then
GoTo 100
Else
command.Parameters.AddWithValue("#inv_lno", DataGridView2.Rows(i).Cells(0).RowIndex + 1)
'command.Parameters.AddWithValue("#inv_lno", DataGridView2.Rows(i).Cells(0).)
command.Parameters.AddWithValue("#inv_no", TextBox1.Text)
command.Parameters.AddWithValue("#inv_prod", DataGridView2.Rows(i).Cells(1).Value)
command.Parameters.AddWithValue("#inv_qty", DataGridView2.Rows(i).Cells(4).Value)
command.Parameters.AddWithValue("#inv_Price", DataGridView2.Rows(i).Cells(3).Value)
End If
DbConnect()
command.ExecuteNonQuery()
DbClose()
100: command.Parameters.Clear()
Next
MsgBox("data saved successfuly")
End Sub
Private Sub Button9_Click(sender As Object, e As EventArgs) Handles Button9.Click
DataGridView1.Visible = True
TextBox5.Visible = True
ComboBox1.Visible = False
DbConnect()
Dim MYQUERY As String = "Select * FROM TBLCUSTOMER" &
" INNER Join TBLINV_HEADER ON TBLINV_HEADER.INV_CUST = TBLCUSTOMER.CUST_CODE" &
" WHERE TBLINV_HEADER.INV_NO ='" & TextBox1.Text & "'"
Dim CMD As New SqlCommand(MYQUERY, CON)
Dim DA As New SqlDataAdapter
DA.SelectCommand = CMD
Dim DT As New DataTable
DA.Fill(DT)
If DT.Rows.Count > 0 Then
MsgBox(DT.Rows(0)(1).ToString())
'ComboBox1.Text = DT.Rows(0)(1).ToString()
ComboBox1.Visible = False
TextBox5.Text = DT.Rows(0)(1).ToString()
TextBox2.Text = DT.Rows(0)(2).ToString()
TextBox3.Text = DT.Rows(0)(3).ToString()
End If
DbClose()
DataGridView1.DataSource = GETPRODUCTDETAILS()
End Sub
Private Function GETPRODUCTDETAILS() As DataTable
Dim PRODUCTDET As New DataTable
DbConnect()
Dim MYQUERY As String = " SELECT TBLINV_DETAIL.INV_LNO, TBLINV_DETAIL.INV_PROD, TBLPRODUCT.PROD_DESC, TBLINV_DETAIL.INV_PRICE, TBLINV_DETAIL.INV_QTY, (TBLINV_DETAIL.INV_QTY*TBLINV_DETAIL.INV_PRICE) AS AMOUNT FROM TBLINV_DETAIL " &
" INNER JOIN TBLPRODUCT On TBLPRODUCT.PROD_CODE = TBLINV_DETAIL.INV_PROD " &
" WHERE TBLINV_DETAIL.INV_NO='" & TextBox1.Text & "'"
Dim CMD As New SqlCommand(MYQUERY, CON)
Dim READER As SqlDataReader = CMD.ExecuteReader()
PRODUCTDET.Load(READER)
DbClose()
Return PRODUCTDET
End Function
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim DELETEQUERY As String = "DELETE FROM TBLINV_DETAIL WHERE TBLINV_DETAIL.INV_NO= '" & TextBox1.Text & "'"
Dim DELETEQUERY2 As String = "DELETE FROM TBLINV_HEADER WHERE TBLINV_HEADER.INV_NO= '" & TextBox1.Text & "'"
Dim CMD As New SqlCommand(DELETEQUERY, CON)
Dim CMD2 As New SqlCommand(DELETEQUERY2, CON)
DbConnect()
CMD.ExecuteNonQuery()
CMD2.ExecuteNonQuery()
DbClose()
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
TextBox4.Clear()
ComboBox1.DataSource = Nothing
DataGridView1.DataSource = Nothing
MsgBox("DATA DELETED SUCCESSFULLY")
End Sub
End Class