Showing data in textbox - vb.net

I am trying to get data from a database (which I have done and know that works)
However I want to push the data into a variable.
I can not see what is wrong, at the moment there is a mistake around "cmd.select" so if someone could point me in the right direction that would be great!
Dim cn As SqlConnection = New SqlConnection()
Dim cmd As SqlCommand = New SqlCommand()
Dim sqladp As New SqlDataAdapter()
Dim ds As New DataSet()
cmd.Parameters.Clear()
cn.ConnectionString = ConfigurationManager.ConnectionStrings("PemcoConnectionString").ConnectionString
cmd.Connection = cn
GridView2.Visible = True
cmd.Connection = cn
cmd.CommandText = "spUserResultsDetails"
cmd.CommandType = CommandType.StoredProcedure
Session.Item("ID") = (sender.SelectedValue.ToString)
cmd.Parameters.AddWithValue("#ID", Session.Item("ID"))
For Each datarow As Data.DataRowView In cmd.Select(DataSourceSelectArguments.Empty)
sEmailAddress = datarow("UserEmail")
Next
sqladp.SelectCommand = cmd
sqladp.Fill(ds)

There are many things that need improvement, this should work:
Using cn = New SqlConnection(ConfigurationManager.ConnectionStrings("PemcoConnectionString").ConnectionString))
Using da = New SqlDataAdapter("spUserResultsDetails", cn)
da.SelectCommand.CommandType=CommandType.StoredProcedure
da.SelectCommand.Parameters.AddWithValue("#ID", CInt(Session.Item("ID")))
Dim table = New Data.DataTable()
da.Fill(table)
GridView2.DataSource = table
GridView2.DataBind()
End Using
End Using
A summary:
use the using statement always to ensure that disposable objects are getting disposed (closed) even on error
use a SqldataAdapter if you want to fill a DataTable, you don't need to open/close it with fill, use it's SelectCommand property to get a reference to the SqlCommand
set the table as DataSource of your GridView and DataBind it
if you use AddWithValue you should cast the passed objects to the correct type, otherwise the correct type cannot be inferred

Related

What would cause my dataset to drop a row?

I have a SQL statement that, when ran in SSMS, returns 6 rows. After attaching the statement to the command text of a VB.NET SQLCommand with a command type of Text, reading it with a SqlDataReader, and attaching it to a dataset, the returned dataset only has 5 rows.
At first, I assumed it was an issue with the data. However, after several bouts of removing and adding rows to the source table with varying data, it was obvious that I was always getting the total row count - 1. I then decided to just use a SQLDataAdapter to populate the DataSet and the proper number of rows was returned.
Dim ds As New DataSet
Dim sqlCmd as New SqlCommand
Dim sqlCn As New SqlConnection
Dim sqlR As New SqlCommand
sqlCn.ConnectionString = "SomeConnectionString"
With sqlCmd.CommandText = "Select * from DummyTable"
.CommandType = CommandType.Text
.Connection = sqlCn
End With
sqlCn.Open()
sqlR = sqlCmd.ExecuteReader
sqlR.Read()
If sqlR.HasRows() Then
ds.Tables.Add("DummyTable")
ds.Tables(0).Load(sqlR)
return ds
End If
From here, I'm expecting to see the 6 rows from DummyTable. Instead, I'm seeing only 5.
However, if I use the following:
Dim da as SqlDataAdapter
Using sqlCn
da.SelectCommand = New SqlCommand(sqlCmd.CommandText, sqlCn)
da.Fill(ds)
End Using
Return ds
I get the full 6 rows. Is there something I'm missing about the way a DataSet's Tables.Add(tableName) or Tables(n).Load(dataReader) works? I had never worked with SqlDataReaders prior to this and was told to stick with them as our other projects use them.
Your code is already reading the first line of the query with the line sqlR.Read(). This line is unnecessary in your code. Remove it and it will work fine.
Also SqlCommand, SqlConnection and SqlDataReader implement iDisposable, so be sure to use using-statement with them:
Using sqlCn As New SqlConnection("SomeConnectionString")
sqlCn.Open()
Using sqlCmd as New SqlCommand
With sqlCmd.CommandText = "Select * from DummyTable"
.CommandType = CommandType.Text
.Connection = sqlCn
End With
Using sqlR As SqlDataReader = sqlCmd.ExecuteReader
If sqlR.HasRows() Then
Dim ds As New DataSet
ds.Tables.Add("DummyTable")
ds.Tables(0).Load(sqlR)
return ds
End If
End Using
End Using
End Using

