I've seen a couple example of how to do this by placing all the code in the aspx file, but I'm trying to do it from the code-behind. Here's what I have in the code behind:
Dim dt As New DataTable
Using conn As New OleDbConnection(ConnectionString)
conn.Open()
Dim dtAdapter As New OleDbDataAdapter
Dim command As New OleDbCommand("SELECT * FROM table " & _
"" _
, conn)
dtAdapter.SelectCommand = command
dtAdapter.Fill(dt)
conn.Close()
End Using
GridView1.DataSource = dt
GridView1.DataBind()
I'm open to any solutions, but I would prefer to do it in the code-behind if possible since thats how the rest of app is. I dont need to necessarily use a gridview just display some tabular data, so whatever works is fine. Im trying to avoid manually constructing sql strings. Any thoughts?
I don't see the question. If you don't kno how to filter the records in your query, use the Where clause with a parameter:
Dim dt = New DataTable()
Using conn As New OleDbConnection(ConnectionString)
Dim queryString As String = "SELECT * FROM Table WHERE Field1 LIKE ?"
Dim command As OleDbCommand = New OleDbCommand(queryString, conn)
command.Parameters.Add("#p1", OleDbType.Char, 3).Value = "a%"
Using da = New OleDbDataAdapter(command)
' you don't need to open/close a connection if you use DataAdapter.Fill
da.Fill(dt)
End Using
End Using
GridView1.DataSource = dt
GridView1.DataBind()
DataAdapter Parameters
Using Statement
Related
I will try to keep this as brief as possible.
I have a function called GetData(ByVal query As String) whose sole purpose is to populate a data table multiple times based on certain conditions. As you can see, the function accepts a string variable where the SQL statement resides. What I am trying to do is add a scalar variable, "#date" in my case, and no matter where I try to add this variable it throws an error stating "Must declare scalar variable #date.
Edit: I should mention that it is throwing the "must declare variable" error on the sda.Fill(dt) line.
GetData Function
Private Shared Function GetData(ByVal query As String) As DataTable
Dim constr As String = ConfigurationManager.ConnectionStrings("WarrantyConnectionString").ConnectionString
Using con As SqlConnection = New SqlConnection(constr)
Using cmd As SqlCommand = New SqlCommand(query)
Dim dt As DataTable = New DataTable()
cmd.Parameters.Add("#date", SqlDbType.Date).Value = Date.Today
Using sda As SqlDataAdapter = New SqlDataAdapter(query, con)
cmd.Parameters.AddWithValue("#date", Date.Today)
sda.Fill(dt)
End Using
Return dt
End Using
End Using
End Function
I am calling the function in a procedure that has the query and handles all of the conditions I need.
Procedure
Dim queryStart As String = "SELECT ( SELECT SUM(DealerNet) FROM Agreement WHERE VoidDate IS NULL "
Dim queryAlias As String = "AS Actual, "
Dim queryStart2 As String = "(SELECT SUM(Amount) FROM AccountingUS.dbo.ProjectedSales "
Dim queryAlias2 As String = "AS Projected "
If chart = "pmtd" Then
Dim queryCondition As String = "AND IssueDate BETWEEN (SELECT DATEADD(MONTH, DATEDIFF(MONTH, 0, #date)-1, 0)) AND #date) "
Dim queryCondition2 As String = "WHERE [Month] = MONTH(#date) AND [Year] = YEAR(#date)) "
Dim query As String = queryStart + queryCondition + queryAlias + queryStart2 + queryCondition2 + queryAlias2
Dim xMember1 As String = "Actual"
Dim xMember2 As String = "Projected"
Dim dt As DataTable = GetData(query)
pmtdChart.DataSource = dt
The variable in question is the #date variable in the strings within the "If" statement, the only value it holds is todays date. Currently, I have tried to use "cmd.Parameters.Add("#date", SqlDbType.Date).Value = Date.Today in the GetData function, however, I still receive the same "Must declare scalar variable" error. I have also tried replacing the #date variable with simply "" + Date.Today + "" or a variable that holds todays date, but upon doing so I receive an operand error about "Operand Clash: Date is incompatible with Int"
Any help regarding this issue would be greatly appreciated, I am relatively new to programming and would appreciate any tips or criticisms regarding best practices. If you need any additional information or clarification regarding this issue I would be happy to provide what I can. Thank you in advance.
Ok, a few things:
I would actually pass a command object to that get data routine.
And your issue is you feeding the query to the "adaptor", but NOT supplying the #date parameter to that "sda"
this:
Using sda As SqlDataAdapter = New SqlDataAdapter(query, con)
cmd.Parameters.AddWithValue("#date", Date.Today)
sda.Fill(dt)
End Using
In other words, you NOT EVEN using the cmd object!!!
So, you would need to add the parameter's to the sda object!!
eg this:
Public Function GetData(ByVal query As String) As DataTable
Dim dt As DataTable = New DataTable()
Dim constr As String =
ConfigurationManager.ConnectionStrings("WarrantyConnectionString").ConnectionString
Using con As SqlConnection = New SqlConnection(constr)
Using sda As SqlDataAdapter = New SqlDataAdapter(query, con)
sda.SelectCommand.Parameters.Add("#date", SqlDbType.Date).Value = Date.Today()
sda.Fill(dt)
End Using
End Using
Return dt
End Function
So, yes, you WILL get that error about "#date" not being declared, since you NOT using the cmd object to fill the table, but are using the data adaptor.
So, as a future suggest?
Pick one way, or the other way.
I MUCH over the years have decided that I will use/have/adopt and cookie cut over and over the SqlCommand object.
I find the Sql cmd object better, since:
it has the parameters.
it has a connection object (if you want to use)
it has a data reader built in
So, what this means?
I suggest this code for get data:
Private Shared Function GetData(ByVal query As String) As DataTable
Dim constr As String =
ConfigurationManager.ConnectionStrings("WarrantyConnectionString").ConnectionString
Dim dt As DataTable = New DataTable()
Using con As SqlConnection = New SqlConnection(constr)
Using cmd As SqlCommand = New SqlCommand(query, con))
con.Open()
cmd.Parameters.Add("#date", SqlDbType.Date).Value = Date.Today
dt.Load(cmd.ExecuteReader)
End Using
End Using
Return dt
End Function
So, we don't need a data adaptor. In fact, you only need a adaptor if you going to update the resulting table (think a "adaptive" table to remember this). You not going to update the data, so really, no need to use a "adaptor" at all here. (and sadly, far too many examples use a "adaptor" anyway. They are for ALLOWING update of the data table, and you not doing that!
So, use a command object. Do note that you ALWAYS must then open the confection, but since we have "using" blocks, it will ALWAYS be closed for you.
And note how then we don't create to "use" the "reader" from the adaptor, nor a fill command. (so, we eliminated one whole confusing object!!).
So, in your example, you created a SQL command object, correctly added the parameter to the command object, but THEN DON'T use it, and then decided to create a data adaptor, and use that!!!
So, you could/can leave your code as you had with the sda "prameter " fix I posted above.
However, but I think your better off to use a sql command object.
Note even better?
Pass the command object to the GetData routine.
I have a global "general" purpose routine called MyRstP(), and I pass it a command object, even for just plain jane sql.
but, if you decide to add parameter's, you can!
Do note that parameter's can be added 100% independent of the SQL string, and they can be added before, or after you set the sql string.
And you can add parameter's WITHOUT a valid working connection (or have created one just yet). So, "parameters" are just a colleciton - it does not care about the SQL (well, at least not yet!!).
So, here is my RstP, and I dumped this into a plain jane "module1" which VB has (this means you don't have to create a static class, and this works then just like VB6, or VBA.
So, this:
Public Function MyRstP(cmdSQL As SqlCommand, ByVal Optional strCon As String = "") As DataTable
If strCon = "" Then
strCon = My.Settings.TEST4
End If
Dim rstData As New DataTable
Using conn As New SqlConnection(strCon)
Using (cmdSQL)
cmdSQL.Connection = conn
conn.Open()
rstData.Load(cmdSQL.ExecuteReader)
End Using
End Using
Return rstData
End Function
So, now to say fill a grid view, I use this:
Dim strSQL As String =
"SELECT id, HotelName, City FROM tblHotelsA"
Dim cmdSQL As New SqlCommand(strSQL)
GridView1.DataSource = MyRstP(cmdSQL)
GridView1.DataBind()
or say a given date of some such:
How about all hotel visit dates from start of year.
So, this:
Dim strSQL As String =
"SELECT id, HotelName, City FROM tblHotelsA
WHERE VisitDate >= #dtStart"
Dim dtStart As DateTime
dtStart = DateSerial(DateTime.Today.Year, 1, 1)
Dim cmdSQL As New SqlCommand(strSQL)
cmdSQL.Parameters.Add("#dtStart", SqlDbType.DateTime).Value = dtStart
GridView1.DataSource = MyRstP(cmdSQL)
GridView1.DataBind()
note then how I have that MyRstP (like your get data), but I can pass it quite much anything I want, including parameter's from the "calling" code, NOT in that general routine.
Anyway, the above use and adding the parameter's to the "adaptor" will fix this, but I would change over to using just a command object and a connection - the adaptor really not required, and as noted, they really are to be used WHEN you actually want to update the data table, and then send it back to the database in one shot.
If you look closely, you setup a cmd command, but you never actually pass it to the DataTable. So it doesn't know anything about your params.
How about this instead (copied untested from Trying to pass SqlCommand in SqlDataAdapter as parameters):
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings("WarrantyConnectionString").ConnectionString))
{
con.Open();
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = query;
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("#date", SqlDbType.Date)
cmd.Parameters.AddWithValue("#date", Date.Today)
using (SqlDataAdapter adp = new SqlDataAdapter(cmd))
{
adp.Fill(dt);
return dt;
}
}
}
Dim dt as new DataTable()
using db as new SqlConnection(ConfigurationManager.ConnectionStrings("WarrantyConnectionString").ConnectionString)
db.Open();
using cmd as New SqlCommand(query, con)
cmd.Parameters.Add("#date", SqlDbType.Date).value = Date.Today
//cmd.Parameters.AddWithValue("#date", Date.Today)
using adp as new SqlDataAdapter(cmd)
adp.Fill(dt)
return dt
End using
End using
End using
I need pass the whole table to a stored procedure to run a update query.
This is my code:
CREATE TYPE [dbo].[UploadData] AS TABLE
(
[CODE] [varchar](4) NULL,
[SERIALNUMBER] [varchar](20) NULL,
[PRODUCTCODE] [varchar](20) NULL,
[THRESHOLD] [int] NULL
)
This is my stored procedure:
CREATE PROCEDURE sp_UpdateExchangeThreshold
#TableType dbo.UploadData READONLY
UPDATE [dbo].[ExchangeData_20221213]
SET t.Threshold = tbl.THRESHOLD
FROM [dbo].[ExchangeData_20221213] t
INNER JOIN #TableType AS tbl ON t.ProductCode = tbl.PRODUCTCODE
AND t.SerialNumber = tbl.SERIALNUMBER
In my VB.Net code, I have this:
Using sqlCommand As SqlCommand = New SqlCommand()
sqlCommand.Connection = connection
sqlCommand.CommandText = "sp_UpdateExchangeThreshold"
sqlCommand.CommandTimeout = 180
sqlCommand.CommandType = CommandType.StoredProcedure
Dim parameterList As SqlParameter = New SqlParameter("#TableType", SqlDbType.Structured)
parameterList.Value = dataTable
parameterList.Direction = ParameterDirection.Input
sqlCommand.Parameters.Add(parameterList)
sqlCommand.ExecuteNonQuery()
End Using
I'm not able to update the records. Any mistake I made? Please help
Unfortunately, a .NET ADO datatable is NOT a SQL Server table type. They have NOHTING to do with each other. You can use a datatable with Oracle, MySQL, or any server based system. You can even use a access database with a data table.
So, datatable object is platform gnostic (neutral), and thus can't be passed, used as a SQL table type.
However, you don't really have to pass a table back. The REAL question is what do you want to do with this table?
Do you want to edit, or update or insert rows from that table back into the database?
If yes, then use a table adaptor (that's what they are for).
Not only will they do all the dirty work for you, but that table can have updates, deletes, edits and insert/additions.
And with ONE command you can send that WHOLE table + all edit/update/delete/adds in one shot.
Say like this:
Dim rstHotels As New DataTable
Using conn As New SqlConnection(My.Settings.TEST4)
Dim strSQL As String = "SELECT * FROM tblHotelsD"
Using cmdSQL As New SqlCommand(strSQL, conn)
conn.Open()
rstData.Load(cmdSQL.ExecuteReader)
' delete first row
rstData.Rows(0).Delete() ' delete first row
rstData.Rows(2).Item("City") = "Zoo" ' edit/modify the 3rd row
Dim OneNewRow As DataRow = rstData.NewRow
OneNewRow("FirstName") = "First Name"
OneNewRow("LastName") = "last Name"
OneNewRow("HotelName") = "My Hotel Name"
OneNewRow("Active") = True
rstData.Rows.Add(OneNewRow)
' now, lets send edits/delete/inserts back to database.
Dim da As New SqlDataAdapter(cmdSQL)
Dim daU As New SqlCommandBuilder(da)
da.Update(rstData)
End Using
End Using
Now, I have the load the table and the update as per above, but they can be done separately.
Edit: Sending the datatable to SQL Server, but not all rows.
' so, lets "send" to the sql database some data
Dim rstData2 As New DataTable
rstData2.Columns.Add("HotelName", GetType(String))
rstData2.Columns.Add("City") ' FYI -- defualt is string
rstData2.Columns.Add("Active", GetType(Boolean))
' lets create 5 test rows of data
For i = 1 To 5
Dim MyNewRow As DataRow = rstData2.NewRow
MyNewRow("HotelName") = "Hotel #" & i
MyNewRow("City") = "City #" & i
MyNewRow("Active") = True ' you MUST include columnes that require deffault value
rstData2.Rows.Add(MyNewRow)
Next
' now send in one shot to database
Using conn As New SqlConnection(My.Settings.TEST4)
Dim strSQL As String = "SELECT ID, HotelName, City, Active FROM tblHotelsD"
Using cmdSQL As New SqlCommand(strSQL, conn)
conn.Open()
Dim da As New SqlDataAdapter(cmdSQL)
Dim daU As New SqlCommandBuilder(da)
da.Update(rstData2)
End Using
End Using
How do you rebind the data in Gridview to show 50 and up instead of 1 and up.
Starts from 1:
Dim connStr, cmdStr As String
Dim myDataSet As New DataSet
Dim dt As New DataTable()
connStr = "connection string works"
cmdStr = "SELECT * FROM table1;"
Try
Using conn As New SqlConnection(connStr)
Using cmd As New SqlCommand(cmdStr, conn)
conn.Open()
cmd.ExecuteNonQuery()
Using myDataAdapter As New SqlDataAdapter(cmd)
myDataAdapter.Fill(myDataSet)
dt = myDataSet.Tables(0)
GridView1.DataSource = dt
GridView1.DataBind()
End Using
conn.Close()
cmd.Dispose()
conn.Dispose()
End Using
End Using
Catch ex As Exception
End Try
What do I need to change to start from 50 and up?
Make your DataTable an enumerable object and then use LINQ's .Skip() function to get past the first 50 items, like this:
Dim filteredSet = dt.AsEnumerable().Skip(50)
Now bind the filteredSet instead of dt to the grid view, like this:
GridView1.DataSource = filteredSet
GridView1.DataBind()
I would say the most efficient choice would be to not select the data from the database by using a parametrized query where you pass in a starting value of some sort and the query only selects data occurring after this point.
Another option, which only takes a small adjustment to your code is to simply delete rows from the DataTable like so:
' remove the first 50 rows
For x As Integer = 1 To 50
dt.Rows.RemoveAt(0)
Next
I'm having a problem populating a child gridview using a function I define. I keep getting the error "Object reference not set to an instance of an object". What am I doing wrong? Am I using the FindControl function incorrectly? It doesn't seem to find the child gridview.
Sub RecordsByZip()
Dim DBConn As New SqlConnection(Application("DBConn"))
Dim gv1 As GridView
gv1 = grdTotal
Dim gv2 As GridView
gv2 = DirectCast(gv1.FindControl("grdChild"), GridView)
Dim ZipCode = lbZip.SelectedItem
For Each ZipCode In lbZip.Items
If ZipCode.Selected = True Then
Dim cmdZip As SqlCommand = New SqlCommand("spPICAInsertTotals2", DBConn)
cmdZip.CommandType = CommandType.StoredProcedure
strZip = ZipCode.Text
strUser = Session("User")
Dim Zip As New SqlParameter("#Zip", SqlDbType.VarChar)
Zip.Value = strZip
cmdZip.Parameters.Add(Zip)
Dim UserID As New SqlParameter("#UserID", SqlDbType.Int)
UserID.Value = strUser
cmdZip.Parameters.Add(UserID)
DBConn.Open()
gv1.DataSource = cmdZip.ExecuteReader
gv1.DataBind()
gv1.Visible = True
DBConn.Close()
End If
Next
btnExport.Visible = True
lblmsg.Visible = False
' Dim DBConn = New SqlConnection(Application("DBConn"))
Dim cmdCounty As SqlCommand = New SqlCommand("spPICAInsertTotals", DBConn)
cmdCounty.CommandType = CommandType.StoredProcedure
'Dim gv As GridView = TryCast(e.Row.FindControl("grdChild"), GridView)
strUser = Session("User")
Dim UserID2 As New SqlParameter("#UserID", SqlDbType.Int)
UserID2.Value = strUser
cmdCounty.Parameters.Add(UserID2)
DBConn.Open()
gv2.DataSource = cmdCounty.ExecuteReader
gv2.DataBind()
gv2.Visible = True
DBConn.Close()
btnExport.Visible = True
lblmsg.Visible = False
lblInstructions.Visible = False
End Sub
First of all . . .
Just as a disclaimer, I normally use repeater controls instead of gridview controls.
But this may help you . . .
I can tell you that with repeater controls, if you want to find a nested repeater then you must look for them inside the item of the parent repeater to which they belong. Essentially, what you are trying to do with the code above, is find grdChild when there might actually be several grdChild (it is a nested gridview, after all). I'd be willing to bet this is where you're object reference error is occurring.
In other words, if you want to find the nested repeater with the ID nestedRepeater, and you know it is located in the first item of your main repeater (which in this case I've assigned to the myRepeater variable), you can do this:
Dim myItem as RepeaterItem = myRepeater.Items(0)
Dim Rep2 as Repeater = myItem.FindControl("nestedRepeater")
Using SqlDataAdapter and a DataSet (recommended)
Dim sa As New SqlDataAdapter(cmdCounty) 'Initialize the SqlDataAdapter and assign the SqlCommand object to it.
Dim ds As New DataSet() 'Initialize the DataSet (we will bind this to the gridview)
Try 'The Try/Catch statements help you to handle errors.
cmdCounty.Connection.Open() 'Open the connection to the database.
sa.Fill(ds) 'This statement uses the SqlDataAdapter to easily execute the SqlCommand (using the query specified in the SqlCommand object) and . . .
'. . .use that data to fill our dataset.
cmdCounty.Connection.Close() 'These statement close the connection and dispose of the SqlCommand object. Note: You may only need the dispose command.
cmdCounty.Dispose()
Catch ex As Exception
'Catch your error here.
cmdCounty.Connection.Close()
cmdCounty.Dispose()
End Try
gv2.DataSource = ds 'Set the datasource for your GridView control.
gv2.DataBind() 'Bind the data.
Using SqlDataReader and a DataTable
According to your comment, you're code is breaking when you assign the gridview to the cmd.ExecuteReader.
You will need to access your data using a method like this:
Dim rdr as SqlDataReader = cmdCounty.ExecuteReader() 'Declare the SqlDataReader and set it to handle your SqlCommand.
Dim dt as New DataTable 'Initialize a new DataTable. This is where we will place the information we read using the SqlDataReader.
'Make sure you add the columns...
dt.Columns.Add("firstColumnName") 'Create a column for each field you will be retrieving data from.
dt.Columns.Add("secondColumnName")
Dim r as DataRow 'Declare the variable r as a DataRow.
'You may want to insert the line "If rdr.HasRows Then" to check if any data was pulled before attempting to read it.
While rdr.Read() 'Loop through each row in the reader.
r = dt.NewRow() 'Set r to equal a new DataTable in the DataTable we created. Note: This does not actually add the row to the table.
r("firstColumnName") = rdr("firstColumnName") 'Set the values of each column in the current DataRow to equal their corresponding data read from SQL.
r("secondColumnName") = rdr("secondColumnName")
dt.Rows.Add(r) 'Add the DataRow r to the DataTable.
End While 'Loop back until there are no more rows.
gv2.DataSource = dt
gv2.DataBind()
Both of these examples assume you have already created your SqlCommand object and have assigned a working SQL query string and Connection object to it.
I intended to do another SQL query inside here and retrieve data from another table by using the "category_id"
I know the problems that asp.net required me to close the data reader before proceed to another query. But is there any solution for me to do another query and open another data reader within the opening data reader?
My current code is as follows...
Dim dr, dr2 As SqlDataReader
Dim conn As SqlConnection
Dim cmd, cmd2 As SqlCommand
conn = New SqlConnection("server=XXX-PC;user=sa;password=abc123321;database=xxx")
cmd = New SqlCommand("SELECT * FROM category ORDER BY category_Name", conn)
conn.Open()
dr = cmd.ExecuteReader()
Do While dr.Read()
Dim category_id As Integer = dr.GetInt32(0)
Dim category_name As String = dr.GetString(1)
/* Another data reader and query here */
Loop
dr.Close()
conn.Close()
You have a few options:
Create a new connection to your database, and create the second data reader from that.
Use a SqlDataAdapter, and dump your queries into in-memory DataTables, and loop through them.
Use an Object-Relational mapper, like NHibernate, or Entity Framework, and obviate all these problems completely.
2 would probably be the simplest, and quickest to implement. 3 will require a bit of a learning curve, but would likely be worth it in the long run. 1 is actually a terrible idea; don't do it. I probably shouldn't even have listed it.
You can use MARS the ultimate feature of vs2005
[Multiple Active Result Sets ]
instead of datareader use Idatareader
Dim dr, dr2 As IDataReader
Dim conn As SqlConnection
Dim cmd, cmd2 As SqlCommand
conn = New SqlConnection("server=XXX-PC;user=sa;password=abc123321;database=xxx")
cmd = New SqlCommand("SELECT * FROM category ORDER BY category_Name", conn)
conn.Open()
dr = cmd.ExecuteReader()
Do While dr.Read()
Dim category_id As Integer = dr.GetInt32(0)
Dim category_name As String = dr.GetString(1)
/* Another data reader and query here */
cmd2.CommandText=” your query”
dr2 = cmd2.ExecuteReader();
Loop
dr2.Close();
dr.Close()
conn.Close()
MARS is disabled by default on the Connection object. You have to enable it with the addition of MultipleActiveResultSets=true in your connection string.
Create a Separate function, and create private data adapter & data set into it and perform your logic then return value to main procedure.