how to call checkbox value from sql to display on form vb.net - vb.net

am doing this but not working only apply in first record its working in insert and update
i stored in sql as true or false
Sub db_load()
On Error Resume Next
Dim pringdata As String = "SELECT custcode_" & _
",custname_" & _
",custname2_" & _
",phone_" & _
",mobile_" & _
",custadd_" & _
",date_" & _
",cutomerzone_ " & _
",check_ " & _
" FROM custInfo "
Dim sqlconload As New SqlConnection(sqlcon)
sqlconload.Open()
Dim da As New SqlDataAdapter(pringdata, sqlconload)
ds.Clear()
da.Fill(ds, "custInfo")
For i As Integer = ds.Tables(0).Rows.Count = 0 To -1
If ds.Tables(0).Rows(i).Item("check_") = "true" Then
checkActive.Checked = True
Else
checkActive.Checked = False
End If
Next
sqlconload.Close()

I gather you are referring to a specific customer since you're only setting a single checkbox? You'll need to modify your query to match that.
Next, examine how you're storing the "check" column. In most cases, converting to Bool will resolve it but you may have to special case it based on available values.
Also, if the field you're looking at could be null, you'll have to account for that as well.
Here's a good pattern to follow that properly disposes of resources such as connections, commands, and readers.
Public Sub db_load()
Using cn = New SqlConnection(sqlcon)
cn.Open()
Using cmd = New SqlCommand("SELECT custcode,custname,custname2,phone,mobile,custadddate,customerzone,check FROM custInfo", cn)
Using dr = cmd.ExecuteReader()
If dr.Read Then
checkActive.Checked = CBool(dr("check"))
End If
End Using
End Using
End Using
End Sub

Related

VB.net Update MS Access from DataGridView with BindingSource

I have a DataGridView populated with a SQL statement that users can input data on certain columns:
Me.bndDataGrid.DataSource = GetData("SELECT H.InnCode, R.RSRM, " & strCols & " E.Escalation " & _
"FROM (((dbo_HotelInfo AS H " & _
"INNER JOIN dbo_RSRM AS R ON H.RevMgr = R.ID) " & _
"INNER JOIN dbo_SrMgr AS S ON R.SrMgr = S.ID) " & _
"INNER JOIN " & strHitList & " AS L ON H.FacilityID = L.FacilityID) " & _
"INNER JOIN dbo_Escalation AS E ON H.FacilityID = E.FacilityID " & _
"WHERE S.ID = " & cbxSrMgr.SelectedValue.ToString)
With Me.grdQueryResults
.AutoGenerateColumns = True
.DataSource = bndDataGrid
End With
bndDataGrid is the BindingSource for grdQueryResults, the DataGridView. The code for GetData is commonly found on MS forums:
Private Shared Function GetData(ByVal sqlCommand As String) As DataTable
Dim strConn As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source={MS Access DB Path Here};"
Dim ctnHitList As OleDbConnection = New OleDbConnection(strConn)
Dim tblHitList As New DataTable
Dim cmdHitList As New OleDbCommand(sqlCommand, ctnHitList)
Dim adrHitList As OleDbDataAdapter = New OleDbDataAdapter()
adrHitList.SelectCommand = cmdHitList
tblHitList.Locale = System.Globalization.CultureInfo.InvariantCulture
adrHitList.Fill(tblHitList)
Return tblHitList
End Function
Now once users are ready to save changes I can't for the life of me figure out how to have this save correctly, mostly since the data source for the DataGridView isn't simply bound to a table.
EDIT:
OK, so I mostly overhauled my code in accordance with Crowcoder's blog page, and got a lot further with it, but now on updating I'm running into a "Concurrency violation: the UpdateCommand affected 0 of the expected 1 records" exception. Here's the update code:
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Dim parInnCode As OleDbParameter = New OleDbParameter("#parInnCode", OleDbType.WChar)
Dim parNotes As OleDbParameter = New OleDbParameter("#parNotes", OleDbType.WChar)
parInnCode.SourceColumn = "InnCode"
parNotes.SourceColumn = "Notes"
Using ctnDataGrid As New OleDbConnection(getConnectionString())
Using cmdGrid As New OleDbCommand("UPDATE (dbo_The400 AS T INNER JOIN dbo_HotelInfo AS H ON T.FacilityID = H.FacilityID) " & _
"INNER JOIN dbo_RSRM AS R ON H.RevMgr = R.ID " & _
"SET [Notes] = #parNotes WHERE H.InnCode = #parInnCode", ctnDataGrid)
Using adrDataGrid As New OleDbDataAdapter()
With adrDataGrid
.UpdateCommand = cmdGrid
With .UpdateCommand.Parameters()
.Add(parInnCode)
.Add(parNotes)
End With
grdQueryResults.EndEdit()
.Update(tblDataGrid)
End With
End Using
End Using
End Using
End Sub
tblDataGrid is declared at the Form Class level, wondering if that may be the issue or if my update query doesn't match the number of columns in the table? Or something else? Can't seem to find the right answer for my case :/
Welp, at long last I figured it out. It involved quite a bit of back end reorganizing to make it easier to connect to it via the front end .net application. Basically I threw all manager inputs into one table and added a column that corresponds to the initiative that required their input.
From there, I could build just about everything in the Dataset Designer and set the Update command on that tableadapter to just update that one table. Cut down the code on the main form to just a few lines that fill the datasources for the combobox columns in the datagridview.
Not an elegant coding solution, but it works!

