Connect an SQL database to a DataGridView with separate command buttons? - sql

I'm a bit puzzled here. I did a form containing a simple datagridview containing data from an MDB file. The connection was alltogether done by Visual Studios wizard so alot of stuff was created automatically. Then I databinded the textboxes to each column in the database and managed to update the database via my own command buttons such as "Update" with this code:
Me.MainTableBindingSource.EndEdit()
Me.MainTableTableAdapter.Update(Me.DBDataSet.MainTable)
Me.DBDataSet.MainTable.AcceptChanges()
This doesn't seem to work with sql. At this point, I've done everything from scratch in this order, added a datagridview and added a database connection with the wizard when connecting the datagridview to a database. Only this time around I created an SQL connection instead.
And Visual Studio created "MainTableTableAdapter", "DBDataSet", "DBDataSet.MainTable".
The SQL server is something which was installed automatically when installing Visual Studio and it does seem to work after creating the table adapter and dataset if there's data in it. In some time I plan to use an SQL Server on the internet which hosts the dataset. So I want to be able to easily edit the source.
The only thing missing now is how to add a row, delete selected row and editing selected row via my own textboxes. More like a fill-in form. Any ideas to put me in the right direction? I've tried googling it and I've found some stuff, but most of it contains stuff on how to create the datasets and etc. And I'm not sure what Visual Studio has done automatically. And I want to update everything just as easily as I did with these three lines of code when I used a local MDB file.

If it's SQL you can do something like this. Here's an example delete function:
Public Shared Function DeleteStuff(ByVal id As Integer) As Integer
Dim query As String = _
"DELETE FROM tbl_Stuff " & _
"WHERE ID_Stuff = " & id & ";"
Dim connection As SqlConnection = YourDB.GetConnection
Dim deleteCommand As New SqlCommand(query, connection)
Dim rowCount As Integer = 0
Try
connection.Open()
rowCount = deleteCommand.ExecuteNonQuery()
Catch ex As SqlException
Throw ex
Finally
connection.Close()
End Try
Return rowCount
End Function
There may be better ways, but you can always pass in SQL queries.
EDIT: Sorry this is more than three lines of code. ;)

Related

SQL Column Does Not Exist Error

