Adding data to a data table from textbox user input - vb.net

When I run the project I add values into my textboxes that I want to go into the datatable but it doesn't have the newly inputted data from the textboxes or the new row when I check it out. Anyone know what I'm missing that puts in the data into my datatable? this is my sample code:
Dim lineTable As Data.DataTable = New Data.DataTable("NAFTALineItems")
lineTable.Columns.Add("NAFTAID")
lineTable.Columns.Add("NAFTALineID")
lineTable.Columns.Add("BoxQuantity")
lineTable.Columns.Add("Weight")
lineTable.Columns.Add("PartNumber")
lineTable.Columns.Add("PartDescription")
lineTable.Columns.Add("QuantityShipped")
lineTable.Columns.Add("UnitPrice")
lineTable.Columns.Add("TotalPrice")
Dim lineRow As DataRow = lineTable.NewRow()
lineRow("NAFTAID") = txtNaftaID.Text
lineRow("NAFTALineID") = txtLineID.Text
lineRow("BoxQuantity") = txtQuantity.Text
lineRow("Weight") = txtWeight.Text
lineRow("PartNumber") = txtPartNumber.Text
lineRow("PartDescription") = txtPartDescription.Text
lineRow("QuantityShipped") = txtQtyShipped.Text
lineRow("UnitPrice") = txtPrice.Text
lineRow("TotalPrice") = txtQtyShipped.Text * txtPrice.Text

Related

DataGridView moves rows to bottom when cell is updated with Unbound data

