How to search a database in VB2010 - vb.net

I'm using Visual basic 2010, I've created 3 text boxes with which i want the user to enter an ID number into the id number and all others will populate the first and last name associated with the ID. I also want the datagridview to hone in on the row with the corresponding first and last name and ID number. I appreciate all your help, thanks!
I populated my database with this:
Last_NameTextBox.Text = strLastName.ToString
First_NameTextBox.Text = strStudent.ToString
IDTextBox.Text = strIdNumber.ToString
DataGridViewStudents.DataSource = MyDataRow.Table()
DataGridViewStudents.Rows.Add(MyDataRow)
'Search id
Dim findId() As Data.DataRow
findId = MyDataRow.GetChildRows(txtId.Text)

Related

Auto generate id number in vb.net

I am creating a library management system. I want to generate different book code for different book genre. For eg:- There is a combo box with book three book genres(novel,literature,poem) and there is another text box with book code. I want if someone chooses novel in comboBox, book code starts form N001 and if someone chooses literature in comboBox, book code starts from L001 and if someone chooses poem, book code starts from P001.
(My vb application is connected with ms access database.)
I see several problems with your fundamental numbering strategy.
Most library numbering systems (Dewey Decimal/Library of Congress) factor sort ordering abilities to their numbering system and allow for future additions to be able to sort higher without needing to shift the number of all other items. With your incremental strategy, how would you accommodate inserting a book later in the process?
If you set up with three digits of numbering, what would you do once you get 1000 books in a category?
While you could use a magic number table that includes the last id allocated per category and increment it as you add a new book. If you have more than one user, there is a potential for a race condition where two users get the same last number and both try to increment it at the same time landing on the same new Id.
I typically recommend keeping a generic ID that has no meaning in the system. This number would be set as an Auto Number in Access and the database would generate new Ids when records are added and ensure that you don't have the collision issue above. If you absolutely need a publically viewable Id, you can use the magic number strategy for a separate BookNumber column that isn't used for record identity. That way if you have a collision in the future, data won't get corrupted.
there are several schools of thought on how one can approach this.
One way? Well, you say have a book type or some such, and then you have that book code. It would be a simple number column without the prefix (P, B etc.).
So, to get the next number, you would then go:
myBookNumber = DMAX("BookNumber","tblBooks","BookType = 'P')
MyBookNumber = MyBookNumber + 1
So, you simply store the book number separate from the prefix. In forms, reports etc., you can then always display the book number like rst!BookType & rst!BookNumber
Another way, which I prefer is to create a table that allows you to get the next book number This also makes it easy to add more types, and better is such a design lets you set the starting number. This approach is also often used for invoice numbers.
So, you create a table called tlbBookIncrements. It will look like this:
ID: (pk - autonumber)
BookType: text (the one char book type)
BookNumber: Number the next book number to assign.
You then build a function like this:
Public Function GetNextBookN(strBookType As String) As Long
Dim strSQL As String
Dim rst As DAO.Recordset
strSQL = "SELECT * FROM tblBookIncrement where BookType = '" & strBookType & "'"
Set rst = CurrentDb.OpenRecordset(strSQL)
If rst.RecordCount = 0 Then
' this book type does not exist - lets add it and start at 1
rst.AddNew
rst!BookType = strBookType
rst!booknumber = 1
End If
GetNextBookN = rst!booknumber
rst!booknumber = rst!booknumber + 1
rst.Update
rst.Close
End Function
Update:
The poster was using vb.net, not VBA, my bad.
Here is the above as vb.net, it really much the same.
Public Function GetNextBookN(strBookType As String) As Integer
Using mycon As New OleDbConnection(My.Settings.ConnectionString1)
Dim strSQL As String
strSQL = "SELECT * FROM tblBookIncrement where BookType = '" & strBookType & "'"
Using da As New OleDbDataAdapter(strSQL, mycon)
Dim cmdBuilder = New OleDbCommandBuilder(da)
Dim rst As New DataTable
da.Fill(rst)
da.AcceptChangesDuringUpdate = True
With rst
If .Rows.Count = 0 Then
With .Rows.Add
.Item("BookType") = strBookType
.Item("booknumber") = 1
End With
GetNextBookN = 1
Else
GetNextBookN = .Rows(0).Item("booknumber")
.Rows(0).Item("booknumber") += 1
End If
End With
da.Update(rst)
End Using
End Using
End Function
So, now anytime you need a book number, you can go like this:
Say, in a form, you need to assign the book number, you could go like this:
You could say use the on-insert event of the form, and go like this:
me!BookNumber = me!bookType & GetNextBookN(me!bookType)
So, the above would say if the bookType is "P", result in P101 if the numbering table has a book type of P and the booknumber set to 101. And of course once you pull that number, then the handy dandy function will increment the number for you.
And I also added the feature that if the type requested does not exist, then we add the type and start at 1. This way, the code works as you over time add new types of books, and then the book number table will always work, and have available a next book number easily available in code.

Visual Studio VB - Query from datatable instead of database

I'm a veteran Excel VBA coder who has been thrown into the deep end on this form <> Access database project. I'm working on one part of the form where users (employees) will select the site location (84 total, but not all will show based on what team they're on) and then select the department within that site. There are 2,189 total departments, so the department list should only show those for that site.
The database that we query from and update to is on a VERY slow server, so I want to pull a whole lookup table at the beginning (restricted down to those that team works on) into a datatable, then populate the first combo box with unique sites within that datatable, then populate the second combo box with all of the departments at that site.
The datatable is more or less just | ID | Site | Department |. I can fill that datatable just fine and leave it sitting in cache. And I could loop through the datatable to populate the combo boxes, but that's slower than it can be.
So is there a way to perhaps query from that datatable to either directly populate the combo boxes, or to fill a secondary datatable then to the combo boxes? For the first box, it's finding UNIQUE sites that is the challenge. Then for the second, it's departments where the site equals the one selected in the first box.
Thanks!
You can use Linq to Sql as mentioned by "Andrew Morton", i have made an exemple for you :
Dim da As SqlDataAdapter = New SqlDataAdapter("select * from YourDatatable, con)
Dim dt As New Data.DataTable()
da.Fill(dt)
'You can change here your condition as you need
Dim query = (From d1In dt.AsEnumerable() _
Where d1.Field(Of Integer)("ID") = 1 And d1.Field(Of Integer)
Select d1!ID, order!Site , d1!Department ,
If query.Count > 0 Then
comboBox1 .Items .Add (query(0).Site) 'Fill your Combobox1
end if
Dim query2 = (From d2 In dt.AsEnumerable() _
Where d2.Field(Of Integer)("ID") = 2 And d2.Field(Of Integer)
Select d2!ID, order!Site , d2!Department ,
If query2.Count > 0 Then
comboBox2 .Items .Add (query2(0).Department ) 'Fill your Combobox2
end if

Add Query with Month filter to an Access Database with Date/Time Field

I have an Access Database with many fields connected through a datagridview in my vb.net project. Two of these fields contain Date/Time Values. I want to create a query through the query builder that uses input from the user to find records that match the dates the user wants. This "where clause" works :
WHERE BETWEEN ? AND ?
This creates a toolstrip in which I can input 2 dates so that the query can fill the datagridview with the records.
What I want now is to make a query like the above only this time the user inputs the name of a month he wants (ex. February or 02 ). Is there any way to do that ?
EDIT: Tried using Plutonix's code (Sailing is the Column name) :
WHERE SAILING BETWEEN #01/31/yyyy# AND #03/01/yyyy#
and I got this error: "Cannot convert entry to valid datetime TO_DATE function might be required"
EDIT 2: I have created a combobox containing all 12 months and I have a commandbutton. I want to find a way so that if the user selects one of the 12 months from that combobox and clicks the commandbutton, to have the datagridview control (access database) show him only the records that go with that month based on their datetime(Short Date) fields. What code should I put in my commandbutton_click ?
Eventually I created a long query where I added a "Between ? and ?" in my where clause for every Year included in the database (2004-2015), created a huge if clause that gives the beginnings and endings of the month requested for every year and used all those strings to query the database.
If Month.Text = "JANUARY" Then
A04A = "01/01/04"
A04B = "31/01/04"
A05A = "01/01/05"
A05B = "31/01/05"
A06A = "01/01/06"
A06B = "31/01/06"
A07A = "01/01/07"
A07B = "31/01/07"
A08A = "01/01/08"
A08B = "31/01/08"
A09A = "01/01/09"
A09B = "31/01/09"
A10A = "01/01/10"
A10B = "31/01/10"
A11A = "01/01/11"
A11B = "31/01/11"
A12A = "01/01/12"
A12B = "31/01/12"
A13A = "01/01/13"
A13B = "31/01/13"
A14A = "01/01/14"
A14B = "31/01/14"
A15A = "01/01/15"
A15B = "31/01/15"
A16A = "01/01/16"
A16B = "31/01/16"
ElseIf etc etc

Sort a Dataset in visualbasic

I don't know what i doing wrong. I have been on several forums trying to figure out how to sort a table in visual basic.
I have treid with and with out a dataview, but noting seams to work.
I have a logg that the user can do new inserts in. It has 3 columns. "Date", "Tool", "Comment".
When my VB application loads the program reads the table from a Access database and i get my sorting just fine by the sql phrase:
"select * from Logg ORDER BY Logg.Datum DESC"
After a user have uppdated the table i whant to sort it again. I have treid the following, but nothing happens. The order is the same whatever i do.
DS is my Dataset and dw my dataview, and "Datum" the column i whant to sort
DS.Tables("hela").DefaultView.Sort = "Datum DESC"
dw = DS.Tables("hela").DefaultView
For i = 0 To antal_poss - 1
LOGG(i, 0) = dw.Table.Rows(i).Item(3)
LOGG(i, 1) = dw.Table.Rows(i).Item(1)
LOGG(i, 2) = dw.Table.Rows(i).Item(4)
Next i
What am i doing wrong?
In your code you use the DataView to retrieve the Table and then the DataRows, but you extract them following the order on the DataTable.
You need to loop following the order of the DataView.
Something like this
Dim i As Integer = 0
For Each row As DataRowView in dw
LOGG(i, 0) = row.Item(3)
LOGG(i, 1) = row.Item(1)
LOGG(i, 2) = row.Item(4)
i += 1
Next i
Of course this assume that your LOGG array contains enough entries to accomodate every row retrieved. It is the same number of the rows in the DataTable

VB.NET How to do changes to rows selected using LINQ?

I have the following code which selects some rows using LINQ depending on some conditions.
Dim cname
Dim Category
Dim cprice
Try
For i = 0 To mainDatatable.Rows.Count - 1
cname = mainDatatable.Rows(i)("cname")
Category = mainDatatable.Rows(i)("ccategory")
cprice = mainDatatable.Rows(i)("cprice")
Dim nameparts() As String = cname.Split(New String() {" "}, StringSplitOptions.None)
Dim query = From products In mainDatatable.AsEnumerable()
Where products.Field(Of Integer)("ccategory") = Category And products.Field(Of Double)("cprice") = cprice And products.Field(Of String)("cname").Contains(nameparts(0)) And products.Field(Of String)("cname").Contains(nameparts(1))
Select products
If query.Count > 1 Then
'then i want to do some changes to those rows
End If
Next
Catch ex As Exception
MsgBox(ex.Message)
End Try
The code is working perfectly but I need to do changes on the selected rows. I'm not sure how to do it, for example i have a column called gprice and I want it to set it to some value for all the selected rows and save changes to mainDatatable ,would aprreciate your help.
To make it clear, suppose the row count in the query is 6 then I want to make all the values for some column in the query = 1 and then update the values of the selected rows in the mainDatatable
------update
If you don't get it forget the above code and here is what I am trying to do
-Ii have a datatable it only have 2 columns product name and product price, now there are products with same name but different colors
-I want to group those products by pharsing the string name and check for other products with identical words in the name, only one word is allowed to differ which is the color,
-Also the price have to be the same between the products in that group and this is what the above LINQ code does and it does it perfectly
-My problem is i have added a third column called groupnumber, I want to add 1 for each product in the 1st group, 2 for each product in group 2nd and so on.