I am currently doing a project on web service for wine. I have the wine table with wineName and wineType. Also I have the search function implemented in the webservice coding as well as a separate webform to call the function of the search function
I have the following code for performing search in the search service:
<WebMethod()> _
Public Function Search(ByVal searchName As String) As System.Data.DataSet
Dim connectionString As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
Dim con As New SqlConnection(connectionString)
Dim selectSql As String = "SELECT * From Wine WHERE WineType='" & searchName + "'"
Dim selectAdapter As New Data.SqlClient.SqlDataAdapter(selectSql, con)
Dim ds As New Data.DataSet
con.Open()
selectAdapter.Fill(ds, "Wine")
con.Close()
Return ds
End Function
As for the webform, it's just a simple page with textbox labeled as searchName, a button and a gridView1 tied to ObjectDataSource.
This is the coding i have for webform:
Partial Class Search
Inherits System.Web.UI.Page
Dim searching As searchwine.Service = New searchwine.Service
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
If searchName.Text = "" Then
lblDisplayError.Text = "Can't search empty field!"
Else
Dim ds As DataSet = searching.Search(searchName.Text)
GridView1.DataSource = ds.Tables(0)
GridView1.DataBind()
GridView1.Visible = True
lblDisplayError.Visible = False
End If
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
lblDisplayError.Text = ""
GridView1.Visible = False
End Sub
End Class
Everything seems fine, but i have the following error when i want to do a search:
System.NullReferenceException: Object reference not set to an instance of an object. at Service.Search(String searchName)
Can anyone help me out please?
I've looked through your code a couple times and I can't see what's causing the NullReferenceException. My best guess is that it couldn't find a connection string name "ConnectionString" in your web.config file, but even that doesn't quite seem to fit.
I can suggest some improvements to your search code. Hopefully you'll at least get a better error message out of this:
<WebMethod()> _
Public Function Search(ByVal searchName As String) As System.Data.DataSet
Dim ds As New Data.DataSet()
Dim connectionString As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
Using con As New SqlConnection(connectionString), _
cmd As New SqlCommand("SELECT * From Wine WHERE WineType= #SearchName", con)
'I had to guess at the exact length and type of the field here
cmd.Parameters.Add("#SearchName", SqlDbType.VarChar, 50).Value = searchName
Dim selectAdapter As New Data.SqlClient.SqlDataAdapter(cmd, con)
selectAdapter.Fill(ds, "Wine")
End Using
Return ds
End Function
But in the end I expect you'll need to step through the method and see exactly which line above throws the exception.
Looks like you are missing a New
Dim ds As DataSet = searching.Search(searchName.Text)
Should be...
Dim ds As **New** DataSet = searching.Search(searchName.Text)
Related
I'm having a problem when I'm reading data from a SQL Server database. The main thing is that I want to read the data from the database and display the data in a Label control. But the concern is that it can't read data to it. I will show you the code snippet and any comments/suggestions are gladly considered.
Option Explicit On
Imports System.Data
Imports System.Data.OleDb
Partial Class ViewDetail
Inherits System.Web.UI.Page
Dim con As OleDbConnection
Dim cmd As OleDbCommand
Dim dr As OleDbDataReader
Dim InstructorID As Integer
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
InstructorID = Request.QueryString("Instructor_ID")
Integer.TryParse(lblID.Text, InstructorID)
con = New OleDbConnection("Provider=SQLNCLI11;Data Source=ARIES-PC\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=SchoolDB")
con.Open()
cmd = New OleDbCommand("SelectData", con)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("#id", InstructorID)
dr = cmd.ExecuteReader
If dr.HasRows Then
While dr.Read
lblID.Text = dr("Instructor_ID").ToString
lblFirstname.Text = dr("FirstName").ToString
lblLastname.Text = dr("LastName").ToString
lblAddress.Text = dr("Address").ToString
lblContact.Text = dr("Contact_Number").ToString
End While
End If
dr.Close()
cmd.Dispose()
con.Close()
End Sub
End Class
This line seems to be totally wrong
Integer.TryParse(lblID.Text, InstructorID)
This lines takes the current value in the lblID.Text at the Page_Load event and tries to set the value of InstructorID. But your code seems to want this value from the QueryString passed that contains the real value.
If you are certain the the QueryString contains a valid integer then remove that line and add
InstructorID = Convert.ToInt32(Request.QueryString("Instructor_ID"))
I want to get the sum of the selected items in the listbox and display them in a label but i am always getting 0,i also want to put the selected items in another label too which is also not working.
Here is what the code look like:
Dim sum As Integer
Dim Items1 As String = "None"
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Label2.Text = Request.QueryString("Name").ToString()
Dim connetionString As String = Nothing
Dim connection As SqlConnection
Dim command As SqlCommand
Dim adapter As New SqlDataAdapter()
Dim ds As New DataSet()
Dim sql As String
connetionString = "Data Source=.;Initial Catalog=Shop;integrated security=true"
sql = "select PhoneName,PhonePrice from SmartPhones"
connection = New SqlConnection(connetionString)
connection.Open()
command = New SqlCommand(sql, connection)
adapter.SelectCommand = command
adapter.Fill(ds)
adapter.Dispose()
command.Dispose()
connection.Close()
ListBox1.DataSource = ds.Tables(0)
ListBox1.DataTextField = "PhoneName"
ListBox1.DataValueField = "PhonePrice"
ListBox1.DataBind()
End Sub
code where the display should happen:
Protected Sub Button2_Click(sender As Object, e As EventArgs) Handles TotalPrice.Click
sum = 0 'reset sum to 0
For Each i As Integer In ListBox1.GetSelectedIndices
Dim CurrentItem As ListItem = ListBox1.Items(i)
sum = sum + CInt(CurrentItem.Value)
Items1 = Items1 + " , " + CStr(CurrentItem.Text)
Next
Label3.Text = Items1
Label1.Text = sum
End Sub
Here is the page Design and the Page On the web Respectively:
PhoneName is of type varchar in database & PhonePrice is of type integer (Both Filled correctly).
ListBox code:
<asp:ListBox ID="ListBox1" runat="server" SelectionMode="Multiple" ></asp:ListBox>
What's the reason that the code won't give me the desired result?
What is happening is that when you click TotalPrice a postback is performed (What is a postback?). If you look at the ASP.NET page lifecycle you will see that the Load event happens before the postback event handling (e.g. your Sub Button2_Click).
So, you click the button, it runs the Me.Load handler and... your list is reset before the click handler gets a chance to run.
There is a property you can check to see if the page is running as a result of a postback: Page.IsPostBack.
So all you need to do is check it to see if you need to populate the list:
Sub FillItemsList()
Dim connectionString As String = "Data Source=.;Initial Catalog=Shop;integrated security=true"
Dim dt As New DataTable()
Using connection As New SqlConnection(connectionString)
Dim sql As String = "SELECT PhoneName,PhonePrice FROM SmartPhones"
Using adapter As New SqlDataAdapter(sql, connection)
adapter.Fill(dt)
End Using
End Using
ListBox1.DataSource = dt
ListBox1.DataTextField = "PhoneName"
ListBox1.DataValueField = "PhonePrice"
ListBox1.DataBind()
End Sub
Private Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Label2.Text = Request.QueryString("Name").ToString()
If Not Page.IsPostBack Then
FillItemsList()
End If
End Sub
Imports System.Data.Odbc
Imports System.Data
Partial Class VIEW_SALARY_DETAILS
Inherits System.Web.UI.Page
Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim cons, query As String
Dim con As OdbcConnection
Dim adpt As OdbcDataAdapter
cons = "dsn=Courier; UID=Courier; PWD=123;"
con = New OdbcConnection(cons)
con.Open()
query = "select * from EMPLOYEE"
Dim ds As DataSet
adpt = New OdbcDataAdapter(query, con)
ds = New DataSet
adpt.Fill(ds, "Courier")
GridView1.DataSource = ds.Tables()
con.Close()
End Sub
End Class
I wrote the above code but it does not display data.
Same thing is possible in VB.NET application.
How do we do it for ASP.net 4.0?
You missed a line after
GridView1.DataSource = ds.Tables[0] //do some correction here..
GridView1.DataBind(); // add this line
You need to bind the GridView with the Datasource..
Your code will be
Imports System.Data.Odbc
Imports System.Data
Partial Class VIEW_SALARY_DETAILS
Inherits System.Web.UI.Page
Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim cons, query As String
Dim con As OdbcConnection
Dim adpt As OdbcDataAdapter
cons = "dsn=Courier; UID=Courier; PWD=123;"
con = New OdbcConnection(cons)
con.Open()
query = "select * from EMPLOYEE"
Dim ds As DataSet
adpt = New OdbcDataAdapter(query, con)
ds = New DataSet
adpt.Fill(ds, "Courier")
GridView1.DataSource = ds.Tables[0]
GridView1.DataBind()
con.Close()
End Sub
End Class
Ensure that connection or sql string you used should be correct.
You'll need to call the DataBind() method. Try this
DataSet ds= new DataSet();
GridView1.DataSource = ds.Tables();
GridView1.DataBind();
I suggest this:
Assuming this markup:
So we dragged in a button , and a gridview.
Now, double click on the button, and we get/have this code stub:
Imports System.Data.SqlClient
Public Class HotelGrid
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Sub LoadGrid()
Using cmdSQL As New SqlCommand("SELECT ID, FirstName, LastName, HotelName, City from tblHotels",
New SqlConnection(My.Settings.TEST3))
cmdSQL.Connection.Open()
GridView1.DataSource = cmdSQL.ExecuteReader
GridView1.DataBind()
End Using
End Sub
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
LoadGrid()
End Sub
End Class
Note a FEW important things here.
First I VERY much recommend for general sql data pulls, use the sql command object.
Why?
Well, the command object has:
A place to hold/have/set the sql (sql command text)
A connection object - no need to create a separate one
A data reader - no need to create a separate one
In other words, the sql command object HAS ALL THREE basic bits and parts to pull data.
And we often want say some kind of recordset (data table), so we COULD have done this:
dim MyTable as new DataTable
Using cmdSQL As New SqlCommand("SELECT ID, FirstName, LastName, HotelName, City from tblHotels",
New SqlConnection(My.Settings.TEST3))
cmdSQL.Connection.Open()
MyTable.load(cmdSQL.ExecuteReader)
GridView1.DataSource = MyTable
GridView1.DataBind()
End Using
So note how in above, we created a data table object. And that data table can then be interated with for/each. You can even edit data in that table, or as above shows, load up the data table with data - and THEN assign it to the grid view.
The resulting output is thus this:
FYI:
In my example, I used sqlclient provider. In YOUR case, you are using ODBC provider. So the above code will be exact same, but NOW using ODBC, we get this:
So in place of ado.net (sql Client), you using ODBC. So you have a
Imports System.Data.Odbc
And thus our load grid code could/would be this:
Sub LoadGrid2()
Using cmdSQL As New OdbcCommand("SELECT ID, FirstName, LastName, HotelName, City from tblHotels",
New OdbcConnection(My.Settings.TEST3ODBC))
cmdSQL.Connection.Open()
GridView1.DataSource = cmdSQL.ExecuteReader
GridView1.DataBind()
End Using
End Sub
So, note how the code is really the "same", but JUST with a different provider (ODBC in your case).
And you can still declare and use say a "data table" to hold the query results.
I'm trying to link Access database with GridView control.
Here's the question:
One successful procedure to link database query.
Protected sub Query(ByVal y as string)
Dim da As New OleDbDataAdapter(y, cn)
Dim dt As New DataTable()
da.Fill(dt)
da.Dispose()
cn.Dispose()
Me.GridView1.DataSource = dt
Me.GridView1.DataBind()
ListBox1.Visible = True
End sub
What I wanted is to re-run query if the first run returns no value/result in another procedure.
Protected Sub btnFind_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnFind.Click
x = "SELECT * From Class Where Gender ='Male' And First_name ='James' "
Query(x)
If gridview.rows.count =0 then
x= "SELECT * From Class Where Gender ='Male'"
query(x)
End If
then put result into listbox.
However, I got error of "The ConnectionString property has not been initialized." on da.Fill(dt) when running the second time. First time was successful.
OK I finally got mistake corrected. I gotta Dim cn As New OleDbConnection("Provider = Microsoft.JET.OLEDB.4.0;" & "Data Source = C:\Class.mdb") again to use query instead of once for all queries.
Create and dispose the connection in the same method
Protected Sub Query(ByVal y as string)
Dim dt As New DataTable()
Using cn as New OleDbConnection("your_connection_string"), _
da As New OleDbDataAdapter(y, cn)
da.Fill(dt)
End Using
Me.GridView1.DataSource = dt
Me.GridView1.DataBind()
End Sub
As you can see from the commented out code, I'm trying to get the model dropdown be affected by + selCurrentManuf.Text.
I get this error
'selCurrentManuf' is not declared. It may be inaccessible due to its protection level.
How can this be solved?
I can access the drop down in another part of the page like this..
Dim sc1_currentmanuf As String = CType(e.Item.FindControl("selCurrentManuf"), DropDownList).Text
However in the function i am trying to use selCurrentManuf does not have access to e
Dim sc1_currentmanuf As String = CType(dlContacts.Items(0).FindControl("selCurrentManuf"), DropDownList).Text
Dim myQuery As String = "SELECT * FROM c5_model where c5_manufid = " + sc1_currentmanuf
Right click on your .aspx page, and select the command Convert To Web Application.
Then you'll be able to write:
Dim myQuery As String =
String.Format("SELECT * FROM c5_model WHERE c5_manuf = '{0}'",
selCurrentManuf.SelectedItem.Text )
I'm assuming your functions are inside a class in your App_Code or another dll and not on the code behind of the page.
If so do this instead:
I'm assuming you have something like this on your asp page code behind:
Protected Sub selCurrentManuf_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
GetCurrentModel(selCurrentManuf.Text)
End Sub
Change Your GetCurrentModel Code To:
Function GetCurrentModel(Byval c5_manuf as String) As DataSet
Dim mySession = System.Web.HttpContext.Current.Session
Dim myQuery As String = "SELECT * FROM c5_model " 'where c5_manuf = " + + c5_manuf
Dim myConnection As New MySqlConnection(mySession("localConn"))
myConnection.Open()
Dim myCommand As New MySqlCommand(myQuery, myConnection)
Dim myDataAdapter = New MySqlDataAdapter(myCommand)
Dim myDataset As New DataSet
myDataAdapter.Fill(myDataset, "c5_model")
Dim dr As DataRow = myDataset.Tables(0).NewRow
myDataset.Tables(0).Rows.Add(dr)
GetCurrentModel = myDataset
myConnection.Close()
End Function