I have the following routine (that works) but which is messy to update owing to the hand-typed strings it uses:
Private Sub ListDefaults()
Dim conn As New SqlConnection( _
"server=bas047\AUTODESKVAULT;Database=DWGDetails;Integrated Security=SSPI")
'Dim conn As New SqlConnection( _
'"server=bas047\AUTODESKVAULT;Database=DWGDetails;Integrated Security=SSPI")
Try
'clear columns
If Not Me.DataGridView1.DataSource Is Nothing Then
Me.DataGridView1.Columns.Clear()
Me.DataGridView1.DataSource = Nothing
End If
conn.Open()
Dim cmd As SqlCommand = conn.CreateCommand()
Dim DLcmd As SqlCommand = conn.CreateCommand()
Dim ILcmd As SqlCommand = conn.CreateCommand()
'Dim srctbl As String = String.Empty
If RadioButton1.Checked = True Then 'A3
shtsize = "A3"
cmd.CommandText = "SELECT [AttributeName],[IsDefaultValue],[DefaultValue] FROM " & _
Chr(34) & "DefaultValues(Borders SB-A3_993-5.2(block))" & Chr(34)
srctbl = "DefaultValues(Borders SB-A3_993-5.2(block))"
ElseIf RadioButton2.Checked = True Then 'A2
shtsize = "A2"
cmd.CommandText = "SELECT [AttributeName],[IsDefaultValue],[DefaultValue] FROM " & _
Chr(34) & "DefaultValues(Borders SB-A2_992-5.2(block))" & Chr(34)
srctbl = "DefaultValues(Borders SB-A2_992-5.2(block))"
ElseIf RadioButton3.Checked = True Then 'A1
shtsize = "A1"
cmd.CommandText = "SELECT [AttributeName],[IsDefaultValue],[DefaultValue] FROM " & _
Chr(34) & "DefaultValues(Borders SB-A1_991-5.2(block))" & Chr(34)
srctbl = "DefaultValues(Borders SB-A1_991-5.2(block))"
ElseIf RadioButton4.Checked = True Then 'A0
shtsize = "A0"
cmd.CommandText = "SELECT [AttributeName],[IsDefaultValue],[DefaultValue] FROM " & _
Chr(34) & "DefaultValues(Borders SB-A0_990-5.2(block))" & Chr(34)
srctbl = "DefaultValues(Borders SB-A0_990-5.2(block))"
End If
'Populate datagridview1
da = New SqlDataAdapter(cmd.CommandText, conn.ConnectionString)
ds = New DataSet
da.Fill(ds, srctbl)
DataGridView1.DataSource = ds.Tables(0)
DataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.DisplayedCells)
'should enable setting of the date and drawn by entries
'Dim X As Integer
'For X = 0 To DataGridView1.Rows.Count
' If UCase(DataGridView1.Rows(X).Cells(0).Value) = "DRAWN BY" Then
' MessageBox.Show("Found Drawn by!")
' End If
'Next
Catch ex As System.Data.SqlClient.SqlException
MessageBox.Show("There was an error in executing the SQL." & vbLf & "Error Message:" & ex.Message, "SQL")
Finally
'cleanup and reset!
conn.Close()
End Try
End Sub
And I am thinking this is an ideal candidate for Linq. This is what I have so far that seems to work:
Private Sub ListDefaultsMk1()
Try
Using db As New DWGDetailsDataContext
If RadioButton1.Checked = True Then 'A3
shtsize = "A3"
DataGridView1.DataSource =
From c In db.DefaultValues_Borders_SB_A3_993_5_2_block__s()
Select New With {c.AttributeName, c.IsDefaultValue, c.DefaultValue}
ElseIf RadioButton2.Checked = True Then 'A2
shtsize = "A2"
DataGridView1.DataSource =
From c In db.DefaultValues_Borders_SB_A2_992_5_2_block__s()
Select New With {c.AttributeName, c.IsDefaultValue, c.DefaultValue}
ElseIf RadioButton3.Checked = True Then 'A1
shtsize = "A1"
DataGridView1.DataSource =
From c In db.DefaultValues_Borders_SB_A1_991_5_2_block__s()
Select New With {c.AttributeName, c.IsDefaultValue, c.DefaultValue}
ElseIf RadioButton4.Checked = True Then 'A0
shtsize = "A0"
DataGridView1.DataSource =
From c In db.DefaultValues_Borders_SB_A0_990_5_2_block__s()
Select New With {c.AttributeName, c.IsDefaultValue, c.DefaultValue}
End If
End Using
Catch ex As Exception
MessageBox.Show("There was an error in executing the SQL." & vbLf & "Error Message:" & ex.Message, "SQL")
End Try
End Sub
The next step of my program is to take the (edited) values from the datagridview (In the case of the handwritten SQL code, the shared DataSet "ds") and populate another table but I can't figure out how to do that using Linq.
Can anyone offer assistance?
Thanks in advance,
Alex.
EDIT: Here's what I've reduced it to based on the comment
Private Sub ListDefaultsMk1()
Try
Using db As New DWGDetailsDataContext
If RadioButton1.Checked = True Then 'A3
shtsize = "A3"
DataGridView1.DataSource = (From c In db.DefaultValues_Borders_SB_A3_993_5_2_block__s Select c).ToList()
ElseIf RadioButton2.Checked = True Then 'A2
shtsize = "A2"
DataGridView1.DataSource = (From c In db.DefaultValues_Borders_SB_A2_992_5_2_block__s Select c).ToList()
ElseIf RadioButton3.Checked = True Then 'A1
shtsize = "A1"
DataGridView1.DataSource = (From c In db.DefaultValues_Borders_SB_A1_991_5_2_block__s Select c).ToList()
ElseIf RadioButton4.Checked = True Then 'A0
shtsize = "A0"
DataGridView1.DataSource = (From c In db.DefaultValues_Borders_SB_A0_990_5_2_block__s Select c).ToList()
End If
End Using
Catch ex As Exception
MessageBox.Show("There was an error in executing the Linq2SQL Query!" & vbLf & "Error Message:" & ex.Message, "SQL")
End Try
End Sub
Linq2Sql and DataSets are two completely different beasts and the reason you can both use them in a grid is because the grid can consume more types than just dataset.
You could technically pin down the linq query result using, say, ToList() and then bind the List to a grid. Afterwards all edits will be reflected on List which you can transform into other formats as you feel like (you didn't give much information about where the data should go other than its a table, table in dataset (must it be dataset), table in database, etc).
Related
getting data from xlsx file and inserting in oledb connection.
i want to make it faster by adding thread or multiple thread if possible. here is my code ... any idea please i need help
Public Sub readEEdata()
Dim eedatapath As String = MainForm.TxtEEData.Text
Dim tempinfo As New infocls
Dim fi As IO.FileInfo = New IO.FileInfo(MainForm.TxtEEData.Text)
Using excelPackage As New ExcelPackage(fi)
Dim firstWorksheet As ExcelWorksheet = excelPackage.Workbook.Worksheets(1)
Dim colCount As Integer = firstWorksheet.Dimension.End.Column
Dim rowCount As Integer = firstWorksheet.Dimension.End.Row
For row As Integer = 2 To rowCount
With tempinfo
MainForm.LblStatus.Text = "Importing EE data: " & row & " " & GetValue(firstWorksheet, "A" & row.ToString)
.ID = GetValue(firstWorksheet, "A" & row.ToString)
.Fname = GetValue(firstWorksheet, "D" & row.ToString)
.lname = GetValue(firstWorksheet, "B" & row.ToString)
.mname = GetValue(firstWorksheet, "E" & row.ToString)
.tinum = GetValue(firstWorksheet, "F" & row.ToString)
If .Fname <> Nothing AndAlso .Fname.Contains("'") Then .Fname = .Fname.Replace("'", "´")
If .lname <> Nothing AndAlso .lname.Contains("'") Then .lname = .Fname.Replace("'", "´")
If .mname <> Nothing AndAlso .mname.Contains("'") Then .mname = .Fname.Replace("'", "´")
End With
If tempinfo.ID <> Nothing And tempinfo.Fname <> Nothing Then
saveEEData(tempinfo)
End If
Next
End Using
Public Sub saveEEData(ByVal infoclass As infocls)
masterConnection = New OleDb.OleDbConnection(connString)
masterConnection.Open()
masterCommand.Connection = masterConnection
masterCommand.CommandText = "Insert into EEData Values('" & infoclass.ID & "', '" & infoclass.lname & "', '" & infoclass.Fname & "','" & infoclass.mname & "','" & infoclass.tinum & "')"
masterCommand.ExecuteNonQuery()
masterConnection.Close()
End Sub
I don't know what you are doing with that label but it just keeps getting overwritten in you loop. The only thing you will see is the last iteration.
There is no need to assign the data to the properties of a class. Just assign them directly to the parameters' values.
Using...End Using block ensure that your database objects are closed and disposed even it there is an error. Always use parameters in you sql statements. You will need to check in your database for the correct datatypes and field sizes. The parameters are added once outside the loop and only the values change inside the loop.
You don't have to worry about single quotes in names when you are using parameters.
This might speed things up because you were opening and closing the connection 10,000 times! Argh!
Public Sub readEEdata()
Dim eedatapath As String = MainForm.TxtEEData.Text
'Don't access the text box a second time, you already have the value
Dim fi As IO.FileInfo = New IO.FileInfo(eedatapath)
Using excelPackage As New ExcelPackage(fi)
Try
Dim firstWorksheet As ExcelWorksheet = excelPackage.Workbook.Worksheets(1)
Dim colCount As Integer = firstWorksheet.Dimension.End.Column
Dim rowCount As Integer = firstWorksheet.Dimension.End.Row
Using cn As New OleDbConnection(connString),
cmd As New OleDbCommand("Insert into EEData Values(#ID, #Lname, #Fname,#Mname,#tinum);", cn)
With cmd.Parameters
.Add("#ID", OleDbType.Integer)
.Add("#Lname", OleDbType.VarChar, 100)
.Add("#Fname", OleDbType.VarChar, 100)
.Add("#Mname", OleDbType.VarChar, 100)
.Add("#tinum", OleDbType.VarChar, 100)
End With
cn.Open()
For row = 2 To rowCount
cmd.Parameters("#ID").Value = GetValue(firstWorksheet, "A" & row.ToString)
cmd.Parameters("#Lname").Value = GetValue(firstWorksheet, "B" & row.ToString)
cmd.Parameters("#Fname").Value = GetValue(firstWorksheet, "D" & row.ToString)
cmd.Parameters("#Mname").Value = GetValue(firstWorksheet, "E" & row.ToString)
cmd.Parameters("#tinum").Value = GetValue(firstWorksheet, "F" & row.ToString)
cmd.ExecuteNonQuery()
Next
End Using
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Using
End Sub
Another approach would be to create and fill a datatable. Then use a DataAdapter to do the Update all at once.
I'm still adjusting to the vb.net environment so I want to ask a question..
I have my code here:
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Dim connstr As String = "server=supertelco\sqlexpress; database=testdb; user= sa; password=sa;"
cmdconn = New SqlConnection
cmd = New SqlCommand
cmdconn.ConnectionString = connstr 'sqlstr
cmd.Connection = cmdconn
cmdconn.Open()
Dim period, VOUCH_AMT, INDIVIDUAL_AMT, check_no, D_MAILED, DIR_NO, who_updated As String
For i As Integer = 0 To Me.DataGridView2.Rows.Count - 1
With Me.DataGridView2.Rows(i)
If IsDBNull(.Cells(0).Value()) OrElse .Cells(0).Value() Is Nothing OrElse .Cells(0).Value().ToString().Trim() = "" Then
period = ""
Else
period = .Cells(0).Value()
End If
If IsDBNull(.Cells(1).Value()) OrElse .Cells(1).Value() Is Nothing OrElse .Cells(1).Value().ToString().Trim() = "" Then
VOUCH_AMT = "0"
Else
VOUCH_AMT = .Cells(1).Value()
End If
If IsDBNull(.Cells(2).Value()) OrElse .Cells(2).Value() Is Nothing OrElse .Cells(2).Value().ToString().Trim() = "" Then
INDIVIDUAL_AMT = "0"
Else
INDIVIDUAL_AMT = .Cells(2).Value()
End If
If IsDBNull(.Cells(3).Value()) OrElse .Cells(3).Value() Is Nothing OrElse .Cells(3).Value().ToString().Trim() = "" Then
check_no = ""
Else
check_no = .Cells(3).Value()
End If
If IsDBNull(.Cells(4).Value()) OrElse .Cells(4).Value() Is Nothing OrElse .Cells(4).Value().ToString().Trim() = "" Then
D_MAILED = ""
Else
D_MAILED = .Cells(4).Value()
End If
If IsDBNull(.Cells(5).Value()) OrElse .Cells(5).Value() Is Nothing OrElse .Cells(5).Value().ToString().Trim() = "" Then
DIR_NO = ""
Else
DIR_NO = .Cells(5).Value()
End If
If IsDBNull(.Cells(6).Value()) OrElse .Cells(6).Value() Is Nothing OrElse .Cells(6).Value().ToString().Trim() = "" Then
who_updated = ""
Else
who_updated = .Cells(6).Value()
End If
End With
cmd.CommandText = "insert into tobee.EBD_BILLHISTORY(period, vouch_amt, individual_amt, check_no, d_mailed, dir_no, who_updated)values" & _
"('" & period.Replace("'", "''") & "'," & VOUCH_AMT & "," & INDIVIDUAL_AMT & ",'" & check_no.Replace("'", "''") & "','" & D_MAILED.Replace("'", "''") & "', '" & DIR_NO.Replace("'", "''") & "','" & who_updated.Replace("'", "''") & "')"
cmd.ExecuteNonQuery()
MsgBox("Saved")
Next
cmdconn.Close()
End Sub
so yeah, all code works fine except the updates in SQL Server. I wonder why the changes I made in dgv was not being reflected in the database after clicking the save button? Could someone help me about this? Am I missing something?
I would suggest to copy the value cmd.CommandText has before you call ExecuteNonQuery to the clipboard and execute it in Sql Server Management Studio ... and see what happens (error messages) ... apart from this you should think about using SqlParameters ...
When I try to run the program, an error shows " ERROR[07002][Microsoft][ODBC MICROSOFT ACCESS DRIVER] TOO FEW PARAMETERS.EXPECTED 1" USING THIS CONNECTION.
Public Sub open_connection ()
Try
con = New OdbcConnection("dsn = LocalDB")
con.Open()
End try
Catch ex As Exception
MsgBox(ex.message)
End sub
Problems occurs when inserting and reading..
sSql = "select * from Faculty where RFID='" & txtrfid.Text & "'"
Dim cmd As New OdbcCommand(sSql, con)
Dim dr As OdbcDataReader = cmd.ExecuteReader()
If dr.HasRows Then
dr.Read()
txtfname.Text = dr("fname").ToString()
txtlname.Text = dr("lname").ToString()
txtid.Text = dr("STID").ToString()
txtposition.Text = dr("Pstion").ToString()
txtsubject.Text = dr("Subject").ToString()
Dim bits As Byte() = CType(dr("Pfile"), Byte())
Dim memo As New MemoryStream(bits)
Dim myimg As New Bitmap(memo)
imgRetrieve.Image = myimg
dr.Close()
sSql = " SELECT TOP 1 flag_inout FROM Attendance where faculty_id = #StId ORDER BY Attendance_id DESC"
Dim pcmd As New OdbcCommand(sSql, con)
pcmd.Parameters.AddWithValue("#StId", txtid.Text)
Dim pdr As OdbcDataReader = pcmd.ExecuteReader()
While pdr.Read()
TextBox1.Text = pdr("flag_inout").ToString()
End While
If TextBox1.Text = "IN" Then
TextBox1.Text = "OUT"
ElseIf TextBox1.Text = "OUT" Then
TextBox1.Text = "IN"
ElseIf TextBox1.Text = Nothing Then
TextBox1.Text = "IN"
End If
pdr.Close()
'Check Duplicate
'If txtfname.Text.Length = 0 Then
' Return
'End If
'If Not CheckDateDuplicate() Then
' MessageBox.Show("Already Saved on this Date")
' Return
'End If
sSql = "insert into Attendance (faculty_id, faculty_Fname,faculty_Lname,[Position],Subject, attendance_date, attendance_time, flag_inout) values('" & txtid.Text & "','" & txtfname.Text & "','" & txtlname.Text & "','" & txtposition.Text & "','" & txtsubject.Text & "','" & DateTimePicker1.Value.Date & "','" & TimeOfDay.ToShortTimeString & "','" & TextBox1.Text & "')"
Dim xcmd As New OdbcCommand(sSql, con)
If xcmd.ExecuteNonQuery() > 0 Then
'MessageBox.Show("ATTENDANCE SAVED")
txtrfid.Text = ""
'txtid.Text = ""
'txtfname.Text = ""
'txtlname.Text = ""
'txtposition.Text = ""
'txtsubject.Text = ""
txtrfid.Focus()
Dtagrid()
End If
If TextBox1.Text = "IN" Then
lblinuse.Visible = True
lblvacant.Visible = False
lbllstuser.Visible = False
lblcrrntuser.Visible = True
ElseIf TextBox1.Text = "OUT" Then
lblinuse.Visible = False
lblvacant.Visible = True
lbllstuser.Visible = True
lblcrrntuser.Visible = False
'txtid.Text = ""
'txtfname.Text = ""
'txtlname.Text = ""
'txtposition.Text = ""
'txtsubject.Text = ""
'imgRetrieve.Image = Nothing
End If
End If
Dtagrid()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
CAUSE
This error occurs only with Microsoft Access when one of the column
names specified in a select statement does not exist in the table
being queried.
Resolution
Remove any invalid column names from the select statement.
Make sure that Column Name RFID exist in Faculty table and also check txtrfid has value or not
Hi I'm just learning how handle SQL statements using vb.net. My problem is how do I update my table using the items in listbox as an identifier.
My SQL query is working.
update tblBillingSched set Status = 'paid'
where BillNum = 'MA5'
Here's the revised code:
Private Sub btnPostAdvancedPayment_Click(sender As Object, e As EventArgs) Handles btnPostAdvancedPayment.Click
Dim connection_string As String = "Data Source=.\sqlexpress;Initial Catalog=CreditAndCollection;Integrated Security=True"
Dim connection As New SqlConnection(connection_string)
connection.Open()
Dim SQLCmd As SqlCommand
Dim sSQL As String = "UPDATE tblBillingSched SET Status = 'Paid' WHERE BillNum = "
If MessageBox.Show("Continue to Save?", " ", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) = DialogResult.OK Then
Dim firstTime As Boolean = True
For Each item In lstBillNum.Items
If (item IsNot Nothing AndAlso item.ToString().Trim().Length > 0) Then
If (firstTime) Then
firstTime = False
Else
sSQL = sSQL & " OR BillNum = "
End If
sSQL = sSQL & "'" & item.ToString() & "'"
End If
Next
SQLCmd = New SqlCommand(sSQL, Connection)
SQLCmd.ExecuteNonQuery()
MessageBox.Show("Client Record Successfully Saved!", " ", MessageBoxButtons.OK, MessageBoxIcon.Information)
connection.Close()
SQLCmd.Dispose()
ElseIf DialogResult.Cancel Then
MessageBox.Show("Saving Cancelled!", "", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Dim dt as date = CDate(DateTime.Today).ToString("MM/dd/yyyy")
Try
Dim cn As New OleDb.OleDbConnection
cn.ConnectionString = GetConnectionStringByName("FD_project.My.MySettings.fixedepoConnectionString")
Dim sSQL As String = "UPDATE fixdeporeg SET approval = 'A', a_user = 'CFO', " & _
"app_date = # " & dt & "# WHERE slno = "
If MessageBox.Show("Continue to Save?", " ", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) = DialogResult.OK Then
Dim firstTime As Boolean = True
For x As Integer = 0 To CheckedListBox1.CheckedItems.Count - 1
If (firstTime) Then
firstTime = False
Else
sSQL = sSQL & " OR slno = "
End If
'sSQL = sSQL & "'" & item.ToString() & "'"
sSQL = sSQL & CheckedListBox1.CheckedItems(x).item("slno")
Next
Dim SQLCmd As OleDbCommand = New OleDbCommand(sSQL, cn)
MessageBox.Show(sSQL)
cn.Open()
'dt = cmd1.ExecuteScalar()
SQLCmd.ExecuteNonQuery()
cn.Close()
ElseIf DialogResult.Cancel Then
MessageBox.Show("Saving Cancelled!", "", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
End Sub
I understand that you are after a loop on these lines:
Dim sSQL As String = "UPDATE tblBillingSched SET Status = 'paid' WHERE BillNum = "
Dim firstTime As Boolean = True
For Each item In lstBillNum.Items
If (item IsNot Nothing AndAlso item.ToString().Trim().Length > 0) Then
If (firstTime) Then
firstTime = False
Else
sSQL = sSQL & " OR BillNum = "
End If
sSQL = sSQL & "'" & item.ToString() & "'"
End If
Next
i have the following code to fill two comboboxes using one dataset:
Private Sub sub_cbo_type_load()
Dim ds As New DataSet
ds = cls.cbo_type()
If ds IsNot Nothing _
AndAlso ds.Tables.Count > 0 _
AndAlso ds.Tables(0).Rows.Count > 0 Then
Me.r_cbo_type.DataSource = ds.Tables(0)
Me.r_cbo_type.DisplayMember = "desc"
Me.r_cbo_type.ValueMember = "code"
Me.r_cbo_type.SelectedIndex = -1
Me.m_cbo_type.DataSource = ds.Tables(0)
Me.m_cbo_type.DisplayMember = "desc"
Me.m_cbo_type.ValueMember = "code"
Me.m_cbo_type.SelectedIndex = -1
End If
End Sub
the problems is: whenever the index is changed in one combobox, it's automatically changed in the other one too.
does anyone know how can i solve this?
thanks for your time.
Try cloning the tables:
Private Function CopyTable(ByVal sourceTable As DataTable) As DataTable
Dim newTable As DataTable = sourceTable.Clone
For Each row As DataRow In sourceTable.Rows
newTable.ImportRow(row)
Next
Return newTable
End Function
Then your data sources would be referencing different sources:
Me.r_cbo_type.DataSource = CopyTable(ds.Tables(0))
Me.m_cbo_type.DataSource = CopyTable(ds.Tables(0))
do like this
Private Sub btn_update1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_update1.Click
If MsgBox("Are you sure to update?" & "", MsgBoxStyle.YesNo, "Confirmation") = MsgBoxResult.Yes = True Then
Dim transmode As String = vbNullString
Dim byair As String = vbNullString
Dim bysea As String = vbNullString
If rb_air.Checked = True Then
transmode = "A"
byair = txt_mserial.Text '.Substring(txt_mserial.TextLength - 4, 4)
bysea = vbNullString
ElseIf rb_sea.Checked = True Then
transmode = "B"
byair = vbNullString
bysea = txt_mserial.Text '.Substring(txt_mserial.TextLength - 4, 4)
End If
Try
If con.State = ConnectionState.Closed Then con.Open()
global_command = New SqlCommand("update ytmi_finished_products set rev_ctrl_no = '" & txt_mrev.Text & "', by_air = '" & byair & "', by_sea = '" & bysea & "', transport_mode = '" & transmode & "' where REPLACE(prod_no, '-', '') +'-'+ ISNULL(CONVERT(varchar(50), prod_sx), '') + prod_lvl = '" & txt_mpart.Text & "' and cast(serial_no as numeric) = '" & txt_mserial.Text & "' and req_box_qty = '" & txt_mqty.Text & "' and remarks is null", con)
global_command.ExecuteNonQuery()
global_command.Dispose()
MsgBox("Successfully Updated!", MsgBoxStyle.Information, "Message")
mclear()
Catch ex As Exception
MsgBox("Trace No 20: System Error or Data Error!" + Chr(13) + ex.Message + Chr(13) + "Please Contact Your System Administrator!", vbInformation, "Message")
End Try
End If
End Sub