Auto update access tables Cells with random numbers from vb.net - vb.net

I searched many forums but didn't find any solution. I want to update access table cells from Vb.net. My table has fields:
[PanelNumber],[Date], [PVValue]
In Panel number field, there is some text like "Panel 1", "Panel 2" etc..
from vb, i will select that "Panel 1" after clicking a button, i need to fill that "PVValue" field with random numbers in given range, plz check my code below, when i try with this code, i am always getting same number in all rows
but need separate number (may be repeated in some rows)
LogTable2 is my table name
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=LoggedData.accdb;Jet OLEDB:Database Password=GodavarthiSuresh;"
myNewConnection.ConnectionString = connString
myNewConnection.Open()
Dim UpdateString As String = "update LogTable2 set [pvvalue]= #rndVal1 where panelnumber='" & panelnametxt.Text & "'"
Dim UpdateCmd As New OleDb.OleDbCommand(UpdateString, myNewConnection)
UpdateCmd.Parameters.Clear()
Randomize()
UpdateCmd.Parameters.AddWithValue("#rndVal1", GetRandom())
Try
UpdateCmd.ExecuteNonQuery()
UpdateCmd.Dispose()
myNewConnection.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
' this is the function to get random number in given range
Public Function GetRandom() As Integer
Static Generator As System.Random = New System.Random()
Return Generator.Next(825, 850)
End Function

