I'm using the Web service as given below for getting the data from database. In that code it has static string connection and string query. I'm using the same web service for multiple functions. Instead of using the same function I need to give the string query and string connection manually to avoid multiple of using the same code. Is it possible to give the string connection and string query in run time.
Here is the code.
<WebMethod()> _
Public Function GetData() As String
Dim sqlcon As New SqlClient.SqlConnection
Dim sqlcmd, cmd As SqlClient.SqlCommand
Dim objeDS, objeDS1 As DataSet
Dim adpp, adpp1 As SqlClient.SqlDataAdapter
Dim dt, dt1 As DataTable
Dim pack_tbl As New DataTable
sqlcon.ConnectionString = ConfigurationManager.AppSettings("constr")
sqlcon.Open()
sqlcmd = New SqlClient.SqlCommand()
sqlcmd.Connection = sqlcon
sqlcmd.CommandType = CommandType.Text
sqlcmd.CommandText = "sqlcommand"
objeDS = New DataSet()
adpp = New SqlClient.SqlDataAdapter()
adpp.SelectCommand = sqlcmd
adpp.Fill(objeDS)
sqlcon.Close()
dt = New DataTable()
dt = objeDS.Tables(0)
Return objeDS.GetXml()
'Return "Welcome"
End Function
Try this code this helps you.
VB code
<WebMethod()> _
Public Function GetData(ByVal strQuery As String, ByVal strCon As String) As String
Dim dt As New DataTable()
dt.Clear()
Using conn As New System.Data.SqlClient.SqlConnection()
conn.ConnectionString = ConfigurationManager.ConnectionStrings(strCon).ConnectionString
Using cmd As New System.Data.SqlClient.SqlCommand()
cmd.CommandText = strQuery
cmd.Connection = conn
conn.Open()
Dim da As New SqlDataAdapter(cmd)
da.Fill(dt)
Dim serializer As New System.Web.Script.Serialization.JavaScriptSerializer()
Dim rows As New List(Of Dictionary(Of String, Object))()
Dim row As Dictionary(Of String, Object)
For Each dr As DataRow In dt.Rows
row = New Dictionary(Of String, Object)()
For Each col As DataColumn In dt.Columns
row.Add(col.ColumnName, dr(col))
Next
rows.Add(row)
Next
Return serializer.Serialize(rows)
End Using
End Using
End Function
Related
How to call the datatable fill code without double in vb.net?.
in the code below you might see I wrote back the fill datatable code if there is a solution without me writing it back in "GenerateReport()". Please Recommend.
Thanks
Private WithEvents dt As New DataTable
Public Sub fillDataGridView1()
dt = New DataTable
Dim query As String = "SELECT NOD,ITM,CIA,DPR,QTY FROM RSD WHERE QTY > 0 AND PNM=#PNM"
Using con As OleDbConnection = New OleDbConnection(GetConnectionString)
Using cmd As OleDbCommand = New OleDbCommand(query, con)
cmd.Parameters.AddWithValue("#PNM", ComboBox1.SelectedValue)
Using da As New OleDbDataAdapter(cmd)
da.Fill(dt)
da.Dispose()
Dim totalColumn As New DataColumn()
totalColumn.DataType = System.Type.GetType("System.Double")
totalColumn.ColumnName = "Total"
totalColumn.Expression = "[CIA]*[QTY]*(1-[DPR]/100)"
dt.Columns.Add(totalColumn)
Me.grid.DataSource = dt
Me.grid.Refresh()
End Using
End Using
End Using
End Sub
Private Sub GenerateReport()
KtReport1.Clear()
'the code below actually already exists but I reuse it
dt = New DataTable
Dim query As String = "SELECT NOD,ITM,CIA,DPR,QTY FROM RSD WHERE QTY > 0 AND PNM=#PNM"
Using con As OleDbConnection = New OleDbConnection(GetConnectionString)
Using cmd As OleDbCommand = New OleDbCommand(query, con)
cmd.Parameters.AddWithValue("#PNM", ComboBox1.SelectedValue)
Using da As New OleDbDataAdapter(cmd)
da.Fill(dt)
Dim dtCloned As DataTable = dt.Clone()
dtCloned.Columns("CIA").DataType = GetType(String)
For Each row As DataRow In dt.Rows
dtCloned.ImportRow(row)
Next row
KtReport1.AddDataTable(dtCloned)
The issue is that you are essentially duplicating code despite the fact that you have a variable setup to hold the filled DataTable at the Form level.
What I would suggest doing is creating a function that returns the filled DataTable, then at the top of your two existing methods do a null check against the Form level variable.
Take a look at this example:
Private _dt As DataTable
Private Function GetAndFillDataTable() As DataTable
Dim dt As New DataTable()
Dim query As String = "SELECT NOD,ITM,CIA,DPR,QTY FROM RSD WHERE QTY > 0 AND PNM=#PNM"
Using con As OleDbConnection = New OleDbConnection(GetConnectionString)
Using cmd As OleDbCommand = New OleDbCommand(query, con)
cmd.Parameters.AddWithValue("#PNM", ComboBox1.SelectedValue)
Using da As New OleDbDataAdapter(cmd)
da.Fill(dt)
da.Dispose()
Dim totalColumn As New DataColumn()
totalColumn.DataType = System.Type.GetType("System.Double")
totalColumn.ColumnName = "Total"
totalColumn.Expression = "[CIA]*[QTY]*(1-[DPR]/100)"
dt.Columns.Add(totalColumn)
Return dt
End Using
End Using
End Using
End Function
Private Sub FillDataGridView1()
If (_dt Is Nothing) Then
_dt = GetAndFillDataTable()
End If
grid.DataSource = _dt
grid.Refresh()
End Sub
Private Sub GenerateReport()
If (_dt Is Nothing) Then
_dt = GetAndFillDataTable()
End If
Dim dtCloned As DataTable = _dt.Clone()
dtCloned.Columns("CIA").DataType = GetType(String)
For Each row In _dt.Rows
dtCloned.ImportRow(row)
Next row
KtReport1.AddDataTable(dtCloned)
End Sub
I am using an OledbConnection to an AS400 computer. When I have a SQL statement that will return nothing, it just hangs on the adapter command Fill.
Function ExecuteOLEDBQuery(ByVal cmdtext As String) As DataTable
Try
Dim connString As String = "Provider=IBMDA400;Persist Security Info=True;User ID=##USERID;Password=##PASSWORD;Data Source=##SYSTEM"
Dim as400 As New OleDb.OleDbConnection(connString)
Dim cmd As New OleDb.OleDbCommand(cmdtext, as400)
Dim adapter As New OleDb.OleDbDataAdapter(cmd)
cmd.CommandTimeout = 60 'Doesn't work. It never times out.
Dim dt As New DataTable
as400.Open()
adapter.Fill(dt) 'This is where it hangs
as400.Close()
adapter.Dispose()
cmd.Dispose()
Return dt
Catch ex As Exception
Return Nothing
End Try
End Function
Any ideas?
It may be the connection to the AS400 itself. Try this version which disposes of the object in a slightly different order:
Function ExecuteOLEDBQuery(cmdtext As String) As DataTable
Using cn = New OleDbConnection("Provider=IBMDA400;Persist Security Info=True;User ID=##USERID;Password=##PASSWORD;Data Source=##SYSTEM")
cn.Open()
Using da = New OleDbDataAdapter(cmdtext, cn)
Dim dt = New DataTable
da.Fill(dt)
Return dt
End Using
End Using
End Function
I'm new in vb.net. I'm using vb.net and sql
I had query this "SELECT * FROM sf_OEEShowRed" and how I'm going to show the result in Label1.Text? Below are my code.
Private Function GetRed()
Try
Dim connectionString As String = System.Configuration.ConfigurationManager.AppSettings("StrConn")
Dim sqlConnection As SqlClient.SqlConnection = New SqlClient.SqlConnection(connectionString)
Dim queryString As String = "SELECT * FROM sf_OEEShowRed"
Dim sqlCommand As SqlClient.SqlCommand = New SqlClient.SqlCommand(queryString, sqlConnection)
sqlCommand.CommandTimeout = 0
Dim dataAdapter As SqlClient.SqlDataAdapter = New SqlClient.SqlDataAdapter(sqlCommand)
Dim dataSet As DataSet = New DataSet
dataAdapter.Fill(dataSet)
Return dataSet
Finally
Label1.Text =
End Try
End Function
You can try:
Me.Label1.Text = dataSet.tables(0).defaultview
I'm trying to learn VB.NET and I'm looking to retrieve data from an Access 2010 view, using Vb.NET 2008, problem is I'm getting the following error. System.ArgumentNullException was unhandled Message=Value cannot be null
I cannot work out how to solve the error, so hopefully someone with more experience can help.
Public Function GetMyoleDataAdapterStudentQuestionRepeat(ByRef mydataSet As DataSet, ByVal topicId As String, ByVal groupId As String) As OleDbDataAdapter
Try
Dim strAccessConn As String = _appConfigDbConn
Dim cn As OleDbConnection = New OleDbConnection(strAccessConn)
Dim ds As New DataSet
Dim da As New OleDbDataAdapter("qryStudentNameRandomBasedOnScore", cn)
da.SelectCommand.CommandType = CommandType.StoredProcedure
da.SelectCommand.Parameters.AddWithValue("#GroupID", groupId)
da.Fill(ds, "Student")
Return da
Catch ex As Exception
Throw New ApplicationException(ex.InnerException.Message.ToString())
End Try
End Function
Within button click
Dim myoleDataAdapter As OleDbDataAdapter = GroupData.GetMyoleDataAdapterStudentQuestionRepeat(mydataSet, topicId, groupId)
myoleDataAdapter.Fill(mydataSet)
txtStudentName.DataBindings.Add("Text", mydataSet.Tables(0), "studentname")
This line throws error: myoleDataAdapter.Fill(mydataSet)
And in case it helps, my view is
SELECT TOP 1 tblStudentNameAndScore.studentname
FROM tblStudentNameAndScore
WHERE (((tblStudentNameAndScore.[QuizCount]) Between 2 And 10)) AND tblStudentNameAndScore.GroupID = ?
ORDER BY Rnd(QuizCount);
Thanks for any hep
In this line
myoleDataAdapter.Fill(mydataSet)
you try to fill the dataset but this dataset is never initialized.
Following your actual pattern, you should change your code that initialize the dataadapter in this way
Public Function GetMyoleDataAdapterStudentQuestionRepeat(ByVal topicId As String, ByVal groupId As String) As OleDbDataAdapter
Try
Dim strAccessConn As String = _appConfigDbConn
Dim cn As OleDbConnection = New OleDbConnection(strAccessConn)
Dim ds As New DataSet
Dim da As New OleDbDataAdapter("qryStudentNameRandomBasedOnScore", cn)
da.SelectCommand.CommandType = CommandType.StoredProcedure
da.SelectCommand.Parameters.AddWithValue("#GroupID", groupId)
Return da
Catch ex As Exception
Throw New ApplicationException(ex.InnerException.Message.ToString())
End Try
End Function
and then in the caller code write
Dim myoleDataAdapter As OleDbDataAdapter = GroupData.GetMyoleDataAdapterStudentQuestionRepeat( topicId, groupId)
mydataSet = new DataSet()
myoleDataAdapter.Fill(mydataSet)
....
In the method that returns the adapter you don't need to pass the dataset because you don't use it in any way and there is no need to create and fill another dataset. Just return the adapter and work on the caller code
Of course you could also change the method and return a dataset filled with your data instead of the DataAdapter. Probably this solution could be considered more encapsulated
Public Function GetStudentQuestionRepeat(ByVal topicId As String, ByVal groupId As String) _
As Dataset
....
Dim da As New OleDbDataAdapter("qryStudentNameRandomBasedOnScore", cn)
da.SelectCommand.CommandType = CommandType.StoredProcedure
da.SelectCommand.Parameters.AddWithValue("#GroupID", groupId)
Dim ds = new Dataset()
da.Fill(ds, "Student")
Return ds
....
End Function
By the way, what is the purpose of topidID variable passed and never used?
Why not return a Dataset instead of DataAdapter, like:
Public Function GetMyoleDataAdapterStudentQuestionRepeat(ByVal topicId As String, ByVal groupId As String) As DataSet
Try
Dim strAccessConn As String = _appConfigDbConn
Dim cn As OleDbConnection = New OleDbConnection(strAccessConn)
Dim ds As New DataSet
Dim da As New OleDbDataAdapter("qryStudentNameRandomBasedOnScore", cn)
da.SelectCommand.CommandType = CommandType.StoredProcedure
da.SelectCommand.Parameters.AddWithValue("#GroupID", groupId)
da.Fill(ds, "Student")
Return ds
Catch ex As Exception
Throw New ApplicationException(ex.InnerException.Message.ToString())
End Try
End Function
And then when you call it would be shorter:
Dim myDataSet As DataSet = GroupData.GetMyoleDataAdapterStudentQuestionRepeat(topicId, groupId)
txtStudentName.DataBindings.Add("Text", myDataSet.Tables(0), "studentname")
The result of my sql-query is a single value i want display that in a lable but dont know how. I have a solution creating a dataset put the result of the query into that dataset and get it by row(0),column(0) but i guess there is a smarter way doing it.
Private myquery As String
Sub New(ByVal query As String)
myquery = query
End Sub
Public Sub query_Send()
Dim myconn As New SqlConnection("Data Source=DB;Integrated Security=TRUE")
Dim mycmd As SqlCommand = New SqlCommand(Me.myQuery, myconn)
Dim myTable As New DataTable
Dim previousConnectionState As ConnectionState = myconn.State
Try
If myconn.State = ConnectionState.Closed Then
myconn.Open()
Dim myDA As New SqlDataAdapter(mycmd)
myDA.Fill(myTable)
tb.text = **...**
End If
If previousConnectionState = ConnectionState.Closed Then
myconn.Close()
End If
End Try
End Sub
You can use SqlCommand.ExecuteScalar Method
Dim querystr as String = "select value from MyTable where ID=5"
Dim mycmd As New SqlCommand(querystr, connection)
dim value as Object = mycmd.ExecuteScalar()
The value you can put to your textbox. ExecuteScalar returns first value of first row of the resultset (equivalent of row(0).column(0) ) When no record is returned the value is nothing.
Try something more along the lines of:
Using myconn As New SqlConnection("Data Source=DB;Integrated Security=TRUE")
Dim myDA As New SqlDataAdapter()
myDA.SelectCommand = New SqlCommand(myQuery, myconn)
myDA.Fill(myTable)
Return myTable
End Using
Or you can just get ahold of the first item in the first row with
myTable.Rows(0).ItemArray(0).ToString()