I have a DataGridView that is styled with code and is using data from a SQLite Database
The Database is NOT bound to the DataGridView. A number of events are triggered when I click on a row.
First the Database is updated with today's date.
And the cell that contain's that date reflects the change.
I then call a sort on the column based on the cells value. With this code
dgvLinks.Sort(dgvLinks.Columns(3), ListSortDirection.Ascending)
The process works as expected with no issues IF I omit these lines of code from the Sub Routine ViewSearches() that populates the DataGridView.
If rowCount <= 25 Then
maxRowCount = 25 - rowCount
For iA = 1 To maxRowCount
dgvLinks.Rows.Add(" ")
Next
End If
I can use these empty rows if I make a call to repopulate the DataGridView with ViewSearches()
I am trying to avoid this design as it seems like a over use of resource.
The ERROR that is happening is the 4 rows that contain data are moved to the bottom of the DataGridView and above these 4 rows with data are the empty rows. I will post the relevant code below.
My question How can I keep the empty rows and populate DataGridView so the rows with data are at the top of the DataGridView?
Here is a Screen Shot after I selected LID 2. It is updated and bubbled to the bottom of the DGV.
Private Sub ViewSearches()
Dim intID As Integer
Dim strChannelName As String
Dim strLinkAddress As String
Dim strLastVisit As String
Dim strLinkType As String
Dim rowCount As Integer
Dim maxRowCount As Integer
'Dim emptyStr As String = " "
Using conn As New SQLiteConnection($"Data Source = '{gv_dbName}';Version=3;")
conn.Open()
Using cmd As New SQLiteCommand("", conn)
'cmd.CommandText = "SELECT * FROM LinkTable"
' Line of CODE Above works with If statement in While rdr
'==========================================================
'cmd.CommandText = "SELECT * FROM LinkTable WHERE ytSiteType = 'News'"
cmd.CommandText = "SELECT * FROM LinkTable WHERE ytSiteType = #site"
cmd.Parameters.Add("#site", DbType.String).Value = gvSLT
Using rdr As SQLite.SQLiteDataReader = cmd.ExecuteReader
'dgvLinks.DataSource = rdr
'Statement Above use when DB is bound to dgvLinks
'=================================================
While rdr.Read()
intID = CInt((rdr("LID")))
strChannelName = rdr("ytChannelName").ToString
strLinkAddress = rdr("ytLinkAddress").ToString
strLastVisit = rdr("ytLastVisit").ToString
strLinkType = rdr("ytSiteType").ToString
'If strLinkType = gvSLT Then
dgvLinks.Rows.Add(intID, strChannelName, strLinkAddress, strLastVisit)
rowCount = rowCount + 1
'End If
End While
dgvLinks.Sort(dgvLinks.Columns(3), ListSortDirection.Ascending)
End Using
If rowCount <= 25 Then
maxRowCount = 25 - rowCount
For iA = 1 To maxRowCount
dgvLinks.Rows.Add(" ")
Next
End If
End Using
End Using
'FindEmpty()
End Sub
Click Event with Update to Database
Private Sub dgvLinks_CellClick(sender As System.Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvLinks.CellClick
selRow = e.RowIndex
If e.RowIndex = -1 Then
gvalertType = "4"
frmAlert.ShowDialog()
Exit Sub
End If
'Dim col As DataGridViewColumn = Me.dgvLinks.Columns(e.ColumnIndex)
Dim row As DataGridViewRow = Me.dgvLinks.Rows(e.RowIndex)
If row.Cells(2).Value Is Nothing Then
gvalertType = "5"
frmAlert.ShowDialog()
Return
Exit Sub
ElseIf gvTxType = "View" Then
webPAGE = row.Cells(2).Value.ToString()
siteID = CInt(row.Cells(0).Value.ToString())
UpdateSiteData()
''MsgBox("Stop " & selRow)
'dgvLinks.ClearSelection()
'dgvLinks.Refresh()
'dgvLinks.RefreshEdit()
Process.Start(webPAGE)
'dgvLinks.Columns.Clear()
''dgvLinks.Rows.Clear()
''ViewSearches()
ElseIf gvTxType = "Delete" Or gvTxType = "Update" Then
gvID = CInt(row.Cells(0).Value)
gvSiteName = row.Cells(1).Value.ToString
gvSiteURL = row.Cells(2).Value.ToString
frmADE.Show()
Close()
End If
End Sub
Update Routine
Public Sub UpdateSiteData()
Dim dateToday = Date.Today
dateToday = CDate(CDate(Date.Today).ToString("M-d-yyyy"))
Using conn As New SQLiteConnection($"Data Source = '{gv_dbName}';Version=3;"),
cmd As New SQLiteCommand("UPDATE LinkTable SET ytLastVisit = #ytLastVisit WHERE LID =" & siteID, conn)
conn.Open()
cmd.Parameters.Add("#ytLastVisit", DbType.String).Value = dateToday.ToString("M-d-yyyy")
cmd.ExecuteNonQuery()
dgvLinks.Rows(selRow).Cells(3).Value = dateToday.ToString("M-d-yyyy")
'Line of code above INSERTS value in Last Visit Column at the correct ROW
'NOT needed if you reload data from the database
'=========================================================================
'dgvLinks.Refresh()
'dgvLinks.RefreshEdit()
dgvLinks.Sort(dgvLinks.Columns(3), ListSortDirection.Ascending)
End Using
End Sub
You will see a number of things I have tried commented out.
As I said I can FIX the issue if I make a call to the ViewSearches() Sub Routine.
Private Sub StyleDGV()
'Sets Design of the DataGridView
'===============================
dgvLinks.DefaultCellStyle.Font = New Font("Times New Roman", 13.0F, FontStyle.Bold)
dgvLinks.ColumnCount = 4
dgvLinks.Columns(0).Width = 60 'ID
dgvLinks.Columns(1).Width = 325 'Site Name 325
dgvLinks.Columns(2).Width = 860 'Site Url 860
dgvLinks.Columns(3).Width = 154 'LastVisit 140
'Option with no blank rows increase col count to 5
'OR increase width of col(3) WHY? because the scroll bar is not showing
' TOTAL Width 1450 Height 488
'=============================
'To Set Col Header Size Mode = Enabled
'To Set Col Header Default Cell Styles DO in Properties
'dgvLinks.Columns(6).DefaultCellStyle.Format = "c"
dgvLinks.ColumnHeadersHeight = 10 'Sans Serif 'Tahoma
dgvLinks.ColumnHeadersDefaultCellStyle.Font = New Font("Sans Serif", 12.0F, FontStyle.Bold)
dgvLinks.ColumnHeadersDefaultCellStyle.ForeColor = Color.Blue
dgvLinks.DefaultCellStyle.BackColor = Color.LightGoldenrodYellow
'DGV Header Names
dgvLinks.Columns(0).Name = "LID"
dgvLinks.Columns(1).Name = "Site Name"
dgvLinks.Columns(2).Name = "Site URL"
dgvLinks.Columns(3).Name = "Last Visit"
dgvLinks.Columns(0).SortMode = DataGridViewColumnSortMode.NotSortable
dgvLinks.Columns(1).SortMode = DataGridViewColumnSortMode.NotSortable
dgvLinks.Columns(2).SortMode = DataGridViewColumnSortMode.NotSortable
dgvLinks.Columns(3).SortMode = DataGridViewColumnSortMode.NotSortable
End Sub
Any one following this question the FIX that permitted keeping the empty rows was to just omit the sort command in the Update to Database Sub Routine
As far as getting the data from the SQLite DB into the grid… you almost have it in the ViewSearches method. The command text looks good; however you are using an SQLiteDataReader. This is resorting to reading the data line by line.
I suggest you use the SQLiteDataAdapter instead. With it you can get the DataTable from the DB in one shot. First create and initialize a DataSet, then create a new SQLiteDataAdapter then add your command to the data adapter something like…
DataSet ds = new DataSet();
using (SQLiteDataAdapter sqlDA = new SQLiteDataAdapter()) {
conn.Open();
sqlDA.SelectCommand = cmd.CommanText;
sqlDA.Fill(ds, “tableName”);
if (ds.Tables.Count > 0) {
//return ds.Tables[“tableName”];
dgvLinks.DataSource = ds.Tables[“tableName”];
}
}
This will add a DataTable to the DataSet ds called “tableName” if the query succeeded.
Then simply use that DataTable as a DataSource to the grid… something like…
dgvLinks.DataSource = ds.Tables[“tableName”];

vb.net - adding a picture box programmatically to a tablelayoutpanel

morning all,
i'm programmatically pulling rows from a db and listing them in my vb.net app like so...
Dim linkurl As String = ""
Dim linkdescription As String = ""
Dim adapter As MySqlDataAdapter
Dim hyperlinkresultstable As DataTable
cn.ConnectionString = connection_string
Dim commandtext As String
commandtext = "Select * from mytable where username = '" & "' and type='HYPERLINK';"
adapter = New MySqlDataAdapter(commandtext, cn)
hyperlinkresultstable = New DataTable
adapter.Fill(hyperlinkresultstable)
For Each row As DataRow In hyperlinkresultstable.Rows
linkurl = row.Item("value")
linkdescription = row.Item("description")
quicklinks_layout.RowStyles.Add(New RowStyle(SizeType.AutoSize))
quicklinks_layout.RowCount += 1
quicklinks_layout.Controls.Add(New PictureBox(), 0, quicklinks_layout.RowCount - 1)
quicklinks_layout.Controls.Add(New LinkLabel(), 1, quicklinks_layout.RowCount - 1)
Next row
I've never worked in this way before and I've not got a single idea on how to set the 'image' property of the Picturebox added.
I also need to be able to set the text value, tooltip value and mouseclick event of the linklabel based on the current row's linkurl and link description aswell.
Any advice or direction is appreciated! Thanks as always!! :)