MysqlDataReader.Read stuck on the last record and doesnt EOF

i confused why mySqlDataReader.Read stuck on the last record and doesnt EOF ..
Here's my private function for executeSql :
Private Function executeSQL(ByVal str As String, ByVal connString As String, ByVal returnRecordSet As Boolean) As Object
Dim cmd As Object
Dim objConn As Object
Try
If dbType = 2 Then
cmd = New MySqlCommand
objConn = New MySqlConnection(connString)
Else
cmd = New OleDbCommand
objConn = New OleDbConnection(connString)
End If
'If objConn.State = ConnectionState.Open Then objConn.Close()
objConn.Open()
cmd.Connection = objConn
cmd.CommandType = CommandType.Text
cmd.CommandText = str
If returnRecordSet Then
executeSQL = cmd.ExecuteReader()
executeSQL.Read()
Else
cmd.ExecuteNonQuery()
executeSQL = Nothing
End If
Catch ex As Exception
MsgBox(Err.Description & " #ExecuteSQL", MsgBoxStyle.Critical, "ExecuteSQL")
End Try
End Function
And this is my sub to call it where the error occurs :
Using admsDB As MySqlConnection = New MySqlConnection("server=" & rs("server") & ";uid=" & rs("user") & ";password=" & rs("pwd") & ";port=" & rs("port") & ";database=adms_db;")
admsDB.Open()
connDef.Close()
rs.Close()
'get record on admsdb
Dim logDate As DateTime
Dim str As String
str = "select userid, checktime from adms_db.checkinout in_out where userid not in (select userid " &
"from adms_db.checkinout in_out join (select str_to_date(datetime,'%d/%m/%Y %H:%i:%s') tgl, fid from zsoft_bkd_padang.ta_log) ta " &
"on ta.fid=userid and tgl=checktime)"
Dim rsAdms As MySqlDataReader = executeSQL(str, admsDB.ConnectionString, True)
Dim i As Integer
'This is where the error is, datareader stuck on the last record and doesnt EOF
While rsAdms.HasRows
'i = i + 1
logDate = rsAdms(1)
'save to ta_log
str = "insert into ta_log (fid, Tanggal_Log, jam_Log, Datetime) values ('" & rsAdms(0) & "','" & Format(logDate.Date, "dd/MM/yyyy") & "', '" & logDate.ToString("hh:mm:ss") & "', '" & logDate & "')"
executeSQL(str, oConn.ConnectionString, False)
rsAdms.Read()
End While
'del record on admsdb
str = "truncate table checkinout"
executeSQL(str, admsDB.ConnectionString, False)
End Using
i'm new to vbnet and really have a little knowledge about it,, please help me,, and thank you in advance..
The issue is that you're using the HasRows property as your loop termination expression. The value of that property never changes. Either the reader has rows or it doesn't. It's not a check of whether it has rows left to read, so reading has no effect.
You are supposed to use the Read method as your flag. The data reader begins without a row loaded. Each time you call Read, it will load the next row and return True or, if there are no more rows to read, it returns False.
You normally only use HasRows if you want to do something special when the result set is empty, e.g.
If myDataReader.HasRows Then
'...
Else
MessageBox.Show("No matches found")
End If
If you don't want to treat an empty result set as a special case then simply call Read:
While myDataReader.Read()
Dim firstFieldValue = myDataReader(0)
'...
End While
Note that trying to access any data before calling Read will throw an exception.