If you have multiple rows for each panel and you want them to have different values, you need to update them individually. Its is not true that update command will be "called" 5 times if there are five rows associated. It will be executed once per click event.
To do what it sounds like you want, you need a unique identifier for each such as an AutoIncrement ID column.
Private RNG As New Random()
Private Sub btnUpdate_Click(etc...
Dim sql = "SELECT ID FROM LogTable2 WHERE panelnumber = #pnl"
Dim pnlList As New List(Of Int32)
Using con As OleDbConnection = GetACEConnection()
Using cmd As New OleDbCommand(sql, con)
con.Open()
cmd.Parameters.AddWithValue("#pnl", panelnametxt.Text)
' get affected row IDs into a list;
Using rdr As OleDbDataReader = cmd.ExecuteReader
While rdr.Read
pnlList.Add(Convert.ToInt32(rdr.Item("ID")))
End While
End Using ' close, dispose of reader
End Using ' dispose of cmd
' not sure you need a new command object
sql = "UPDATE LogTable2 SET pvvalue = #rVal WHERE ID = #id"
Using pcmd As New OleDbCommand(sql, con)
' loop thru ID list and update each row with
' new random value 825-849 inclusive
For n As Int32 = 0 To pnlList.Count - 1
pcmd.Parameters.AddWithValue("#rVal", RNG.Next(825, 850))
pcmd.Parameters.AddWithValue("#id", pnlList(n))
pcmd.ExecuteNonQuery()
' clear for next iteration
pcmd.Parameters.Clear()
Next
End Using ' close and dispose of pcmd
End Using ' close and dispose of connection
End Sub
I dont like scattering the connection string in every method which opens a connection, so a method for that is nice to have.
Notes:
This depends on a unique ID column which is AutoIncrement (PK). If you have some other unique identifier, use it but you have to have some way to identify rows individually.
Rather than a method to create a random value, since it is just one line, it might be easier to just use your RNG directly as shown.
I cant test the code, but it should be close.
Use Using blocks to close and dispose of DBObjects like connections, command and reader otherwise you can run out of resources.
You can also initialize Command objects with the SQL and COnnection when you declare it rather than setting them as properties. It makes the code a little more compact and less likely that you forget them.
Randomize does nothing - it is meant to be used with the old VB6 Rnd(). You only need to [Escape] keywords in SQL, not every column name and pvvalue is not a keyword.
A DataTable instead of a Reader could be used to get the rows but I am not sure it is any simpler.
Finally, elements of a SQL WHERE clause can also be parameterized; there is no need to concat them just because it is a where rather than a column value.

you can do this in database level,add auto increment value to database field

Related

How can i resolve ExecucuteNonQuery throwing exception Incorrect syntex near '?'

Dim StrSql = "update student set id=?"
Updated (StrSql,15)
Public Function Updated (ByVal strSql As String, ByVal ParamArray Parameters As String ())
For Each x In Parameters
cmd.Parameters.AddWithValue("?",x)
Next
cmd.ExecuteNonQuery()
End Function
You didn't leave us much to go on; as jmcilhinney points out, you need to add more detail to future questions. For example in this one you have code there that doesn't compile at all, doesnt mention the types of any variable, you don't give the name of the database...
...I'm fairly sure that "Incorrect syntax near" is a SQL Server thing, in which case you need to remember that it (re)uses named parameters, unlike e.g. Access which uses positional ones:
SQL Server:
strSql = "SELECT * FROM person WHERE firstname = #name OR lastname = #name"
...Parameters.AddWithValue("#name", "Lee")
Access:
strSql = "SELECT * FROM person WHERE firstname = ? OR lastname = ?"
...Parameters.AddWithValue("anythingdoesntmatterwillbeignored", "Lee")
...Parameters.AddWithValue("anythingdoesntmatterwillbeignoredalso", "Lee")
This does mean your function will need to get a bit more intelligent; perhaps pass a ParamArray of KeyValuePair(Of String, Object)
Or perhaps you should stop doing this way right now, and switch to using Dapper. Dapper takes your query, applies your parameters and returns you objects if you ask for them:
Using connection as New SqlConnection(...)
Dim p as List(Of Person) = Await connection.QueryAsync(Of Person)( _
"SELECT * FROM person WHERE name = #name", _
New With { .name = "John" } _
)
' use your list of Person objects
End Using
Yep, all that adding parameters BS, and executing the reader, and converting the results to a Person.. Dapper does it all. Nonquery are done like connection.ExecuteAsync("UPDATE person SET name=#n, age=#a WHERE id=#id", New With{ .n="john", .a=27, .id=123 })
http://dapper-tutorial.net
Please turn on Option Strict. This is a 2 part process. First for the current project - In Solution Explorer double click My Project. Choose Compile on the left. In the Option Strict drop-down select ON. Second for future projects - Go to the Tools Menu -> Options -> Projects and Solutions -> VB Defaults. In the Option Strict drop-down select ON. This will save you from bugs at runtime.
Updated(StrSql, 15)
Your Updated Function calls for a String array. 15 is not a string array.
Functions need a datatype for the return.
cmd.Parameters.AddWithValue("?", X)
cmd is not declared.
You can't possible get the error you mention with the above code. It will not even compile, let alone run and produce an error.
It is not very helpful to write a Function that is trying to be generic but is actually very limited.
Let us start with your Update statement.
Dim StrSql = "update student set id=?"
The statement you provided will update every id in the student table to 15. Is that what you intended to do? ID fields are rarely changed. They are meant to uniquely identify a record. Often, they are auto-number fields. An Update command would use an ID field to identify which record to update.
Don't use .AddWithValue. See http://www.dbdelta.com/addwithvalue-is-evil/
and
https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/
and another one:
https://dba.stackexchange.com/questions/195937/addwithvalue-performance-and-plan-cache-implications
Here is another
https://andrevdm.blogspot.com/2010/12/parameterised-queriesdont-use.html
Since you didn't tell us what database you are using I guessed it was Access because of the question mark. If it is another database change the connection, command and dbType types.
Using...End Using block ensures you connection and command are closed and disposed even if there is an error.
Private ConStr As String = "Your Connection String"
Public Function Updated(StudentNickname As String, StudentID As Integer) As Integer
Dim RetVal As Integer
Using cn As New OleDbConnection(ConStr),
cmd As New OleDbCommand("Update student set NickName = #NickName Where StudentID = #ID", cn)
cmd.Parameters.Add("#NickName", OleDbType.VarChar, 100).Value = StudentNickname
cmd.Parameters.Add("#ID", OleDbType.Integer).Value = StudentID
cn.Open()
RetVal = cmd.ExecuteNonQuery
End Using
Return RetVal
End Function
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim RowsUpdated = Updated("Jim", 15)
Dim message As String
If RowsUpdated = 1 Then
message = "Success"
Else
message = "Failure"
End If
MessageBox.Show(message)
End Sub
This code keeps your database code separated from user interface code.

Adding Data to DataTable

This code is recording the inserted IDs in arraylist and when press on button it should create loop for this array and get the data of each ID from the array and put it in Datatable and add the new data while looping to the datatable and finaly show it in datagridview .
The problem in the result when I insert one record it works fine but when I insert more than one the datagridview shows just the last one , what the mistake that I Done ?!!
In Mainform
Public Inserted_record_hold_dt As New DataTable
Public Inserted_record_dt As New DataTable
Public Sub Addcolumnstodatagrid()
Inserted_record_dt.Columns.Add("ID")
Inserted_record_dt.Columns(0).AutoIncrement = True
Inserted_record_dt.Columns.Add("drawingname")
Inserted_record_dt.Columns.Add("serial")
End Sub
and call this in main_Load
Addcolumnstodatagrid()
And this in the show button when click to loop on the array list that already have the latest ID's that has been added
Private Sub show_btn_Click(sender As System.Object, e As System.EventArgs) Handles show_btn.Click
Dim InsertedID As Integer
Inserted_record_dt.Clear()
Dim R As DataRow = Inserted_record_dt.NewRow
'Loop For each ID in the array "Inserted_List_Array"
For Each InsertedID In mainadd.Inserted_List_Array
'MsgBox(InsertedID.ToString)
Dim cmd As New SqlCommand("select drawingname , serial from main where drawingid = '" & InsertedID & "'", DBConnection)
DBConnection.Open()
Inserted_record_hold_dt.Load(cmd.ExecuteReader)
Try
R("drawingname") = Inserted_record_hold_dt.Rows(0).Item(0)
R("serial") = Inserted_record_hold_dt.Rows(0).Item(1)
Inserted_record_dt.Rows.Add(R)
Catch
End Try
'MsgBox("added")
DBConnection.Close()
cmd = Nothing
Inserted_record_hold_dt.Clear()
Next
sendmail.Show()
sendmail.Mail_DGView.DataSource = Inserted_record_dt
End Sub
Please tell me what is the problem in my code .
Your mistake is in declaring the R variable just one time outside the loop. In this way you continuously replace the values on the same instance of a DataRow and insert always the same instance.
Just move the declaration inside the loop
For Each InsertedID In mainadd.Inserted_List_Array
......
Try
Dim R As DataRow = Inserted_record_dt.NewRow
R("drawingname") = Inserted_record_hold_dt.Rows(0).Item(0)
R("serial") = Inserted_record_hold_dt.Rows(0).Item(1)
Inserted_record_dt.Rows.Add(R)
Catch
....
Next
Another important thing to do is to remove the empty Try/Catch because you are just killing the exception (no message, no log) and thus you will never know if there are errors in this import. At the end you will ship a product that could give incorrect results to your end user.

Database Lookup From ComboBox selection

I have a question about database values and how to determine the id of a value that has been changed by the user at some point.
As it is currently set up there is a combobox that is populated from a dataset, and subsequent text boxes whose text should be determined by the value chosen from that combobox.
So let's say for example you select 'Company A' from the combobox, I would like all the corresponding information from that company's row in the dataset to fill the textboxes (Name = Company A, Address = 123 ABC St., etc.,)
I am able to populate the combobox just fine. It is only however when I change the index of the combobox that this specific error occurs:
An unhandled exception of type 'System.Data.OleDb.OleDbException'
occurred in System.Data.dll
Additional information: Data type mismatch in criteria expression.
Here is the corresponding code:
Imports System.Data.OleDb
Public Class CustomerContact
Dim cn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|datadirectory|\CentralDatabase.accdb;")
Dim da As New OleDbDataAdapter()
Dim dt As New DataTable()
Private Sub CustomerContact_Load(sender As Object, e As EventArgs) Handles MyBase.Load
cn.Open()
da.SelectCommand = New OleDbCommand("select * from Customers", cn)
da.Fill(dt)
Dim r As DataRow
For Each r In dt.Rows
cboVendorName.Items.Add(r("Name").ToString)
cboVendorName.ValueMember = "ID"
Next
cn.Close()
End Sub
Private Sub cboVendorName_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboVendorName.SelectedIndexChanged
cn.Open()
da.SelectCommand = New OleDbCommand("select * from Customers WHERE id='" & cboVendorName.SelectedValue & "'", cn)
da.Fill(dt)
Dim r As DataRow
For Each r In dt.Rows
txtNewName.Text = "Name"
txtAddress.Text = "Address"
Next
cn.Close()
End Sub
The error is caught at Line 24 of this code, at the second da.Fill(dt) . Now obviously from the exception I know that I am sending in a wrong datatype into the OleDbCommand, unfortunately I am a novice when it comes to SQL commands such as this. Also please keep in mind that I can't even test the second For loop, the one that is supposed to fill the Customer information into textboxes (for convenience I only copied the first two textboxes, of which there are nine in total). I am think I could use an If statement to determine if the row has been read, and from there populate the textboxes, but I will jump that hurdle when I can reach it.
Any guidance or suggestions would be much appreciated. Again I am a novice at managing a database and the code in question pertains to the project my current internship is having me write for them.
Since you already have all the data from that table in a DataTable, you dont need to run a query at all. Setup in form load (if you must):
' form level object:
Private ignore As Boolean
Private dtCust As New DataTable
...
Dim SQL As String = "SELECT Id, Name, Address, City FROM Customer"
Using dbcon = GetACEConnection()
Using cmd As New OleDbCommand(SQL, dbcon)
dbcon.Open()
dtCust.Load(cmd.ExecuteReader)
End Using
End Using
' pk required for Rows.Find
ignore = True
dtCust.PrimaryKey = New DataColumn() {dtCust.Columns(0)}
cboCust.DataSource = dtCust
cboCust.DisplayMember = "Name"
cboCust.ValueMember = "Id"
ignore = False
The ignore flag will allow you to ignore the first change that fires as a result of the DataSource being set. This will fire before the Display and Value members are set.
Preliminary issues/changes:
Connections are meant to be created, used and disposed of. This is slightly less true of Access, but still a good practice. Rather than connection strings everywhere, the GetACEConnection method creates them for me. The code is in this answer.
In the interest of economy, rather than a DataAdapter just to fill the table, I used a reader
The Using statements create and dispose of the Command object as well. Generally, if an object has a Dispose method, put it in a Using block.
I spelled out the columns for the SQL. If you don't need all the columns, dont ask for them all. Specifying them also allows me to control the order (display order in a DGV, reference columns by index - dr(1) = ... - among other things).
The important thing is that rather than adding items to the cbo, I used that DataTable as the DataSource for the combo. ValueMember doesn't do anything without a DataSource - which is the core problem you had. There was no DataSource, so SelectedValue was always Nothing in the event.
Then in SelectedValueChanged event:
Private Sub cboCust_SelectedValueChanged(sender As Object,
e As EventArgs) Handles cboCust.SelectedValueChanged
' ignore changes during form load:
If ignore Then Exit Sub
Dim custId = Convert.ToInt32(cboCust.SelectedValue)
Dim dr = dtCust.Rows.Find(custId)
Console.WriteLine(dr("Id"))
Console.WriteLine(dr("Name"))
Console.WriteLine(dr("Address"))
End Sub
Using the selected value, I find the related row in the DataTable. Find returns that DataRow (or Nothing) so I can access all the other information. Result:
4
Gautier
sdfsdfsdf
Another alternative would be:
Dim rows = dtCust.Select(String.Format("Id={0}", custId))
This would return an array of DataRow matching the criteria. The String.Format is useful when the target column is text. This method would not require the PK definition above:
Dim rows = dtCust.Select(String.Format("Name='{0}'", searchText))
For more information see:
Using Statement
Connection Pooling
GetConnection() method aka GetACEConnection

How do I read data in drop down?

I can view the data in textbox but the problem is, if I change it to drop down to show multiple data, it will give an empty data ..
Private Sub textbox2_SelectionChangeCommitted(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox2.KeyPress
Try
cmd = New Odbc.OdbcCommand("SELECT maker FROM pcba_info.tblvendorpartnumber WHERE partnumber ='" & Trim(TextBox2.Text.TrimEnd()) & "'", con)
dr = cmd.ExecuteReader
If dr.Read Then
TextBox55.Text = dr("maker").ToString ----------> return single data
TextBox12.SelectedIndex = dr("maker").ToString -----------> no data
dgvcertifiedoperator.DataSource = dt
dgvcertifiedoperator.Update()
dgvcertifiedoperator.Refresh()
End If
Catch ex As Exception
Debug.WriteLine("Plz check the parts" & ex.Message)
End Try
End Sub
I am assuming that your TextBox12 represents a dropdown. In this case assigning SelectedIndex to a string is incorrect (just think about it for a second - an index cannot be a string, i.e. AAA is not an index). Use Option Strict On to prevent such errors.
See, by default, VB.NET does not prevent you from doing it, because theoretically a string can be an integer, so this statement can work. But it does not mean it will work 100% of the time. Option Strict validates type conversion to ensure it always works, or your code does not compile.
Back to your question, one way to do it is to accumulate values in a list, then make that list a data source for your dropdown, like this:
Dim lst As New List(Of String)
While dr.Read Then
lst.Add(dr("maker").ToString)
End While
TextBox12.DataSource = lst
You can then retrieve current value by using TextBox12.SelectedItem, cast to string:
DirectCast(TextBox12.SelectedItem, String)
A side note - make sure your controls are named accordingly. TextBox is usually reserved for, well, text boxes. Dropdowns are usually MakerComboBox, MakerDropDown etc. Avoid naming your controls like TextBox56 and ComboBox188, because those numbers are meaningless for another developer. Even if you are the only one on the project, consider us helping you with it.

<VB> Highlighting Selected dates from database in Calendar control

I am currently using VB. I want to do a Calendar Control which have dates highlighted/selected. All these dates are retrieved from a database.
First thing I need to know is how to put all the dates into an array
Second thing I need to know is how to highlight all the dates in the array.
I have done some research on the internet and they said something about selectedDates and selectedDates collection and dayrender. But frankly speaking, I can't really find any VB codes regarding this. Dates format will be in dd/MM/yyyy
Imports System.Data.SqlClient
Partial Class _Default
Inherits System.Web.UI.Page
Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
Dim connectionString As String = ConfigurationManager.ConnectionStrings("CleanOneConnectionString").ConnectionString
Dim connection As SqlConnection = New SqlConnection(connectionString)
connection.Open()
Dim sql As String = "Select schedule From OrderDetails Where schedule is not null"
Dim command As SqlCommand = New SqlCommand(sql, connection)
Dim reader As SqlDataReader = command.ExecuteReader()
If (reader.Read()) Then
If (reader.HasRows) Then
While reader.Read()
myCalendar.SelectedDates.Add(CType(reader.GetDateTime(0), Date))
End While
End If
End If
reader.Close()
connection.Close()
myCalendar.SelectedDayStyle.BackColor = System.Drawing.Color.Red
End Sub
End Class
My Calendar
<asp:Calendar ID="myCalendar" runat="server" ShowGridLines="True">
</asp:Calendar>
Updated with what I have done, but still does not show
Thanks for the help
Assume you have a DataTable named myDates, and a Calendar control named myCalendar:
For i As Int = 0 To myDates.Rows.Count - 1
myCalendar.SelectedDates.Add(CType(myDates.Row(i)(0), Date)
Next
You can declare the highlighting in your markup:
<asp:Calendar ID="myCalendar" runat="server">
<SelectedDayStyle BackColor="red" />
</asp:Calendar>
Or programatically:
myCalendar.SelectedDayStyle.BackColor = System.Drawing.Color.Red
UPDATE For SqlDataReader (VB.NET this time)
If reader.HasRows Then
While reader.Read()
myCalendar.SelectedDates.Add(CType(reader(0), Date)
End While
End If
UPDATE based on OP's code
Are you getting any errors when the code runs? SqlDataReader.GetDateTime will throw an InvalidCastException if the column being read isn't a DateTime column.
I'm wondering if it's a format issue? Can you verify the data type of the column in the database, as well as the format the date is being stored in?
I've modified your code a bit with a couple of suggestons.
Imports System.Data.SqlClient
Partial Class _Default Inherits System.Web.UI.Page
Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
Dim connectionString As String = ConfigurationManager.ConnectionStrings("CleanOneConnectionString").ConnectionString
' Using blocks will automatically dispose of the object, and are
' pretty standard for database connections
Using connection As New SqlConnection(connectionString)
connection.Open()
Dim sql As String = "Select schedule From OrderDetails Where schedule is not null"
Dim command As SqlCommand = New SqlCommand(sql, connection)
Dim reader As SqlDataReader = command.ExecuteReader()
' This is not needed - in fact, this line will "throw away"
' the first row in the row collection
'If (reader.Read()) Then
If (reader.HasRows) Then
While reader.Read()
myCalendar.SelectedDates.Add(CType(reader.GetDateTime(0), Date)) End While
End If
reader.Close()
' Not needed because of the Using block
'connection.Close()
End Using
myCalendar.SelectedDayStyle.BackColor = System.Drawing.Color.Red
End Sub
End Class
For the second part of your question, you can see on this post how to highlight specified days, albeit using C# syntax.
I'm going to assume a L2S format is being used to fetch the dates for now (comment with actual implementation if you need better detail).
I would recommend the dates you want to select be held in a variable on the form (instead of scoped to the function) to prevent database queries running everytime a day is rendered. With that in mind, here is some sample code (free-hand so please excuse and comment on basic/troubling syntax issues):
Private DatesToHighlight As IEnumerable(Of Date)
' implementation details provided so commented this bit out, see EDIT below
'Protected Sub PopulateDatesToHighlight()
' DatesToHighlight = db.SomeTable.Select(Function(n) n.MyDateField)
'End Sub
Protected Sub DayRenderer(ByVal object As Sender, ByVal e As DayRenderEventArgs)
If DatesToHighlight.Contains(e.Day.Date) Then
e.Cell.BackColor = System.Drawing.Color.Red
End If
End Sub
As specified in the question I linked, you'll need to change the markup for the calendar control to provide the ondayrender parameter like so ondayrender="DayRenderer"
Regarding changing your dates to an array, it depends what format they are in at the start. If in anything that inherits from IEnumerable then you can use ToArray(). If they are just variables you can initialise the array with the dates
Dim myDates() As Date = {dateVar1, dateVar2}
Hope that helps?
EDIT: (In response to OP's addition of code)
To get from your data reader to an array (though I'm not convinced you need an array) I would do the following:
' using the variable I declared earlier
DatesToHighlight = New IEnumerable(Of Date)
If reader.HasRows Then
Dim parsedDate As Date
While reader.Read()
If Date.TryParse(reader(0), parsedDate) Then
DatesToHighlight.Add(parsedDate)
End If
End While
End If
Dim myArrayOfDates() As Date = DatesToHighlight.ToArray()