Syntax error at UPDATE VB - when saving info to access

I have a windows form with various textboxes and 1 label, the label Identifies my ID in my database, I essentially want to search find the record using the label (ID) and then update the row with the data in the textboxes.
I get syntax error when I carry out ds.update(da)
any ideas? I have no idea what it is holding me back I am assuming it is something silly.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim ds As New DataTable
Dim da As OleDb.OleDbDataAdapter
Dim sql As String
Dim connString As String = ConfigurationManager.ConnectionStrings("dbx").ConnectionString
Dim conn As New OleDb.OleDbConnection(connString)
sql = "SELECT * FROM [STG] WHERE [ID] like '" & Label15.Text & "%'" 'LABEL 15 CONTAINS DATABASE ID
da = New OleDbDataAdapter(sql, conn)
ds = New DataTable
conn.Open()
da.Fill(ds)
'conn.Close()
Dim cb As New OleDb.OleDbCommandBuilder(da)
ds.Rows(0).Item(1) = KKSTextbox.Text
ds.Rows(0).Item(1) = KKSTextbox.Text 'DATA I WISH TO STORE IN MY DATABASE
ds.Rows(0).Item(2) = TypeTextbox.Text
ds.Rows(0).Item(3) = RangeTextBox.Text
ds.Rows(0).Item(4) = CompDescTextbox.Text
ds.Rows(0).Item(5) = LRTextBox.Text
ds.Rows(0).Item(6) = FuncLocTextbox.Text
ds.Rows(0).Item(7) = LocTextbox.Text
ds.Rows(0).Item(8) = MANTextBox.Text
ds.Rows(0).Item(9) = PTNOTextBox.Text
ds.Rows(0).Item(10) = SUPPTextBox.Text
ds.Rows(0).Item(11) = DetailTextBox.Text
ds.Rows(0).Item(12) = PIDTextBox.Text
ds.Rows(0).Item(13) = CONNTextBox.Text
ds.Rows(0).Item(14) = BLOCKTextBox.Text
ds.Rows(0).Item(15) = OMTextBox.Text
ds.Rows(0).Item(16) = AL1TextBox.Text
ds.Rows(0).Item(17) = AL2TextBox.Text
ds.Rows(0).Item(18) = AL3TextBox.Text
ds.Rows(0).Item(19) = AL4TextBox.Text
ds.Rows(0).Item(20) = AL5TextBox.Text
ds.Rows(0).Item(21) = AL6TextBox.Text
ds.Rows(0).Item(22) = AL7TextBox.Text
ds.Rows(0).Item(23) = AL8TextBox.Text
ds.Rows(0).Item(24) = AL9TextBox.Text
ds.Rows(0).Item(25) = AL10TextBox.Text
ds.Rows(0).Item(26) = EFF1TextBox.Text
ds.Rows(0).Item(27) = EFF2TextBox.Text
ds.Rows(0).Item(28) = EFF3TextBox.Text
ds.Rows(0).Item(29) = EFF4TextBox.Text
ds.Rows(0).Item(30) = EFF5TextBox.Text
ds.Rows(0).Item(31) = EFF6TextBox.Text
ds.Rows(0).Item(32) = EFF7TextBox.Text
ds.Rows(0).Item(33) = EFF8TextBox.Text
ds.Rows(0).Item(34) = EFF9TextBox.Text
ds.Rows(0).Item(35) = EFF10TextBox.Text
ds.Rows(0).Item(36) = SET1TextBox.Text
ds.Rows(0).Item(37) = SET2TextBox.Text
ds.Rows(0).Item(38) = SET3TextBox.Text
ds.Rows(0).Item(39) = SET4TextBox.Text
ds.Rows(0).Item(40) = SET5TextBox.Text
ds.Rows(0).Item(41) = SET6TextBox.Text
ds.Rows(0).Item(42) = SET7TextBox.Text
ds.Rows(0).Item(43) = SET8TextBox.Text
ds.Rows(0).Item(44) = SET9TextBox.Text
ds.Rows(0).Item(45) = SET10TextBox.Text
da.Update(ds)
'da.Dispose() 'I get syntax here
conn.Close()
End Sub
Do use the command builder after the fill
Dim row As DataRow = ds.NewRow
'set all the values for row like row("columnName") = value
ds.Rows.Add(row)
da.Update(ds)
First you need to get a reference to a new row. Then set the values. Then add the new row to the DataTable and finally do the update

