I am trying to collect values from a database, and if they are X value sett he background colour to green.
Basically, I have a Rota system, and if the user is working, then change the background colour. The select * will only bring back 1 row ever.
Imports System.Data.SqlClient
Imports System.Data.OleDb
Public Class Form4
Dim Con As SqlConnection
Dim cmd As New OleDbCommand
Dim sqlstring As String
Dim connstring As String
Dim ds As DataSet
Dim da As SqlDataAdapter
Private Sub Form4_Load(sender As Object, e As EventArgs)
connstring = "Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Assignment.mdf;Integrated Security=True;Connect Timeout=30"
Con = New SqlConnection(connstring)
Con.Open()
Dim strSQL As String = "SELECT * from Users"
Dim da As New SqlDataAdapter(strSQL, Con)
Dim ds As New DataSet
da.Fill(ds, "Users")
With cboname
.DataSource = ds.Tables("Users")
.DisplayMember = "Name"
.ValueMember = "Id"
.SelectedIndex = 0
End With
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Con As SqlConnection
Dim cmd As New OleDbCommand
Dim sqlstring As String
Dim connstring As String
Dim ds As DataSet
Dim da As SqlDataAdapter
connstring = "Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Assignment.mdf;Integrated Security=True;Connect Timeout=30"
Con = New SqlConnection(connstring)
Con.Open()
sqlstring = ("SELECT * FROM Rota WHERE UserId ='" & cboname.SelectedIndex & "' and ID ='" & dtp1.Value & "'")
da = New SqlDataAdapter(sqlstring, Con)
ds = New DataSet
da.Fill(ds, "Rota")
End Sub
End Class
After this, I understand I need to get a few IF statements, but I am unsure on how to construct them.
To check a value in a DataSet use first get a DataTable inside of it, then a DataRow, then check one of the field values:
ds.Tables(0).Rows(0)("{field name}");
So to change the color based on some value:
If ds.Tables(0).Rows(0)("{field name}") = "Red" Then
textbox1.BackColor = Color.Red
End If
Some other comments:
A DataSet may be a bit heavy for getting one value (unless you're binding to a control). You can just use ADO.NET objects and use ExecuteScalar)
It's safer to use parameters instead of concatenating SQL statements (prevents SQL Injection and errors from special characters)
You can refactor your code to put the connection string in a single location rather than duplicating it across methods.
Related
I was hoping someone could explain this a bit better for me.
I have a visual studio project and created the database in the project: Project >> Add Item >> Service Database. I have a form with a textbox that I am trying to insert data into and I have looked up how to do this and there are things like SQLCommand or ExecuteNonQuery are not an option I have.
Since the database is associated with the project I don't know if I even need to do that part but I haven't seen anything to the contrary. I don't want to hard code in a server connection if I can avoid it because I am hoping this will become an application.
This is my code so far
Private Sub btnAddNewSpellSchool_Click(sender As Object, e As EventArgs) Handles btnAddNewSpellSchool.Click
Dim sqlCMD As String
Dim text As String
text = Me.txtAddSpellSchool.Text
sqlCMD = "INSERT INTO tblList_Spell_Config_SpellSchool (spellSchool) VALUES('" & text & "')"
End Sub
This is what I have been seeing
Dim DA As SqlDataAdapter = New SqlDataAdapter
Dim Parm As New SqlParameter
DA.InsertCommand = New SqlCommand("Insert Into tbl1(fld0, fld1, fld2) Values(#fld0, #fld1, #fld2)", conn)
Parm = DA.InsertCommand.Parameters.Add(New SqlParameter ("#fld0", NVarChar, 50, "fld0"))
Parm = sqlDA.InsertCommand.Parameters.Add(New SqlParameter ("#fld1", SqlDbType.NVarChar, 50, "fld1"))
Parm = sqlDA.InsertCommand.Parameters.Add(New SqlParameter ("#fld2", SqlDbType.NVarChar, 50, "fld2"))
DA.Update(dataset1, "tbl1")
Imports System.Data
Imports System.Data.SqlClient
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim myconn As SqlConnection
Dim mycmd As SqlCommand
Dim qry As String
qry = "Insert Into tblList_Spell_Config_SpellSchool (spellSchool) Values('Air')"
myconn = New SqlConnection("Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\jpac0\Dropbox\Dungeon and Dragons\DND_Application\DND_ExperienceBuilder\DND_ExperienceBuilder\DND_ExperienceBuilderDB.mdf;Integrated Security=True;Connect Timeout=30")
myconn.Open()
mycmd = New SqlCommand(qry, myconn)
mycmd.ExecuteNonQuery()
myconn.Close()
End Sub
I'm creating a program in which users can see a table from an access database in a DataGridView.
However, when pressing "btnDisplay" the program crashes and highlights this line:
da.Fill(ds, "tblOrders")
The error reads: "No value given for one or more required parameters"
What does this mean and how do I fix it?
Here is the code:
Imports System.Data.OleDb
Public Class frmViewTables
Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & Application.StartupPath & "\SAC1 Database.mdb"
Dim MyConn As OleDbConnection
Dim da As OleDbDataAdapter
Dim ds As DataSet
Dim tables As DataTableCollection
Dim source1 As New BindingSource
Private Sub btnDisplayDataGrid_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisplayDataGrid.Click
MyConn = New OleDbConnection
MyConn.ConnectionString = connString
ds = New DataSet
tables = ds.Tables
da = New OleDbDataAdapter("Select * from [tblOrders] where Username = #username", MyConn)
cm.Parameters.Add(New OleDbParameter("#username", OleDbType.VarChar, 255, frmLogin.SuccessfulLoginUsername))
cm.Parameters("#username").Value = frmLogin.SuccessfulLoginUsername
da.Fill(ds, "tblOrders")
Dim view As New DataView(tables(0))
source1.DataSource = view
dgvDynamic.DataSource = view
End Sub
Things seem a little messed up. I am not sure about the rest of it but this should solve your parameter problem.
Dim source1 As New BindingSource
Dim ds = New DataSet
Dim tables = ds.Tables
Dim cn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & Application.StartupPath & "\SAC1 Database.mdb")
Dim da As OleDbDataAdapter = New OleDbDataAdapter()
Dim cmd As New OleDbCommand("Select * from [tblOrders] where Username = #username", cn)
cmd.Parameters.Add("#username", OleDbType.VarChar, 255).Value = frmLogin.SuccessfulLoginUsername
da.SelectCommand = cmd
da.Fill(ds, "tblOrders")
Dim view As New DataView(tables(0))
source1.DataSource = view
dgvDynamic.DataSource = view
This has got to be close, but it's been a long day and I'm tired now so I can;t really see what the problem is. Basically, I have a table in SQL Server with 2 columns; one has the names of reports and the other has some SQL Scripts that I want to pass into a GridView, based on what a user selects from a ListBox. Here is my code.
Imports System.Data.SqlClient
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Try
Dim sqlConn As New SqlClient.SqlConnection("Data Source=EXCEL-PC\SQLEXPRESS;Initial Catalog=Test;Integrated Security=True")
sqlConn.Open()
Dim cmd As New SqlClient.SqlCommand("Select ReportName From [Table_1] order by ReportName", sqlConn)
Dim dsColumns As New DataSet
Dim daAdapter As New SqlClient.SqlDataAdapter(cmd)
daAdapter.Fill(dsColumns)
If dsColumns.Tables(0).Rows.Count > 0 Then
ListBox1.Items.Clear()
For i As Integer = 0 To dsColumns.Tables(0).Rows.Count - 1
ListBox1.Items.Add(dsColumns.Tables(0).Rows(i)(0).ToString())
Next
End If
Catch ex As Exception
End Try
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim connetionString As String
Dim SqlStr As String
Dim connection As SqlConnection
Dim adapter As SqlDataAdapter
Dim ds As New DataSet
Dim myItem As String
connetionString = "Data Source=EXCEL-PC\SQLEXPRESS;Initial Catalog=Test;Integrated Security=True"
connection = New SqlConnection(connetionString)
'Dim iIndex As Integer = ListBox1.SelectedIndex
myItem = ListBox1.SelectedItem
SqlStr = "select SqlScript from [Table_1] Where ReportName = '" & myItem & "'"
Try
connection.Open()
adapter = New SqlDataAdapter(SqlStr, connection)
adapter.Fill(ds)
connection.Close()
DataGridView1.DataSource = ds.Tables(0)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class
I guess the problem is passing the SQL to the GridView. When I select the first Item, I see this in my GridView.
SELECT [OrderID]
,[CustomerID]
,[EmployeeID]
,[OrderDate]
,[RequiredDate]
,[ShippedDate]
,[ShipVia]
,[Freight]
,[ShipName]
,[ShipAddress]
,[ShipCity]
,[ShipRegion]
,[ShipPostalCode]
,[ShipCountry]
FROM [Test].[dbo].[Orders]
That's pretty close, but I want to get that SQL fed into the GridView, and get the results of the SQL displayed in the GridView, not eh SQL statement itself.
This is what I see now.
I want to see something more like this.
Finally, I am curious to know of the GridView can be made dynamic, so if I stretch out the window the GridView shows more columns. Now, if I stretch out the form window, the GridView stays static.
You need to actually run the retrieved Sql statement:
sqlstr = "select SqlScript from [Table_1] Where ReportName = '" & myItem & "'"
Try
connection.Open()
Dim cmd As New SqlCommand(sqlstr, connection)
Dim sqlstr_report As String = CStr(cmd.ExecuteScalar())
cmd.Dispose()
adapter = New SqlDataAdapter(sqlstr_report, connection)
adapter.Fill(ds)
connection.Close()
DataGridView1.DataSource = ds.Tables(0)
Use the .Anchor property of the DataGridView to make it resize with the form
Private Sub btnAddSub_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddSub.Click
Dim comboboxvalue As String
comboboxvalue = "'" & CBClass.SelectedItem & "'"
Dim sql As String
sql = "Select * From class Where ClassCode=" & comboboxvalue
Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=H:\ProjectDatabase.mdb"
Dim MyConn As OleDbConnection
Dim da As OleDbDataAdapter
Dim ds As DataSet
Dim tables As DataTableCollection
Dim source1 As New BindingSource
MyConn = New OleDbConnection
MyConn.ConnectionString = connString
ds = New DataSet
tables = ds.Tables
da = New OleDbDataAdapter(sql, MyConn)
da.Fill(ds, "Class")
Dim view As New DataView(tables(0))
source1.DataSource = view
Form1.dgv.DataSource = view
End Sub
I can currently add one piece of data to the datagrid. When I try to add a second piece of data it replaces the current data stored.
How do I make it so that when I add more data it goes to a new line.
The source code you provided looks a lot like you are just refreshing the data source for the DGV on every btnAddSub click, by assigning to form1.dgv.datasource each time. If you want to simply append new rows to the DGV you will need to manipulate the DGV.Rows collection by adding DataGridViewRow objects to it.
I am having a problem trying to get the contents of a list box into and SQL string via a variable(moon)
Here are 3 SELECT strings from the main body of code below.The last two strings work fine
but the first one doesn't.That's the one where I try and place the variable into the code
I have tried a few variations on the code but nothing seems to work.Does anybody have any suggestions.
THE SQL STRINGS:
da = New OleDbDataAdapter("SELECT * FROM books WHERE [author] = '" & moon "' ", myConnection) 'fails
da = New OleDbDataAdapter("SELECT * FROM books", myConnection) 'works
da = New OleDbDataAdapter("SELECT * FROM books WHERE author = 'molly brown' ", myConnection) 'works{
MAIN CODE BODY
Imports System.Data
Imports System.Data.OleDb
Imports System.Data.Odbc
Imports System.Data.DataTable
Public Class Form1
Dim provider As String
Dim dataFile As String
Dim connString As String
Dim myConnection As OleDbConnection = New OleDbConnection
Dim ds As DataSet = New DataSet
Dim da As OleDbDataAdapter
Dim tables As DataTableCollection = ds.Tables
Dim source1 As New BindingSource()
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim moon As String
moon = ListBox1.Text
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
dataFile = "C:\Documents and Settings\james\Desktop\Authors.accdb" ' change to access database location on your computer
connString = provider & dataFile
myConnection.ConnectionString = connString
da = New OleDbDataAdapter("SELECT * FROM books WHERE [author] = '" & moon & "' ", myConnection) 'fails
'da = New OleDbDataAdapter("SELECT * FROM books", myConnection) 'works
'da = New OleDbDataAdapter("SELECT * FROM books WHERE author = 'molly brown' ", myConnection) 'works
da.Fill(ds, "books")
' replace "items" with the name of the table
' replace [Item Code], [Description], [Price] with the columns headers
Dim view1 As New DataView(tables(0))
source1.DataSource = view1
DataGridView1.DataSource = view1
DataGridView1.Refresh()
End Sub
End Class
Best practice is to use a new connection object for each call to the database, define objects with the smallest scope possible, and to use parameterized queries instead of substituting the value into your sql string.
Under no circumstances should you ever use string manipulation to put a user-selected value into your sql statement! Code like this is very bad:
da = New OleDbDataAdapter("SELECT * FROM books WHERE [author] = '" & moon & "' ", myConnection)
Imagine what would happen in this example if you have an author like "Patrick O'Neil". There are many ways this problem can be further abused to cause real damage to your database, application, and users. Just don't use string concatenation for this.
Do it like this instead:
Public Class Form1
Private Const provider As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
Private Const dataFile As String = "C:\Documents and Settings\james\Desktop\Authors.accdb" ' change to access database location on your computer
Private connString As String = provider & dataFile
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim ds As New DataSet()
'Set a special placeholder for your value as part of a *constant* sql statement
Dim sql As String = "SELECT * FROM books WHERE [author] = ? "
Using cn As New OleDbConnection(connString), _
cmd As New OleDbCommand(sql, cn), _
da As New OleDbDataAdapter(cmd)
'Set the value for that placeholder via a query parameter
'Parameters work best when you set the actual type and length
' to match your database. I had to guess at the length here.
cmd.Parameters.Add("?", OleDbType.NVarChar, 50).Value = Listbox1.Text
da.Fill(ds, "books")
End Using
DataGridView1.DataSource = ds.Tables("books")
DataGridView1.Refresh()
End Sub
End Class