GridView + Access Database - asp.net

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

Related

Search function fail

I would like to search data in a textbox . Below is my code. I tried to search but nothing happen.
If Not Me.IsPostBack Then
Me.SearchPanelId()
End If
End Sub
Private Sub SearchPanelId()
Dim ConnectionString As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
Using con As New SqlConnection(ConnectionString)
Using cmd As New SqlCommand()
Dim sql As String = "SELECT panelid, panelname, paneltype FROM PANEL_TABLE"
If Not String.IsNullOrEmpty(TextBox1.Text.Trim()) Then
sql += " WHERE panelid LIKE #panelid + '%'"
cmd.Parameters.AddWithValue("#panelid", TextBox1.Text.Trim())
End If
cmd.CommandText = sql
cmd.Connection = con
Using sda As New SqlDataAdapter(cmd)
Dim dt As New DataTable()
sda.Fill(dt)
GridView1.DataSource = dt
GridView1.DataBind()
End Using
End Using
End Using
End Sub
Protected Sub Search(sender As Object, e As EventArgs)
Me.SearchPanelId()
End Sub
Protected Sub OnPaging(sender As Object, e As GridViewPageEventArgs)
GridView1.PageIndex = e.NewPageIndex
Me.SearchPanelId()
End Sub
Do the validation before you start creating objects. You need to check if that datatype of the ID is valid. I guessed that this was an Integer type but check your database. If I am wrong and the datatype is .VarChar then see the second rendition. :-) The Like keyword does not make any sense with a numeric field.
Don't use .AddWithValue See http://www.dbdelta.com/addwithvalue-is-evil/
and
https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/
and another one:
https://dba.stackexchange.com/questions/195937/addwithvalue-performance-and-plan-cache-implications
A DataAdapter is not necessary. Just use the load method of the DataTable.
Private Sub SearchPanelId()
Dim IDValue As Integer
Dim dt As New DataTable
If String.IsNullOrEmpty(TextBox1.Text.Trim()) OrElse Not Integer.TryParse(TextBox1.Text.Trim, IDValue) Then
Return
End If
Using con As New SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString)
Using cmd As New SqlCommand("SELECT panelid, panelname, paneltype FROM PANEL_TABLE WHERE panelid = #panelid", con)
cmd.Parameters.Add("#panelid", SqlDbType.Int).Value = IDValue
con.Open()
dt.Load(cmd.ExecuteReader)
End Using
End Using
GridView1.DataSource = dt
GridView1.DataBind()
End Sub
If Id is a .VarChar
Private Sub SearchPanelId()
Dim dt As New DataTable
If String.IsNullOrEmpty(TextBox1.Text.Trim()) Then
Return
End If
Using con As New SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString)
Using cmd As New SqlCommand("SELECT panelid, panelname, paneltype FROM PANEL_TABLE WHERE panelid Like #panelid", con)
cmd.Parameters.Add("#panelid", SqlDbType.VarChar).Value = TextBox1.Text.Trim() & "%"
con.Open()
dt.Load(cmd.ExecuteReader)
End Using
End Using
GridView1.DataSource = dt
GridView1.DataBind()
End Sub

Can't read data from SQL Server database

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"))

Program won't give me the right Sum

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

SQL and GridView

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)

loop through datatable and run stored procedure

I am trying to loop through a datatable, that will pass information to my stored procedure but it isn't working.
even though it works when i manuelly
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim dv As New DataView
Dim dt As New DataTable
dv = SqlDataSource1.Select(DataSourceSelectArguments.Empty)
dt = dv.ToTable()
For Each row As DataRow In dt.Rows
If row("vtr_gen10").ToString() = "y" Or row("vn10").ToString() = "a" Or row("vtr_gen10").ToString() = "p" Then
Dim SQLCon As New SqlClient.SqlConnection
Dim sqlcmd As New SqlCommand
SQLCon.ConnectionString = SqlDataSource2.ConnectionString
SQLCon.Open()
sqlcmd.CommandText = "protest" ' Stored Procedure to Call
sqlcmd.CommandType = CommandType.StoredProcedure 'Setup Command Type
sqlcmd.Connection = SQLCon 'Active Connection
sqlcmd.Parameters.AddWithValue("#ID", row("id"))
sqlcmd.Parameters.AddWithValue("#Value", "Y")
sqlcmd.ExecuteNonQuery()
SQLCon.Close()
End If
Next
End Sub
Are you absolutely sure the IF criteria is being met after the first two records? One thing to look for is spaces or other string anomalies such as carraige returns in your database...
Row("vn10").ToString for example may for some reason be "a " instead of "a". Might be worth putting in a temporary debug line such as :
Throw New Exception("[" & Row("vn10").ToString & "]")
or inspect length on some records that erroneously fail.
There is nothing seems to be wrong with your code, but if you think its because its moving too fast, try adding sleep using System.Threading.Thread.Sleep(milliseconds)

Resources