SQL query is not running IN VB.NET

I am fresher in VB.NET and I am trying to execute an SQL query in VB.NET but not showing any value at output. Can u please help me to find where am I going Wrong.
Dim sConnectionString As String _
= "User ID=XXX ;Password=XXX;Initial Catalog=gemXXX;Data Source=SCRBAMSDKBXXXXXX"
Dim objConn As New SqlConnection(sConnectionString)
objConn.Open()
Dim sw ,readerObj
Dim sSQL As String = "select top 1 " & sw & " = e.import from tblrelcoms r , [beant].[dbo].tblequipments e where r.IDEquipment = e.IDEquipment"
Using readerObj As SqlClient.SqlDataReader = cmdObj.ExecuteReader
Dim objCmd As New SqlCommand(sSQL, objConn)
objCmd.ExecuteNonQuery()
TextBox1.Text = sw.ToString()
The problem you have is that you cannot just concatenate a variable into SQL and expect it to be updated once the SQL is executed.
ExecuteScalar is probably the easiest way of achieving what you want:
Dim sConnectionString As String _
= "User ID=XXX ;Password=XXX;Initial Catalog=gemXXX;Data Source=SCRBAMSDKBXXXXXX"
Dim sSQL as string = "SELECT TOP 1 e.import " _
"FROM tblrelcoms r " & _
" INNER JOIN [beant].[dbo].tblequipments e " & _
" ON r.IDEquipment = e.IDEquipment " & _
"ORDER BY e.Import;"
Using connection = new SqlConnection(sConnectionString)
Using command = New SqlCommand(sSQL, connection)
connection.Open()
TextBox1.Text = command.ExecuteScalar().ToString()
End Using
End Using
Although if you need more than one column, then you could use a data reader:
Dim sConnectionString As String _
= "User ID=XXX ;Password=XXX;Initial Catalog=gemXXX;Data Source=SCRBAMSDKBXXXXXX"
Dim sSQL as string = "SELECT TOP 1 e.import " _
"FROM tblrelcoms r " & _
" INNER JOIN [beant].[dbo].tblequipments e " & _
" ON r.IDEquipment = e.IDEquipment " & _
"ORDER BY e.Import;"
Using connection = new SqlConnection(sConnectionString)
Using command = New SqlCommand(sSQL, connection)
connection.Open()
Using reader = command.ExecuteReader()
If reader.Read()
TextBox1.Text = reader.GetString(0)
End If
End Using
End Using
End Using
I have made a couple of other changes too.
Added Using blocks to ensure IDisposable objects are disposed of properly.
Updated the sql join syntax from ANSI 89 implicit joins to ANSI 92 explicit joins, as the name suggests the syntax you are using is 24 years out of date. There are many reasons to start using the new syntax, which is nicely covered in this article: Bad habits to kick : using old-style JOINs
Added an ORDER BY clause to your sql. TOP 1 without order by will give you indeterminate results (unless you only have one record, in which case top 1 is redundant)
A more complex solution would be to use output parameters, which will work and seems more in line with what you were originally trying to achieve, but is overkill for this situation (in my opinion):
Dim sConnectionString As String _
= "User ID=XXX ;Password=XXX;Initial Catalog=gemXXX;Data Source=SCRBAMSDKBXXXXXX"
Dim sSQL as string = "SELECT TOP 1 #Output = e.import " _
"FROM tblrelcoms r " & _
" INNER JOIN [beant].[dbo].tblequipments e " & _
" ON r.IDEquipment = e.IDEquipment " & _
"ORDER BY e.Import;"
Using connection = new SqlConnection(sConnectionString)
Using command = New SqlCommand(sSQL, connection)
connection.Open()
Dim p As SqlParameter = command.Parameters.Add("#Output", SqlDbType.VarChar, 255)
p.Direction = ParameterDirection.InputOutput
command.ExecuteNonQuery();
TextBox1.Text = p.Value.ToString()
End Using
End Using
*Please excuse any syntax errors, I have not used VB.Net in years, and some c# quirks may be in the below, such as I can't remember if you just don't have to use parentheses for a parameterless method, or if you can't... Hopefully there is enough basic structure to get you started

