I'm experiencing an issue where I use a data adapter to update and then refill a datatable. After calling the fill method, the row gets duplicated. One ID has the correct (new) ID and the other shows -1 for the ID. The code below works perfect and is the simpler form of what I want my more complex code to do. Cosider the following:
Imports WindowsApplication1.testDataSet
Imports WindowsApplication1.testDataSetTableAdapters
Imports System.Data.OleDb
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim DA As New testTableAdapter
Dim DT As New testDataTable
DA.Fill(DT)
Dim NR As testRow = DT.Rows.Add
NR.SomeText = "Test"
Dim DA2 As New OleDbDataAdapter("SELECT * FROM test", _
DA.Connection.ConnectionString)
Dim CB As New OleDbCommandBuilder(DA2)
DA2.Update(DT)
DA.Fill(DT)
For Each R As testRow In DT.Rows
Debug.Print(R.ID)
Next
End Sub
End Class
The code above works perfect. They key column doesn't show -1, there are no duplicates. Now consider the code below from my application which causes a duplicate row with the key column resulting in -1 right after the last LoadLoadNumbers().
Dim AccountLoans As IEnumerable(Of LoanNumbersRow) = _
From L As LoanNumbersRow In LoanNumbers _
Select L Where L.AccountID = ID
If Not frmFindLoans.IsDisposed AndAlso _
frmFindLoans.DialogResult = Windows.Forms.DialogResult.OK Then
For Each L As LoanNumbersRow In AccountLoans
If (From R As DataGridViewRow In frmFindLoans.dgvLoans.Rows _
Select R Where R.Cells("LoanNumber").Value = L.LoanNumber).Count = 0 Then
If L.IsWhenDeletedNull Then
L.WhenDeleted = Now
L.DeletedBy = UserName()
End If
End If
Next
Dim NewLoan As LoanNumbersRow
Dim FindLoan As IEnumerable(Of LoanNumbersRow)
For Each R As DataGridViewRow In frmFindLoans.dgvLoans.Rows
FindLoan = From L As LoanNumbersRow In LoanNumbers.Rows _
Select L Where L.LoanNumber = R.Cells("LoanNumber").Value And _
L.AccountID = ID
If FindLoan.Count = 0 Then
NewLoan = LoanNumbers.Rows.Add
NewLoan.AccountID = Acc.AccountID
NewLoan.LoanNumber = R.Cells("LoanNumber").Value
NewLoan.LoanBusinessName = R.Cells("LoanBusiness").Value
NewLoan.LoanBorrower = R.Cells("LoanBorrower").Value
NewLoan.AddedBy = UserName()
NewLoan.WhenAdded = Now
End If
Next
Try
Dim CB As New OleDbCommandBuilder(LoanNumbersAdapter)
LoanNumbersAdapter.Update(LoanNumbers)
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical, "Error saving loan number data")
Exit Sub
End Try
If Not LoadLoanNumbers() Then Exit Sub
End If
Other variables and such from a module:
Public LoanNumbersAdapter As OleDbDataAdapter
Public LoanNumbers As New LoanNumbersDataTable
Public Sub InitializeAdapters()
LoanNumbersAdapter = New OleDbDataAdapter( _
"SELECT * FROM LoanNumbers WHERE WhenDeleted IS NULL ORDER BY WhenAdded DESC", AccountingConn)
End Sub
Public Function LoadData(ByVal DA As OleDbDataAdapter, ByVal DT As DataTable) As Boolean
Try
DA.Fill(DT)
Return True
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical, "Error loading the " & DT.TableName & " table")
Return False
End Try
End Function
Public Function LoadLoanNumbers() As Boolean
Return LoadData(LoanNumbersAdapter, LoanNumbers)
End Function
Why does the simple test at the top work fine, but my actual application create the duplicate row with -1 on the key column? I suppose I could clear the datatable before filling after the update but wouldn't that bog it down once it starts becoming a large table?
*BTW: The DB is MS access and it's .NET 3.5
This is my duct tape solution :(
''' <summary>
''' Removes any rows where the ID/key column is less than zero
''' </summary>
<Extension()> Public Sub DeleteRelics(ByVal DT As DataTable)
If DT.PrimaryKey.Count = 0 Then Exit Sub
For Each R As DataRow In _
(From Rows As DataRow In DT.Rows _
Select Rows Where Rows(DT.PrimaryKey.First.ColumnName) < 0)
R.Delete()
Next
DT.AcceptChanges()
End Sub
Related
I'm sorry for the log post but I am about to pull my hair out. I am attempting to import a PDF into a database.
The main error I am getting is: "Implicit conversion from data type varchar to varbinary(MAX) is not allowed. Use the CONVERT function to run this query."
Some of the coding included below is for a SEARCH function that is not yet completed. Please disregard that area of coding.
Basically I am loading a PDF in the AxAcroPDF1 box. This works great. It then pre-fills out a few of the textboxes. User inputs the Broker Load Number than hits save and a openfiledialog opens and the file is chosen to be imported. This then is where the failed import happens and the error above is given. I have tried many different avenues but always ending up with the same result. I am at a complete and total loss.
Table structure is as follows:
ID, int, NOT NULL IDENTITY(1,1) PRIMARY KEY,
BROKER_LOAD_NUMBER nvarchar(15) NOT NULL,
PDF_FILENAME,nvarchar(50) NOT NULL,
PETS_LOAD_NUMBER nvarchar(10) NOT NULL,
PAPERWORK varbinary(MAX) NOT NULL
My FULL code is as follows:
Imports System.Data.SqlClient
Public Class LoadDocs
Private DV As DataView
Private currentRow As String
Private Sub LoadDocs_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'DocDataset.Documents_Table' table. You can move, or remove it, as needed.
Documents_TableTableAdapter.Fill(DocDataset.Documents_Table)
End Sub
Private Sub btnOpenPDF_Click(sender As Object, e As EventArgs) Handles btnOpenPDF.Click
Dim CurYear As String = CType(Now.Year(), String)
On Error Resume Next
OpenFileDialog1.Filter = "PDF Files(*.pdf)|*.pdf"
OpenFileDialog1.ShowDialog()
AxAcroPDF1.src = OpenFileDialog1.FileName
tbFilePath.Text = OpenFileDialog1.FileName
Dim filename As String = tbFilePath.Text.ToString
tbFileName.Text = filename.Substring(Math.Max(0, filename.Length - 18))
Dim loadnumber As String = tbFileName.Text
tbPetsLoadNumber.Text = loadnumber.Substring(7, 7)
End Sub
Private Sub SearchResult()
Dim cmd As New SqlCommand
Dim reader As SqlDataReader
'SQL to get specific data from the Documents_Table
cmd.Parameters.Clear()
If cbColName.Text = "SEARCH BY:" Then
MeMsgBoxSearchCriteria.ShowDialog()
Else : lblSearchResults.Items.Clear()
Select Case DocDataset.Documents_Table.Columns(cbColName.Text).DataType
Case GetType(Integer)
DV.RowFilter = cbColName.Text & " = " & tbSearchInput.Text.Trim
Case GetType(Date)
DV.RowFilter = cbColName.Text & " = #" & tbSearchInput.Text.Trim & "#"
Case Else
DV.RowFilter = cbColName.Text & " LIKE '*" & tbSearchInput.Text.Trim & "*'"
End Select
If DV.Count > 0 Then
For IX As Integer = 0 To DV.Count - 1
lblSearchResults.Items.Add(DV.Item(IX)("PETS_LOAD_NUMBER"))
Next
If DV.Count = 1 Then
lblSearchResults.SelectedIndex = 0
Dim ix As Integer = DocumentsTableBindingSource.Find("PETS_LOAD_NUMBER", CInt(lblSearchResults.SelectedItem.ToString))
DocumentsTableBindingSource.Position = ix
Else
lblSearchResults.Visible = True
lblSearchResults.BringToFront()
End If
Else
' Display a message box notifying users the record cannot be found.
MeMsgBoxNoSearch.ShowDialog()
End If
End If
End Sub
Private Sub LbllSearchResults_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lblSearchResults.SelectedIndexChanged
Dim ix As Integer = DocumentsTableBindingSource.Find("PETS_LOAD_NUMBER", CInt(lblSearchResults.SelectedItem.ToString))
DocumentsTableBindingSource.Position = ix
lblSearchResults.Visible = False
End Sub
Private Sub DocumentsTableBindingSource_PositionChanged(sender As Object, e As EventArgs) Handles DocumentsTableBindingSource.PositionChanged
Try
currentRow = DocDataset.Documents_Table.Item(DocumentsTableBindingSource.Position).ToString
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub BtnSavePDF_Click(sender As Object, e As EventArgs) Handles btnSavePDF.Click
If tbPetsLoadNumber.Text.Length = 0 Then
MessageBox.Show("Please enter a PETS Load Number", "Missing Load Number", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Exit Sub
ElseIf tbBrokerLoadNumber.Text.Length = 0 Then
MessageBox.Show("Please enter a Broker Load Number", "Missing Load Number", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Exit Sub
ElseIf tbFileName.Text.Length = 0 Then
MessageBox.Show("Please enter a Filename", "Missing Filename", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Exit Sub
End If
Try
Using OpenFileDialog As OpenFileDialog = OpenFileDialog1()
If (OpenFileDialog.ShowDialog(Me) = DialogResult.OK) Then
tbFilePath.Text = OpenFileDialog.FileName
Else 'Cancel
Exit Sub
End If
End Using
'Call Upload Images Or File
Dim sFileToUpload As String = ""
sFileToUpload = LTrim(RTrim(tbFilePath.Text))
Dim Extension As String = Path.GetExtension(sFileToUpload)
upLoadImageOrFile(sFileToUpload, "PDF")
upLoadImageOrFile(sFileToUpload, Extension)
'Initialize byte array with a null value initially.
Dim data As Byte() = Nothing
'Use FileInfo object to get file size.
Dim fInfo As New FileInfo(tbFilePath.Text)
Dim numBytes As Long = fInfo.Length
'Open FileStream to read file
Dim fStream As New FileStream(tbFilePath.Text, FileMode.Open, FileAccess.Read)
'Use BinaryReader to read file stream into byte array.
Dim br As New BinaryReader(fStream)
'Supply number of bytes to read from file.
'In this case we want to read entire file. So supplying total number of bytes.
data = br.ReadBytes(CInt(numBytes))
'Insert the details into the database
Dim cmd As New SqlCommand
cmd.CommandText = "INSERT INTO Documents_Table (BROKER_LOAD_NUMBER, PDF_FILENAME, PETS_LOAD_NUMBER, PAPERWORK)
VALUES ('#bl', '#fn', '#pl', '#pdf');"
cmd.Parameters.AddWithValue("#fn", tbFileName.Text)
cmd.Parameters.AddWithValue("#p1", tbPetsLoadNumber.Text)
cmd.Parameters.AddWithValue("#bl", tbBrokerLoadNumber.Text)
cmd.Parameters.AddWithValue("#fp", tbFilePath.Text)
cmd.Parameters.AddWithValue("#pdf", data)
cmd.CommandType = CommandType.Text
cmd.Connection = New SqlConnection With {
.ConnectionString = My.MySettings.Default.PETS_DatabaseConnectionString
}
cmd.Connection.Open()
cmd.ExecuteNonQuery()
cmd.Connection.Close()
MsgBox("File successfully Imported to Database")
Catch ex As Exception
MessageBox.Show(ex.ToString())
End Try
End Sub
Private Sub upLoadImageOrFile(sFilePath As String, sFileType As String)
Dim cmd As New SqlCommand
Dim Data As Byte()
Dim sFileName As String
Dim qry As String
Try
'Read Image Bytes into a byte array
Data = ReadFile(sFilePath)
sFileName = Path.GetFileName(sFilePath)
'Set insert query
qry = "INSERT INTO Documents_Table (BROKER_LOAD_NUMBER, PDF_FILENAME, PETS_LOAD_NUMBER, PAPERWORK)
VALUES ('#bl', '#fn', '#pl', '#pdf')"
'Initialize SqlCommand object for insert.
cmd = New SqlCommand(qry, cmd.Connection)
'We are passing File Name and Image byte data as sql parameters.
cmd.Parameters.AddWithValue("#fn", tbFileName.Text)
cmd.Parameters.AddWithValue("#p1", tbPetsLoadNumber.Text)
cmd.Parameters.AddWithValue("#bl", tbBrokerLoadNumber.Text)
cmd.Parameters.AddWithValue("#fp", tbFilePath.Text)
cmd.Parameters.AddWithValue("#pdf", Data)
cmd.ExecuteNonQuery()
MessageBox.Show("File uploaded successfully")
Catch ex As Exception
MessageBox.Show("File could not uploaded")
End Try
End Sub
Private Function ReadFile(sFilePath As String) As Byte()
Throw New NotImplementedException()
End Function
End Class
Following my previous question answered by #Andrew Morton, I have one more :)
Here is my whole code (not very long for now) :
Imports System.Data
Imports System.Data.SqlClient
Imports System.Data.Sql
Public Class Form1
Sub PopulateCB()
Dim connection As String = "Data Source=.\SQLEXPRESS;Initial Catalog=OST;Integrated Security=True"
Dim sql = "SELECT * FROM liste_unités"
Dim dt As New DataTable
Using conn As New SqlConnection(connection),
da As New SqlDataAdapter(sql, conn)
da.Fill(dt)
End Using
ComboBoxC1L1.DataSource = dt
ComboBoxC1L1.DisplayMember = "nom_unité"
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
PopulateCB()
End Sub
Private Sub ComboBoxC1L1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBoxC1L1.SelectedIndexChanged
Dim cb = DirectCast(sender, ComboBox)
If cb.SelectedIndex >= 0 Then
Dim val = DirectCast(cb.SelectedItem, DataRowView).Row.Field(Of Integer)("cout_unité")
If ComboBoxQC1L1.Text = "ordinaire" Then
LabelPointsC1L1.Text = val
ElseIf ComboBoxQC1L1.Text = "médiocre" Then
LabelPointsC1L1.Text = val - 2
ElseIf ComboBoxQC1L1.Text = "élite" Then
LabelPointsC1L1.Text = val + 2
End If
If cb.SelectedIndex >= 0 Then
Dim val2 = DirectCast(cb.SelectedItem, DataRowView).Row.Field(Of String)("type_unité")
LabelUnitType.Text = val2
End If
End If
Try
Dim totalC1L1 As Integer
totalC1L1 = CInt(TextBoxC1L1.Text) * CInt(LabelPointsC1L1.Text)
LabelTotalC1L1.Text = totalC1L1
Catch ex As Exception
End Try
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ComboBoxQC1L1.Text = "ordinaire"
End Sub
Private Sub TextBoxC1L1_TextChanged(sender As Object, e As EventArgs) Handles TextBoxC1L1.TextChanged
Try
Dim totalC1L1 As Integer
totalC1L1 = CInt(TextBoxC1L1.Text) * CInt(LabelPointsC1L1.Text)
LabelTotalC1L1.Text = totalC1L1
Catch ex As exception
End Try
End Sub
End Class
Here is the program interface
Here is the SQL table look
Here is the program interface when the Button has been clicked
Red Arrow ComboBox text is a DropDownStyle box with 3 possible text choices:
ordinaire,
élite,
médiocre
What I want to do: when changing the red arrow combobox text, the cout_unité label should change too with a "cout_unité -2" in case of "médiocre" ComboBox text, or "cout_unité +2" in case of "élite" ComboBox text or remain = to "cout_unité" if the selected text is "ordinaire".
And it should calculate this only once from the original "cout_unité" value in the table (in case of clicking 10 times on "ordinaire", it shouldn't subtract 10 * 2 to the "cout_unité" value, only 1 * 2)
I can do it in the ComboBoxC1L1 (see code) but I can't reproduce it with this red arrow combobox (probably because of the type of data into this combobox which are "strings", I don't know).
Many thanks :)
Since there is only a single Handles clause, the following line is unnecessary. The sender can only be the ComboBox in the Handles.
Dim cb = DirectCast(sender, ComboBox)
If you set the ValueMember of the combo in the PopulateCB method, you can save a long line of code making the code more readable.
Dim val = DirectCast(cb.SelectedItem, DataRowView).Row.Field(Of Integer)("cout_unité")
To:
Dim val = CInt(ComboBoxC1L1.SelectedValue)
We need the CInt since SelectedValue is an Object.
Don't assign the DataSource until after the DisplayMember and ValueMember are set.
You are checking twice for ComboBoxC1L1.SelectedIndex >= 0.
Just include the unit type in the first If.
The user may not have to trigger the SelectedIndexChanged event if the correct value is already selected. Maybe a button click would be better.
Sub PopulateCB()
Dim connection As String = "Data Source=.\SQLEXPRESS;Initial Catalog=OST;Integrated Security=True"
Dim sql = "SELECT * FROM liste_unités"
Dim dt As New DataTable
Using conn As New SqlConnection(connection),
da As New SqlDataAdapter(sql, conn)
da.Fill(dt)
End Using
ComboBoxC1L1.DisplayMember = "nom_unité"
ComboBoxC1L1.ValueMember = "cout_unité"
ComboBoxC1L1.DataSource = dt
End Sub
Private Sub btnCalculateValue_Click(sender As Object, e As EventArgs) Handles btnCalculateValue.Click
If ComboBoxC1L1.SelectedIndex >= 0 Then
Dim val = CInt(ComboBoxC1L1.SelectedValue)
If ComboBoxQC1L1.Text = "ordinaire" Then
LabelPointsC1L1.Text = val.ToString
ElseIf ComboBoxQC1L1.Text = "médiocre" Then
LabelPointsC1L1.Text = (val - 2).ToString
ElseIf ComboBoxQC1L1.Text = "élite" Then
LabelPointsC1L1.Text = (val + 2).ToString
End If
Dim val2 = DirectCast(ComboBoxC1L1.SelectedItem, DataRowView).Row.Field(Of String)("type_unité")
LabelUnitType.Text = val2
End If
Dim totalC1L1 As Integer
totalC1L1 = CInt(TextBoxC1L1.Text) * CInt(LabelPointsC1L1.Text)
LabelTotalC1L1.Text = totalC1L1.ToString
End Sub
since i have the code of the auto generated text box
Insert data from auto generated textbox to SQL Server database
i am try to write a code for ensuring of the auto generated text box in FlowLayoutPanel1 contain data
the auto generated text box build depends on the number in Val(Label2.Text) of the real part
and if any text box is null or empty then the process will stop until fill all fields
the auto generated text box will be like this if the Val(Label2.Text)
is equal to 3
so i try this in the save button
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
For k As Integer = 1 To Val(Label2.Text)
If String.IsNullOrEmpty(FlowLayoutPanel1.Controls(i).Text) Then
MsgBox("Error , fill all text box")
Return
Else
UpdateUsers()
i += 1
End If
Next
MsgBox("Done , add all data to database ")
Button3.Enabled = False
End Sub
so i getting error after leave some text box and back to fill it again
and the all of form code is
Imports System.Data.SqlClient
'library for create folders
Imports System.IO
Public Class part
Dim cLeft As Integer = 1
Dim top1 As Integer = 5
Dim i As Integer = 0
Dim path1 As String
Dim cmd As SqlCommand
Public Sub AddNewTextBox()
Dim txt As New System.Windows.Forms.TextBox()
txt.Top = cLeft * 30
txt.Left = 100
'txt.Text = "TextBox " & Me.cLeft.ToString
cLeft = cLeft + 1
txt.ForeColor = Color.White
txt.BackColor = Color.Gray
txt.Font = New Font("Arial", 14.0, FontStyle.Regular)
txt.Size = New Size(350, 31)
txt.Location = New Point(156, 130 + top1)
txt.TextAlign = HorizontalAlignment.Center
FlowLayoutPanel1.Controls.Add(txt)
End Sub
Private Sub part_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'college part number
Label2.Visible = False
'college path folder
Label3.Visible = False
For m As Integer = 1 To Val(Label2.Text)
AddNewTextBox()
top1 = top1 + 35
Next
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Me.Close()
End Sub
Private Sub UpdateUsers()
Using cn As New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Hazim M\Desktop\stud_project\stud_project\Database1.mdf;Integrated Security=True;User Instance=True")
Using cmd As New SqlCommand("INSERT INTO college_part ([name],[coll_of_part],[part_path]) Values (#name,#coll_of_part,#part_path);", cn)
If i < Val(Label2.Text) Then
path1 = Label3.Text & "\" & FlowLayoutPanel1.Controls(i).Text.Trim & Date.Now.Year
cmd.Parameters.Add("#name", SqlDbType.NVarChar).Value = FlowLayoutPanel1.Controls(i).Text
cmd.Parameters.Add("#coll_of_part", SqlDbType.NVarChar).Value = Label1.Text
cmd.Parameters.Add("#part_path", SqlDbType.NVarChar).Value = path1
cn.Open()
cmd.ExecuteNonQuery()
cn.Close()
If Not Directory.Exists(path1) Then
Directory.CreateDirectory(path1)
Else
MsgBox("folder is existing")
End If
End If
End Using
End Using
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
For k As Integer = 1 To Val(Label2.Text)
If String.IsNullOrEmpty(FlowLayoutPanel1.Controls(i).Text) Then
MsgBox("Error , fill all text box")
Return
Else
UpdateUsers()
i += 1
End If
Next
MsgBox("Done , add all data to database ")
Button3.Enabled = False
End Sub
End Class
thank u
I think you need to move dim i Integer=0 to local variable in the Button3_click method. ANd Pass i to the UpdateUser call (add the param to UpdateUser). The current global i keeps adding 1 and eventually out of range.
I'm having a hard time in DataGridView ComboBox DropDown. Can someone enlighten me on how i bind data in a custom ComboBox with a special condition in a datagridview?
something like, If the database table was read and then in a particular column "Status" was populated with 0 or 1. And then in datagridview combobox drop down it should display unattended instead of 0 and currently attended instead of 1 and then in running the program when i click attended it should be updated in database as 1.
Any advice, recommendation or tips will be greatly appreciated.
Here is my code:
Private Sub loadDataGrid()
Try
Dim TQry As String
TQry = "Select TQ.Que_No, TS.Step_Remarks, T.Trans_Name, TS.Step_No, O.Office_Name, TQ.Date_Arrive, TQ.Time_Arrive, TQ.STATUS FROM TRANS_QUEUE TQ LEFT JOIN TRANS_STEP TS ON TQ.Trans_Step_ID = TS.Trans_STep_ID LEFT JOIN TRANSACTIONS T ON TQ.Trans_ID = T.Trans_ID LEFT JOIN OFFICE O ON TQ.Office_ID = O.Office_ID"
Dim TCmd As New SqlCommand(TQry, MysqlConn)
TCmd.CommandType = CommandType.Text
Dim TDa As New SqlDataAdapter(TCmd)
Dim TDt As New DataTable
TDa.Fill(TDt)
Dim TBs As New BindingSource
TBs.DataSource = TDt
Dim comboboxColumn As New DataGridViewComboBoxColumn
Dim Status_Data() As String = New String() {"Attended", "Unattended"}
comboboxColumn.Items.AddRange(Status_Data)
comboboxColumn.Name = "Status"
comboboxColumn.MaxDropDownItems = 2
comboboxColumn.FlatStyle = ComboBoxStyle.DropDown
comboboxColumn.Resizable = DataGridViewTriState.True
DataGridView1.DataSource = TBs
DataGridView1.Columns.Remove("Status")
DataGridView1.Columns.Insert(7, comboboxColumn)
Dim CountCols As Integer
CountCols = DataGridView1.ColumnCount - 2
For index As Integer = 0 To CountCols
DataGridView1.Columns(index).ReadOnly = True
Next
Me.DataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.BottomCenter
Me.DataGridView1.DefaultCellStyle.Alignment = DataGridViewContentAlignment.BottomCenter
Catch ex As Exception
MessageBox.Show(ex.Message + " #Function GetTD()", _
"Important Note", _
MessageBoxButtons.OK, _
MessageBoxIcon.Exclamation, _
MessageBoxDefaultButton.Button1)
Me.Close()
End Try
End Sub
Screenshots:
Output
Database Table
i come up on this kind of sol. I discard the combobox dropdown idea and switch to normal button to make the function works and tweak the query.
in query
TQry = "Select TQ.Que_No as Queue, TS.Step_Remarks as Remarks, T.Trans_Name as Transactions, TS.Step_No as Steps, O.Office_Name as Office, TQ.Date_Arrive as Date, TQ.Time_Arrive as Time, case TQ.STATUS when 0 then 'unattended' else 'attended' end as Status FROM TRANS_QUEUE TQ LEFT JOIN TRANS_STEP TS ON TQ.Trans_Step_ID = TS.Trans_STep_ID LEFT JOIN TRANSACTIONS T ON TQ.Trans_ID = T.Trans_ID LEFT JOIN OFFICE O ON TQ.Office_ID = O.Office_ID"
in Start button
Private Sub Start_Btn_Click(sender As Object, e As EventArgs) Handles Start_Btn.Click
Dim RowSelected As Integer = Me.DataGridView1.CurrentRow.Cells(0).Value
MsgBox(RowSelected)
SelectedRow("SELECT * FROM TRANS_QUEUE WHERE Que_No like '%" & RowSelected & "%'") 'kwaon ang Que ID sa selected col
UpQuery("Update TRANS_QUEUE set Status = 1 WHERE Que_No = " & RowSelected & "") 'I update ang status sa selected col
End Sub
Public Sub SelectedRow(ByVal SQCommand As String)
MysqlConn.ConnectionString = "server=BOSS;user=sa;password=pass2017;database=DB_CFSys"
MysqlConn.Open()
Dim Cmpr_EMPLogIn As String = Login.UIDTextBox.Text
Dim SQCmd As New SqlCommand(SQCommand, MysqlConn)
Dim SQDr As SqlDataReader
SQDr = SQCmd.ExecuteReader()
SQDr.Read()
If SQDr.HasRows Then
MsgBox(SQDr.Item("Date_Arrive"))
MsgBox(SQDr.Item("Time_Arrive").ToString)
End If
MysqlConn.Close()
End Sub
Public Sub UpQuery(ByVal SQCommand As String)
MysqlConn.ConnectionString = "server=BOSS;user=sa;password=pass2017;database=DB_CFSys"
Dim SQLCMD As New SqlCommand(SQCommand, MysqlConn)
MysqlConn.Open()
SQLCMD.ExecuteNonQuery()
MsgBox("Successfully Updated")
MysqlConn.Close()
End Sub
In a switch(unattended/attended) button
Private Sub Status_Btn_Click(sender As Object, e As EventArgs) Handles Status_Btn.Click
If count_click = 1 Then
count_click = 2
Me.Status_Btn.Text = "Unattended"
loadDataGridAttended()
ElseIf count_click = 2 Then
count_click = 1
Me.Status_Btn.Text = "Attended"
loadDataGrid()
End If
End Sub
I am a Vb nooby and I have trouble to add specific Items to my Listview from a database.
I would like to compare the value of a combobox with a column value of a table.
To proof if they are equal like apple = apple
When they are equal the whole data set should be added to my ListView. (Only data sets which have the equal value like the selected item of the combobox)
Please Help !!
Thanks a lot and best regards
You can try below code..
Imports System.Data.SqlClient
Public Class Form1
Dim conn As SqlConnection
Dim cmd As SqlCommand
Dim da As SqlDataAdapter
Dim ds As DataSet
Dim itemcoll(100) As String
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.ListView1.View = View.Details
Me.ListView1.GridLines = True
conn = New SqlConnection("Data Source=SQLEXPRESS;Initial Catalog=Northwind;Persist Security Info=True;User ID=id;Password=pass")
Dim strQ As String = String.Empty
strQ = "SELECT * FROM Northwind.dbo.Products"
cmd = New SqlCommand(strQ, conn)
da = New SqlDataAdapter(cmd)
ds = New DataSet
da.Fill(ds, "Table")
Dim i As Integer = 0
Dim j As Integer = 0
' adding the columns in ListView
For i = 0 To ds.Tables(0).Columns.Count - 1
Me.ListView1.Columns.Add(ds.Tables(0).Columns(i).ColumnName.ToString())
Next
'Now adding the Items in Listview
For i = 0 To ds.Tables(0).Rows.Count - 1
For j = 0 To ds.Tables(0).Columns.Count - 1
itemcoll(j) = ds.Tables(0).Rows(i)(j).ToString()
Next
Dim lvi As New ListViewItem(itemcoll)
Me.ListView1.Items.Add(lvi)
Next
End Sub
End Class
You can try this link.
Thanks for your help.
In my solution, I just set a parameter into the sql statement.
Public Function getRahmenvertrag**(ByVal costumerID As Integer)** As List(Of Rahmenvertrag)
Dim sqlCom As New SqlServerCe.SqlCeCommand
sqlCom.CommandText = **"SELECT * FROM Rahmenvertrag LEFT OUTER JOIN Kunde ON Kunden_FID = Kunden_ID WHERE Kunden_ID = #Kunde "**
**sqlCom.Parameters.AddWithValue("Kunde", costumerID)**
Private Sub ComboBox1_Click(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
ListView4.DataBindings.Clear()
ListView4.Items.Clear()
If IsNothing(ComboBox1.SelectedItem) = False Then
For Each Rahmenvertrag As Rahmenvertrag In controller.getRahmenvertrag(ComboBox1.SelectedItem.kunde_ID)
With ListView4.Items.Add(Rahmenvertrag.bezeichnung)
.SubItems.Add(Rahmenvertrag.inhalt)
End With
Next
End If
End Sub