How do I loop through the rows in a Dataview in vb.net

I need to loop through the rows in a DataView so I can get the data or object from the row to add to a listbox. Here is my code for the DataView. The RowFilter is set to only extract the data for a row if the ID that the user entered matches the "CustomerID" field. How do I loop through the Rows that have been added to create a temporary object for the data in the row?
'create new table for storing incident data
Dim incidentTable As DataView = CType(incidentsDataSource.Select(
DataSourceSelectArguments.Empty), DataView)
incidentTable.RowFilter = ("CustomerID = '" & custIDTextBox.Text & "'")
Dim incidentRow As DataRowView = incidentTable(0)
'declare temporary incident and store all data in corresponding fields
Dim incident As New Incident
With incident
.IncidentID = incidentRow("IncidentID").ToString
.CustomerID = incidentRow("CustomerID").ToString
.ProductCode = incidentRow("ProductCode").ToString
.TechID = incidentRow("TechID").ToString
.DateOpened = incidentRow("DateOpened").ToString
.DateClosed = incidentRow("DateClosed").ToString
.Title = incidentRow("Title").ToString
End With
The DataView itself IS a list; a list of DataRowView objects to be precise. You simply loop through the DataView itself, e.g.
For Each row As DataRowView In myDataView
Dim name = CStr(row("Name"))
'...
Next

vb.net - button.text not aligning when pulled from data table

Please refer to the images below:
So the left image has a hardcoded string and the image on the right has the data pulled in form an MSSQL database.
The code below makes up these buttons (they are dynamically created based on the amount of records in the database table)
'Button
Private Sub LoadUseraccount()
'Connect to Database (from module1)
connectSQL()
'Setup DataAdapter with query
Dim da As SqlDataAdapter
da = New SqlDataAdapter("SELECT * from useraccounts", SQLConn)
'Store results in temporary datatable
Dim dt As DataTable
dt = New DataTable()
da.Fill(dt)
Dim i As Integer
'Create a button for every record shown in useraccount table.
For i = 0 To dt.Rows.Count - 1
Dim dr As DataRow = dt.Rows(i)
Dim newbutton As New Windows.Forms.Button
Dim dataString As String = CStr(dr.Item("username"))
newbutton.Name = "btnButton" & i
newbutton.Text = dataString '<========= This Line is where the button text is set
newbutton.Top = 200 + i * 105
newbutton.Left = 40
newbutton.TextAlign = ContentAlignment.MiddleCenter
newbutton.Height = 107
newbutton.Width = 180
Dim myFont As System.Drawing.Font
myFont = New System.Drawing.Font("Arial", 20.25)
newbutton.Font = myFont
newbutton.ForeColor = Color.White
newbutton.BackColor = Color.MidnightBlue
Me.Controls.Add(newbutton)
Next
SQLConn.Close()
End Sub
So the only difference in the images is what the text is set to display on the buttons, but the alignment is all out of whack when the string is not static.
What am I doing wrong or what am I missing to have the right image formatted the same as the left one?
Cheers :-)
I have tried your example and I was unable to reproduce the problem until I added a carriagereturn/linefeed to the variable used for button text.
So I assume that your data contains some unprintable characters that disalign your output.
A simple fix should be
newbutton.Text = dataString.Trim()