Cannot open any more tables - OleDbException was unhandled

Good Day,
My question is how to handle the exception or get rid of the error pertaining to "Cannot open any more tables". For an overview to the program I was creating, I pull out the record of subject in ms access 2007, I loop to that record to randomly assign a schedule and one by one I insert the newly record with assigned schedule in the table.
My program flow of inserting the record work only for a certain number of times, like almost 200 and at some point it stop and pop-up the oledbexception
Thanks in advance for your time on answering my question.
here is my code for more detailed overview of my program,
Private Sub Assignsched(ByVal rType As String, ByVal subjectCode As String, ByVal SecID As String, ByVal CourseCode As String)
If shrdcon.con.State = ConnectionState.Closed Then
shrdcon.con.Open()
End If
Dim RoomNum As Integer
dtARoom.Clear()
Dim stoploop As Boolean
Dim count As Integer = 0
Dim rm1 As String
RoomAssign = ""
rm1 = "SELECT * FROM tblRoom WHERE RoomType = '" & rType & "'"
Dim dat As New OleDbDataAdapter(rm1, shrdcon.con)
dat.Fill(ds, "ARoom")
stoploop = False
count = 0
Do Until stoploop = "True"
RoomNum = rndm.Next(0, ds.Tables("ARoom").Rows.Count)
RoomAssign = ds.Tables("ARoom").Rows(RoomNum).Item(1)
ScheduleGeneration()
If checkExisting(sTime, eTime, RoomAssign, daypick) = False Then
RoomA = RoomAssign
GenerateOfferingID()
Dim cmd1 As New OleDbCommand()
cmd1.CommandText = "INSERT INTO [tblSubjectOffer]([SubjectOID],[SubjectCode],[SectionID],[Day],[sTime],[eTime],[RoomName],[CourseCode]) VALUES('" & _
myId & "','" & subjectCode & "','" & SecID & "','" & daypick & "'," & sTime & "," & eTime & ",'" & RoomA & "','" & CourseCode & "')"
cmd1.Connection = shrdcon.con
cmd1.ExecuteNonQuery()
cmd1.Dispose()
Dim pipz As New OleDbCommand("Update tblGenerator Set NextNo='" & myId & "' where TableName ='" & "tblSubjectOffer" & "'", shrdcon.con)
pipz.ExecuteNonQuery()
pipz.Dispose()
stoploop = True
Else
stoploop = False
End If
If stoploop = False Then
If count = 30 Then
stoploop = True
Else
count = count + 1
End If
End If
Loop
End Sub
This is typical error happens with Microsoft Jet engine when You have exceeded the maximum number of open TableIDs allowed by the Microsoft Jet database engine, which is 2048 with Jet3.5 engine and 1024 with older engines.
Even though you are closing the Command objects after each use, you are still using the same connection for the whole process, which actually holds the TableID's and is at some point of time exceeding the number of allowed open TableID's.
A probable solution would be to update the Jet Engine with the latest, which is available here
It might solve your problem, but if you are already using the latest engine, you have to look into other options to reduce the number of DB operations.
Try using the UpdateBatch method for applying the updates as a batch.
Hope this helps
Private Sub Command1_Click()
Dim myConnection As ADODB.Connection
Dim rsData As ADODB.Recordset
Set myConnection = New ADODB.Connection
myConnection.ConnectionString = "xxxxxxxxxxxxxxxxxxxx"
myConnection.Open
Set rsData = New ADODB.Recordset
rsData.CursorLocation = adUseClient
rsData.Open "select * from mytable", myConnection, adOpenStatic, adLockBatchOptimistic
For i = 1 To 10000
rsData.AddNew
rsData.Fields(0).Value = 1
rsData.Fields(1).Value = 2
Next i
rsData.UpdateBatch
rsData.Close
myConnection.Close
Set rsData = Nothing
End Sub
Good Evening,
Recently I encounter this type of error and i was able to resolve it by adding
con.close and call conState (a procedure conState- check below) before any insert/update or select statement
In my code i have something like
For i = 0 To DataGridView1.RowCount - 1
reg = DataGridView1.Rows(i).Cells(0).Value
Label2.Text = reg
'i added this two lines
***con.Close()***
***Call conState()***
Dim cmdcheck As New OleDbCommand("Select * from [2015/2016 UG CRF] where regno ='" & reg & "'", con)
Dim drcheck As OleDbDataReader
drcheck = cmdcheck.ExecuteReader
If drcheck.Read = True Then
GoTo A
End If
coursesFirst = String.Empty
coursesSecond = String.Empty
creditFirst = 0
creditSecond = 0
Dim cmdlevel As New OleDbCommand("Select * from [2015/2016 UG registration Biodata 5 april 16] where regno ='" & reg & "'", con)
Dim drlevel As OleDbDataReader
drlevel = cmdlevel.ExecuteReader
If drlevel.Read = True Then
level = drlevel.Item("level").ToString
faculty = drlevel.Item("faculty").ToString
program = drlevel.Item("programme").ToString
End If
...............
next
The conState is a connection testing if connection is closed is should open it again like in below
Public Sub conState()
If con.State = ConnectionState.Closed Then
con.Open()
End If
End Sub
This stop the error message
I got this exception in my C# application and the cause was using OleDbDataReader instances without closing them:
OleDbDataReader reader = cmd.ExecuteReader();
bool result = reader.Read();
reader.Close(); // <= Problem went away after adding this
return result;