Is filling a DataTable necessary for just setting variables with 2 column values?

I am trying to improve performance of an application, I have a case where a common SPROC is being used but is it necessary to fill a DataTable just to set 2 variable values?
Is there anything more efficient?
Dim Conn As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("DB").ConnectionString)
Dim CmdUsers As SqlCommand = New SqlCommand("uspGetUsers", Conn)
CmdUsers.CommandType = CommandType.StoredProcedure
CmdUsers.Parameters.Add(New SqlParameter("#UserName", Session("UserID")))
Dim da As SqlDataAdapter = New SqlDataAdapter
Dim dtUserInfo As DataTable = New DataTable
da = New SqlDataAdapter(CmdUsers)
da.Fill(dtUserInfo)
isParent = dtUserInfo.Rows(0)("IsAdmin")
UserVal = dtUserInfo.Rows(0)("UserVal")
A SqlDataReader is the fastest way to read data from a query. Try the following:
Using conn As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("DB").ConnectionString)
conn.Open()
Using cmd As New SqlCommand("uspGetUsers", conn)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("#UserName", Session("UserID"))
Using reader As SqlDataReader = cmd.ExecuteReader()
While reader.Read()
isParent = reader("IsAdmin")
UserVal = reader("UserVal")
End While
End Using
End Using
End Using
You may need to parse the data to the correct types.
Also, note the use of Using to automatically dispose of the connection, command and reader objects: http://msdn.microsoft.com/en-GB/library/htd05whh.aspx

ComboBox not filling with code