Okay, so basically I asked this little earlier today but we didn't get to the root of the problem and a lot of speculation was clouding the solutions. I have a program that currently needs to check a users inputed 'Gamer-Tag' from RegUserName.Text and compare that with Gamer-Tags stored on the SQL Table PersonsA which is in the Members_Details Database.
When the code is ran I receive the below error;
An unhandled exception of type 'System.ArgumentException' occurred in
System.Data.dll
Additional information: Column 'Gamer_Tag' does not belong to table
PersonsA.
However, Gamer-Tag IS in the Table; It's the second Column in the table. The Server is MS SQL Server and when I use the 'SQL Server Management Studio' I can clearly see the table & columns. From there all SQL Codes in relation to the Gamer_Tag column work flawlessly, so it's definitely in the database.
Here's the code which is called when a button is pressed. This code 'calls' the Function with the error.
Dim dbManager As New DatabaseManager() 'My Class Where The Functions Are
If dbManager.CheckGamerTagisMember(RegUserName.Text) Then
MsgBox("Gamer-Tag is NOT A Member.")
GoTo Ender
Else
MsgBox("Gamer-Tag is A Member.")
GoTo Ender
End If
And here's the Function which contains the Error;
Public Function CheckGamerTagisMember(ByVal gamertag As String) As Boolean
Connection = New SqlConnection("Data Source =" & My.Settings.ServerIP & ";Initial Catalog=Members_Details;Integrated Security=False;User=" & My.Settings.UserName & ";Password=*******;")
Connection.Open()
Dim gamertagDatSet As New DataSet()
usersDataAdapter.FillSchema(gamertagDatSet, SchemaType.Source, "PersonsA")
usersDataAdapter.Fill(gamertagDatSet, "PersonsA")
Dim table As DataTable = gamertagDatSet.Tables("PersonsA")
For i As Integer = 0 To table.Rows.Count - 1
Dim storedgamertag As String = table.Rows(i)("Gamer_Tag").ToString.ToString '<-------- ERROR
If (storedgamertag = gamertag) Then
gamertagDatSet.Dispose()
Connection.Close()
Return True
End If
Next
gamertagDatSet.Dispose()
Connection.Close()
Return False
End Function
What could cause this problem? I've checked obvious spelling and spacing, the firewall's off and the Column is without a doubt there. The function code was adapted from my SQL Login function, which worked without any issues, so I'm puzzled on why this isn't working.
Here's a screenshot from MS SQL Server Management Studio showing the PersonsA Table columns.
It's really getting frustrating now.
Some possible reasons:
Your user has actually been denied access to see the column. This can be accomplished via something as simple as:
DENY SELECT ON dbo.PersonsA(Gamer_Tag) TO your_user;
There is more than one PersonsA table, and the one you are accessing in your code is actually in a different schema than dbo. This is why you should always, always, always specify the schema when creating or referencing objects. Always. Read this post for more info.
Your code is connecting to a different server, a different database, or a different copy of the same database than Management Studio. (The latter can happen when using SQL Express and the User Instance/AttachDbFileName settings, which I can see that your code is not using, but I don't know if you are connecting to a user instance from Management Studio.)

Multiple Database connections within 1 application - VB .NET

This may have been answered but my search hasn't found what I was looking for.
Basically, I am developing an application which allows the user to build a query at design time, i.e. for users with no prerequisite knowledge of SQL
The application thus far allows the user to select which table(s) from the database they wish to start querying (I won't go into the details of the rest for now)
My confusion is this; I already have the connection to the database in a subroutine which obtains the schema information and filters it to display only the available tables within the database, which then compiles the data into a listbox, here is that sub:
Public Sub getSchemaInfo()
Dim ds As New DataSet
Dim dt As New DataTable
Dim con As New OleDbConnection
Dim strDatabaseLocation As String = Application.StartupPath
Dim da As New OleDbDataAdapter
Dim i As Integer
'ds.Tables.Add(dt)
con.ConnectionString = "Provider=microsoft.jet.oledb.4.0; data source = " & strDatabaseLocation & _
"\EmployeeDepartment.mdb"
'clear listbox of any data first
frmAddTable.lbTables.Items.Clear()
'Try catch block used to handle connection errors gracefully
Try
con.Open()
'Accessing methods to obtain schema information
dt = con.GetOleDbSchemaTable(OleDb.OleDbSchemaGuid.Tables, New Object() _
{Nothing, Nothing, Nothing, "TABLE"})
'loop datatable to store schema information within it
For i = 0 To dt.Rows.Count - 1
'compile lbtables with a list of available tables from the database
frmAddTable.lbTables.Items.Add(dt.Rows(i)!TABLE_NAME.ToString())
Next
Catch ex As Exception
MessageBox.Show(ex.Message.ToString(), "Data Load Error", MessageBoxButtons.OK,
MessageBoxIcon.Exclamation)
End Try
con.Close()
As you can see, at the very top is all the information regarding the connection to the database and loading of the information into the dataset.
My question is this; Whenever I need to gain access to the database and any information within it, will I have to perform all the connection process (oledbconnection, etc..)
or is there I way I can create a class for the connection functions and simply reference them whenever I need to connect?
For example, I now am in the process of creating another sub which gathers the columns, based on the tables chosen in the listbox, and displays it back onto the main form in the relevant checklistbox, again, connecting to the database, therefore would I need to perform all of the connection processes?
Any information would be very useful, thank you!
It is a standard approach to separate your DAL ( Data Access Logic ) from your Business Logic. I would definitely create a separate class for connecting to the database and executing the queries that would bring back the results that you can then either Bind to a control or iterate over inside a loop.
You might even want to look into using EF ( Entity Framework ) or my favorite LINQ to SQL to help in following a standard Design Pattern. By using a framework like EF or L2S you can leverage their ability to cache objects and return back strongly typed objects versus loosely typed. Strongly typed objects give you intelisense and are less prone to common mistakes like misspelling a field from a DataTable.

how to query/get data from Datasource in VB.NET

i am building a database application in vb.net and i started by adding a data source from the DATA in the toolbar. my connection is good and it shows all my tables in the data source panel.
i also see new classes related to my database, like
sakilaDataSet
sakilaDataSet.customerDataTable
...
and so on.
how do i query and use these ? i googled a lot and i am not able to get this.
Dim cust As sakilaDataSet.customerDataTable = New sakilaDataSet.customerDataTable
Dim row() As System.Data.DataRow = cust.Select("customer_id=5")
MsgBox(row.Count)
My last try was with the above code, but the row.count always turns out to be zero.
You need to open a connextion to the DB. Here are some options:
You could use EntityFramework, which provides a nice way to access data and control it by mapping to entities (classes). For this, in VisualStudio create a ClassLibrary project, add an item ADO.NET Entity Data Model. This will open a wizard that will help you connect to the DB, map the objects in the DB to entities and access the entities by a reference to an entity context. The basics are easy.
Other option is to use an OLEDB provider, which is a classic way to access DB. An example to open an Access DB of employees:
Dim connString As String = "provider= microsoft.jet.oledb.4.0; " & _
"data source=Employee.mdb;"
Dim conn As New OleDbConnection(connString)
Try
conn.Open()
Finally
conn.Close()
Console.WriteLine("Connection Closed")
End Try
Visit http://www.connectionstrings.com/ to get a list of common connection string for many DB. Other useful links:
EntityFramework:
http://www.codeguru.com/csharp/csharp/net30/article.php/c15489
http://www.asp.net/entity-framework/tutorials
OLEDB:
http://oreilly.com/catalog/progvbdotnet/chapter/ch08.html
http://www.homeandlearn.co.uk/net/nets12p2ed.html
http://www.sourcecodester.com/tutorials/net/database-programming-made-easy.html
Hope this helps.
What i wanted to achieve was not to use connection strings again. After adding the data source in VB.net, it makes Data Classes and Adapters, which i can use directly to access the database, as follows :
Dim staff As sakilaDataSet.customerDataTable = New sakilaDataSetTableAdapters.customerTableAdapter().GetData
Dim rows() As sakilaDataSet.customerRow = staff.Select("email='" + email.Text + "'")
This website http://visualbasic.about.com/od/usingvbnet/a/begdbapp7.htm had a good tutorial where it talked about what happens when you use the data sources window and how to use it in your code after that.
I know it's an old question, but it was very high in Google results, and it was more of a "This is how you should have done it" answer instead of actually answering with what it seems like you asked

Using TableAdapter to insert rows into a dataset does not do anything

I have a question similar to this one, but reading the (accepted) answer didn't give me much insight, so I'm hoping to state it more clearly and get a clearer response back.
I'm attempting to insert a data row into a table. I'm using TableAdapter's custom "insert nonQuery" that I wrote (it works, I tested) to accept some parameters. I'm fairly new to this business of communication with a database via .NET and what I'm doing is probably wrong by design. My questions are why is it wrong and what's the right way to do it? Both are equally important, IMO.
Here's some sample VB code I wrote:
Dim arraysTableAdapter As New UnitTestsDataSetTableAdapters.ArraysTableAdapter
Try
arraysTableAdapter.InsertArray("Test Array", 2, 1, 2, "Test user")
Catch ex As SqlException
MsgBox("Error occured when trying to add new array." _
& vbNewLine & vbNewLine _
& ex.Message)
End Try
...and that's pretty much it. There is no exception raised, my table does not get a new row inserted. Everything is just the way it was before I called the InsertArray method. When I test my query in the QueryBuilder with the same parameters, a new row gets added to the database.
Now, I do understand some of the reasons this would not work. I understand that I need to create and select a row in my DataSet (no idea how to do it) in order to tell the TableAdapter what it's adding the data to. Or at least I got that impression from reading the vast abyss of forums.
I would really like to use TableAdapter at some point, because it knows that .InsertArray exists and it knows which parameters it likes. I could try and do it using
Dim con As New SqlConnection
Dim cmd As New SqlCommand
con.ConnectionString = connString
con.Open()
cmd.CommandText = "INSERT ...... all that jazz"
but it's not nearly clean enough for how clean I like my code to be. So, is there any way to do what I'm trying to do the way I'm doing it? In other words, how do I use the neat structure of a TableAdapter to communicate to my DataSet and put a new row in it?
Thanks in advance!
There were two things that were wrong:
(minor issue) I did not have a DataTable filled from the TableAdapter (see code below)
(major, sneaky issue) My method worked from the very beginning. There is nothing extra to be added except for the line above. However, the ConnectionString of arraysTableAdapter was pointing my program (automatically, by default) to a wrong location. Once I manually set the ConnectionString, it worked perfectly.
Here's my complete code:
Dim connString As String = "Some correct connection string"
Dim arraysDataTable As New SpeakerTestsDataSet.ArraysDataTable
Dim arraysTableAdapter As New UnitTestsDataSetTableAdapters.ArraysTableAdapter
'Set the correct connection string'
arraysTableAdapter.Connection.ConnectionString = conn
'Fill table from the adapter'
arraysTableAdapter.Fill(arraysDataTable)
Try
arraysTableAdapter.Insert("Test", 2, 1, 2, Now, Now, "Me")
Catch ex As Exception
MsgBox("Error occured when trying to add new array." _
& vbNewLine & vbNewLine _
& ex.Message)
End Try
The accepted answer in the question you linked to is correct, but sometimes saying it in different words helps:
A TableAdapter is used to communicate between a DataTable (there can be one or more DataTables in a DataSet) and a database. It can pull data from a database and add it to a DataTable and it can send data from a DataTable to the database. It's purpose is to create and execute the SQL code required to make this communication work.
You are trying to use the TableAdapter to directly add data to your DataTable. This will not work. Instead, you should use the methods that come with the DataTable to add a new row to the DataTable and then (if necessary) use your TableAdapter to send that row to a database.
For instance, with a Dataset called DataSet1 that contains a DataTable called DataTable1 that has three text columns you can add a record like this:
Dim d As New DataSet1
d.DataTable1.AddDataTable1Row("value1", "value2", "value3")
That AddDataTable1Row method is automatically created for you, and I think is what you are looking for.

Access remote sql server using VB.NET

I've found a few examples of using vb.net to access an sql database, so far none of them have worked . They all involve using DataReaders. Maybe its the fact that the sql db is not on the same machine as the application.
I was just wondering if anyone had a more comprehensive example of using VB.NET to access a remote sql server.
Thanks!
EDIT:
I've received a few helpful comments an replies already. So far my connection string looks like:
"server=sqlblah.myhost.com;uid=myuser;pwd=pass;database=testdb"
Probably also good to mention their is no editing of the tables a this point, just reading.
Check out the SQLClient class.
One convienent way to access a SQL database is to fill a DataSet object with query data with a DataAdapter object.
Dim sSQL As String = "SELECT * FROM ???"
Dim conn As New SqlClient.SqlConnection("connection string")
Dim da As New SqlClient.DataAdapter(sSQL, conn)
Dim ds As New DataSet
da.Fill(ds, "TABLE NAME")
You can then access the "TABLE NAME" table in the DataSet object.
The "connection string" is obviously your SQL connection string.
Use the sSQL string to query as necessary.
Quick side note - a helpful tool for creating connection strings:-
Open up a text document (notepad, wordpad etc) and save a blank document with the extension ".UDL".
This will give you a "Data link Properties" mini app.
Open up the app and change the provider in the "Provider" to whichever provider you need (in this case OLE DB Provider for SQL Server).
You then need to build up the connection in the connection tab.
Once you have chosen the criteria (ServerName (the drop down list will show you all visible Servers), Security permissions,Database (this drop down list will be populated based on the server chosen)) you can test your connection (to make sure you have permissions etc).
Click ok to close the App, rename the file to have a ".txt" extension and re-open in a text editor, hey presto, one built up connection string (as below).
Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=YOURDBNAME;Data Source=YOURSERVERNAME