Report only shows the last record

I have to display data from VB.NET code to crystal report...and I'm doing everything from the code, so the problem is that I have to display multiple data from for-each loop, this is the code:
Private Sub Print_Row(ByVal pp As Boolean)
Dim rptDokument As New ReportDocument, brkop As Integer
Dim rw_mat As DataRow
Dim cn As OracleClient.OracleConnection = New OracleClient.OracleConnection(Gdb_conn)
' Objects used to set the parameters in the report
Dim pCollection As New CrystalDecisions.Shared.ParameterValues
Dim pTSJ As New CrystalDecisions.Shared.ParameterDiscreteValue
Dim pNaziv As New CrystalDecisions.Shared.ParameterDiscreteValue
Dim pKolicina As New CrystalDecisions.Shared.ParameterDiscreteValue
Dim pTezina As New CrystalDecisions.Shared.ParameterDiscreteValue
Try
rptDokument.Load(Gpath & "PakLista.rpt")
pTSJ.Value = barcode.Text
pCollection.Add(pTSJ)
rptDokument.DataDefinition.ParameterFields("pTSJ").ApplyCurrentValues(pCollection)
cn.Open()
Dim myQuery As String = "SELECT S.TSJ,M.NAZ_MAT, S.IBRMAT, S.KOLICINA, S.TEZINA " & _
"FROM TWM_SADRZAJ S, TWM_MATER M, TWM_ATRIBUT A, TWM_PAKIR PAK " & _
"WHERE(S.VLASNIK_MP = M.VLASNIK_MP) " & _
"AND S.IBRMAT = M.IBRMAT " & _
"AND S.ATR_ID = A.ATR_ID (+) " & _
"AND PAK.VLASNIK_MP (+) = S.VLASNIK_MP " & _
"AND PAK.IBRMAT (+) = S.IBRMAT " & _
"AND PAK.PAK (+) = S.PAK " & _
"AND (S.TSJ = '" & barcode.Text & "') " & _
"ORDER BY S.IBRMAT"
Dim da As OracleClient.OracleDataAdapter = New OracleClient.OracleDataAdapter(myQuery, cn)
Dim ds As New DataSet
da.Fill(ds, "TWM_SADRZAJ")
For Each rw_mat In ds.Tables("TWM_SADRZAJ").Rows
If (rw_mat.Item("NAZ_MAT") Is DBNull.Value) Then
pNaziv.Value = ""
Else
pNaziv.Value = CStr(rw_mat.Item("NAZ_MAT"))
End If
If (rw_mat.Item("KOLICINA") Is DBNull.Value) Then
pKolicina.Value = ""
Else
pKolicina.Value = CStr(rw_mat.Item("KOLICINA"))
End If
If (rw_mat.Item("TEZINA") Is DBNull.Value) Then
pTezina.Value = ""
Else
pTezina.Value = CStr(rw_mat.Item("TEZINA"))
End If
pCollection.Add(pNaziv)
rptDokument.DataDefinition.ParameterFields("pNaziv").ApplyCurrentValues(pCollection)
pCollection.Add(pKolicina)
rptDokument.DataDefinition.ParameterFields("pKolicina").ApplyCurrentValues(pCollection)
pCollection.Add(pTezina)
rptDokument.DataDefinition.ParameterFields("pTezina").ApplyCurrentValues(pCollection)
Next rw_mat
If pp Then
Dim frm As New frmPrint_preview
frm.crvDocument.ReportSource = rptDokument
frm.ShowDialog()
Else
Dim pd As New PrintDialog
pd.PrinterSettings = New PrinterSettings
If pd.ShowDialog(Me) Then
For brkop = 1 To pd.PrinterSettings.Copies
rptDokument.PrintOptions.PrinterName = pd.PrinterSettings.PrinterName
rptDokument.PrintToPrinter(1, False, 1, 99999)
Next brkop
End If
End If
Catch Exp As LoadSaveReportException
MsgBox("Incorrect path for loading report.", MsgBoxStyle.Critical, "Load Report Error")
Catch Exp As System.Exception
MsgBox(Exp.Message, MsgBoxStyle.Critical, "General Error")
End Try
End Sub
The problem is in this section:
pCollection.Add(pNaziv) rptDokument.DataDefinition.ParameterFields("pNaziv").ApplyCurrentValues(pCollection)
pCollection.Add(pKolicina) rptDokument.DataDefinition.ParameterFields("pKolicina").ApplyCurrentValues(pCollection)
pCollection.Add(pTezina) rptDokument.DataDefinition.ParameterFields("pTezina").ApplyCurrentValues(pCollection)
It has to be out side for each loop to gather all the data, but the problem is no mater where i put this code it only displays the last record from data row for let's say 5 records in crystal report...I know it's peace of cake but I'm relay stuck here so I would appreciate a little help.
It is normal that the report only shows the last record, because you try to pass the data as parameters. Instead you should set the datasource programmatically, you can see how to do it here ^
ReportDocument.SetDataSource Method
and here you can find a complete example of how to create a typed dataset to use on your report
Create report by vb.net and crystal report