I have the following code:
Using conn = New SqlConnection(connStr)
Dim sql = "SELECT [CATEGORIA], [AREA] FROM [CATEGORIAS] WHERE ([AREA] = #AREA)"
Dim sqlCmd = New SqlCommand(sql, conn)
sqlCmd.Parameters.AddWithValue("#AREA", CStr(PublicLogin.Area))
conn.Open()
Dim ds As New DataSet
Dim da As New SqlDataAdapter(sql, conn)
da.Fill(ds, "CATEGORIAS")
With cboCat
.DataSource = ds.Tables("CATEGORIAS")
.DisplayMember = "CATEGORIAS_AREA"
.ValueMember = "CATEGORIAS_AREA"
.SelectedIndex = 0
End With
End Using
It should in theory fill the combo box right? It doesn't. It doesn't give me any errors or anything; the combo box just sits there empty. I am pretty sure the query is working well and its grabbing the correct info but the Combobox doesn't fill. If I take the where query out it fills the CB with 'System.Data.Row...'
UPDATE: Working code in case someone needs it;
Using conn = New SqlConnection(connStr)
Dim sql = "SELECT [CATEGORIA], [AREA] FROM [CATEGORIAS] WHERE ([AREA] = #AREA)"
Dim sqlCmd = New SqlCommand(sql, conn)
sqlCmd.Parameters.AddWithValue("#AREA", CStr(PublicLogin.Area))
conn.Open()
Dim ds As New DataSet
Dim da As New SqlDataAdapter(sqlCmd)
da.Fill(ds, "CATEGORIAS")
With cboCat
.DataSource = ds.Tables("CATEGORIAS")
.DisplayMember = "CATEGORIA"
.ValueMember = "CATEGORIA"
.SelectedIndex = 0
End With
End Using
Its empty because probably the query returns nothing. Notice that you are not adding the parameter to the final query on the sql variable.
You create a command with the query and the parameter but you never use it, so when you select all the values WHERE ([AREA] = #AREA) it returns nothing.
Try this:
Dim da As New SqlDataAdapter(sqlCmd)
This looks odd to me:
.DisplayMember = "CATEGORIAS_AREA"
.ValueMember = "CATEGORIAS_AREA"
It should probably be something like this:
.DisplayMember = "CATEGORIA"
.ValueMember = "AREA"
From MSDN on DisplayMember:
Gets or sets a string that specifies the property or column from which to retrieve strings for display in the combo boxes.
EDIT: You also need to replace this:
Dim da As New SqlDataAdapter(sql, conn)
with this:
Dim da As New SqlDataAdapter(sqlCmd)
Otherwise your parameters are never used.

Saving record with dataset

I want to save a record in the database using a dataset, but my data is not committing into my database.
My code can be viewed below:
Dim mydataset1 As New MyDataSet
Dim row As DataRow = mydataset1.Tables("testtable").NewRow()
With row
.Item("name") = "Segun Omotayo"
.Item("address") = "Abuja"
End With
mydataset1.Tables("testtable").Rows.Add(row)
Any help will be appreciated
A DataSet/DataTable is a offline/in-memory representation of your database. If you want to update the database, you need to use a DataAdapter.
For example (assuming you're using MS-Sql-Server):
Public Function UpdateDataSet(dataSet As DataSet) As Int32
Using con = New SqlConnection(My.Settings.SqlConnection)
Dim sql = "INSERT INTO TUser(Name,Address)VALUES(#Name,#Address)"
Using cmd = New SqlCommand(sql, con)
cmd.Parameters.Add(New SqlParameter("#Name", SqlDbType.VarChar))
cmd.Parameters.Add(New SqlParameter("#Address", SqlDbType.VarChar))
Using da = New SqlDataAdapter()
da.InsertCommand = cmd
con.Open()
Dim rowCount = da.Update(dataSet)
Return rowCount
End Using
End Using
End Using
End Function
I could be rusty here since its a long time since I wrote any VB.NET or used data adapters/datasets/datatables but I think if you decide to take that route you would need code like this:
Dim connection As New SqlConnection("#####YourConnectionString#####")
connection.Open()
Dim adapter As New SqlDataAdapter("SELECT * FROM testtable", connection)
' For the line below to work, you must have a primary key field in "testtable"
Dim builder As New SqlCommandBuilder(adapter)
Dim testtable As New DataTable("testtable")
adapter.Fill(testtable)
Dim row As DataRow = testtable.NewRow()
With row
.Item("name") = "Segun Omotayo"
.Item("address") = "Abuja"
End With
testtable.Rows.Add(row)
adapter.Update(testtable)
connection.Close()

Retrieving rows from a MS Access Database View using Vb.Net

I've managed to get the following code...
con.ConnectionString = My.Settings.dbConnection
Dim sqlCmd As System.Data.OleDb.OleDbCommand = New System.Data.OleDb.OleDbCommand()
con.Open()
sqlCmd.Connection = con
Dim schemaTable As DataTable
schemaTable = con.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Views, Nothing)
To retrieve a list of Views in my Access database, but now I want to retrieve the results based on a selected View.
Is there a correct method in doing this, or do I take the SQL Statement from the DataTable returned for each row?
Suppose you have Query1 (View) in your Access database (Database1.accdb file). The following code will output each row of the query to the console (for demo purposes):
Dim con As OleDbConnection = New OleDbConnection()
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Database1.accdb;Persist Security Info=False;"
Dim sqlCmd As OleDbCommand = New System.Data.OleDb.OleDbCommand()
sqlCmd.CommandType = CommandType.StoredProcedure
sqlCmd.CommandText = "Query1"
sqlCmd.Connection = con
con.Open()
Dim reader As OleDbDataReader
reader = sqlCmd.ExecuteReader()
If reader.HasRows Then
While reader.Read()
Console.WriteLine(reader("Column1")) 'output specific column
End While
End If
Console.ReadLine()
Hope this helps