Invalid attempt to call Read when reader is closed - asp.net

I'm attempting to create a search page, which will display the results into a Gridview, but keep getting the following error when I click the my search button: Invalid attempt to call Read when reader is closed.
This is my code:
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim connectionString As [String] = ConfigurationManager.ConnectionStrings("myDbConnectionString1").ConnectionString
Dim connection As New SqlConnection(connectionString)
connection.Open()
Dim mySQLQuery As String
Dim vID As String
vID = Request.QueryString("pgResults")
mySQLQuery = "SELECT name,address,results,url FROM myTb WHERE name LIKE '%" + TextBox1.Text + "%'"
Dim myCommand As New SqlCommand(mySQLQuery, connection)
Dim myReader1 As SqlDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection)
While (myReader1.Read())
GridView1.DataSource = myReader1
GridView1.DataBind()
End While
panelBody.Visible = False
panelSearchResults.Visible = True
connection.Close()
End Sub
Could I get some help please?

You cannot call Read() and then use a IDataReader as a DataSource, let DataBinding handle that. try this:
Dim myReader1 As SqlDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection)
GridView1.DataSource = myReader1
GridView1.DataBind()

Related

asp.net DropDownList postback not executing method on first postback

I'm facing very un natural problem suddenly. I have DropDownList with autopostback is true. Postback executes a method which populates other things onpage according to selection. Now When I select any value first time from that dropdown then page gets postback but nothing get populate but from second time it works fine. Even I put breakpoint on that dropdown & it's not even hitting breakpoint for first postback.
<asp:DropDownList ID="ClientCode" runat="server" ClientIDMode="Static" CssClass="field-pitch" AutoPostBack="true"></asp:DropDownList>
Private Sub ClientCode_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ClientCode.SelectedIndexChanged
Me.populateConsignerDetails()
End Sub
Private Sub populateConsignerDetails()
Try
Dim str As String = "SELECT * FROM clientsDetails WHERE clientID = #clientID"
con.Open()
Dim cmd As New MySqlCommand(str, con)
cmd.Parameters.AddWithValue("#clientID", ClientCode.SelectedItem.ToString)
Dim da As New MySqlDataAdapter(cmd)
Dim dt As New DataTable
da.Fill(dt)
con.Close()
Dim payingParty As String = String.Empty
If dt.Rows.Count > 0 Then
consignerName.Text = dt.Rows(0)("clientName").ToString
consignerAddress.Text = dt.Rows(0)("companyAddress").ToString
consignerMobile1.Text = dt.Rows(0)("contactNumber1").ToString
consignerCity.Text = dt.Rows(0)("city").ToString
consignerState.Text = dt.Rows(0)("state").ToString
consignerPinCode.Text = dt.Rows(0)("pinCode").ToString
End If
Catch ex As Exception
Response.Write(ex)
End Try
End Sub
Update
Private Sub myadmin_shipment_details2_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
populateClient()
End If
End Sub
Private Sub populateClient()
Using conn As New MySqlConnection()
conn.ConnectionString = ConfigurationManager _
.ConnectionStrings("conio").ConnectionString()
Using cmd As New MySqlCommand()
cmd.CommandText = "Select * from clientsDetails where status = 'active'"
cmd.Connection = conn
conn.Open()
Using sdr As MySqlDataReader = cmd.ExecuteReader()
While sdr.Read()
Dim item As New ListItem()
item.Text = sdr("clientID").ToString()
item.Value = sdr("ClientName").ToString()
ClientCode.Items.Add(item)
End While
End Using
conn.Close()
End Using
End Using
End Sub

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

How to delete data in database using grid view in vb.net

I'm a beginner in vb.net. Currently I'm develop a simple application by using a grid view. however, I'm facing a problem in deleting the data. When I click delete button, it keep adding the blank line. and this blank line is affected my database also. and this blank line also can't be deleted from database manually.
here my code behind
`Imports System.Data.SqlClient
Imports System.Drawing
Imports System.Data
Imports System.Configuration
Imports System.Linq
Partial Class test2
Inherits System.Web.UI.Page
Dim AMS As String = System.Web.Configuration.WebConfigurationManager.ConnectionStrings("AMS").ConnectionString
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not IsPostBack Then
Me.BindData()
End If
End Sub
Private Sub BindData()
Dim dt As DataTable = New DataTable
Dim strConnString As String = ConfigurationManager.ConnectionStrings("AMS").ConnectionString
Using con As SqlConnection = New SqlConnection(strConnString)
Dim strQuery As String = "SELECT * FROM ModuleDetail"
Using cmd As SqlCommand = New SqlCommand(strQuery)
Dim sda As SqlDataAdapter = New SqlDataAdapter
cmd.Connection = con
con.Open()
sda.SelectCommand = cmd
sda.Fill(dt)
GridView1.DataSource = dt
GridView1.DataBind()
End Using
End Using
End Sub
Protected Sub GridView1_RowDeleting(ByVal sender As Object, ByVal e As GridViewDeleteEventArgs)
Dim IsDeleted As Boolean = False
Dim ModuleID As String = Convert.ToInt32(GridView1.DataKeys(e.RowIndex).Value.ToString())
Dim ModuleName As Label = CType(GridView1.Rows(e.RowIndex).FindControl("lblModuleName"), Label)
Dim SubModule As Label = CType(GridView1.Rows(e.RowIndex).FindControl("lblSubModule"), Label)
Dim strConnString As String = ConfigurationManager.ConnectionStrings("AMS").ConnectionString
Using con As SqlConnection = New SqlConnection(strConnString)
Using cmd As SqlCommand = New SqlCommand
cmd.CommandType = CommandType.Text
cmd.CommandText = "DELETE FROM ModuleDetail WHERE ModuleID=#ModuleID"
cmd.Parameters.AddWithValue("#ModuleID", ModuleID)
cmd.Connection = con
con.Open()
IsDeleted = cmd.ExecuteNonQuery() > 0
con.Close()
GridView1.DataSource = cmd
GridView1.DataBind()
End Using
End Using
If IsDeleted Then
lblMsg.Text = "'" & SubModule.Text & "' details has been deleted successfully!"
lblMsg.ForeColor = System.Drawing.Color.Green
BindData()
Else
lblMsg.Text = "Error while deleting '" & SubModule.Text & "' details"
lblMsg.ForeColor = System.Drawing.Color.Red
End If
End Sub
`
I have try a few code from others sources but it shows the same logic error which keep adding the blank line. I hope you guys can help me to solve the issue.
Though it might not relevant to your problem context, but I have observed a couple of issues from your code:
1) It seems you are binding grid twice after row delete.
2) Try commenting following lines since you already calling BindData() whithin IsDeleted flag check.
GridView1.DataSource = cmd;
GridView1.DataBind();
3) You are assigning the 'Command' object: cmd to the Grid's datasource which is not correct. Check your BindData(...) method how you need to bind Grid actually.

Getting error for Data Reader in vb.net

Im facing the error when execute the data reader command in vb.net. it throw handling. This field like when you enter employee id in textbox then it will capture in database for other field name,department.
here is my code
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim conn As New MySql.Data.MySqlClient.MySqlConnection
Dim strConnectionString As String =ConfigurationManager.ConnectionStrings("testConnectionString").ConnectionString
Dim sqlQuery As String = "SELECT * hr_record WHERE Emplid='" & txt1.Text & "'"
Using sqlConn As New MySqlConnection(strConnectionString)
Using sqlComm As New MySqlCommand()
With sqlComm
.CommandText = sqlQuery
End With
Try
sqlConn.Open()
Dim sqlReader As MySqlDataReader = sqlComm.ExecuteReader()
While sqlReader.Read()
txt1.Text = sqlReader("Emplid").ToString()
TextBox1.Text = sqlReader("Nama").ToString()
TextBox2.Text = sqlReader("DeptDesc").ToString()
End While
Catch ex As MySqlException
MessageBox.Show(ex.Message)
End Try
End Using
End Using
End Sub
Try to change your select query like
Dim sqlQuery As String = "SELECT * from hr_record WHERE Emplid='" & txt1.Text & "'"
Note:- Cannot use code like that in Page_Load.Try to make one Function and call that function from Page_Load and always use Parameterized query.
Updated answer:
Page_Load
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
DataBind()
End Sub
Outside Method:
Public Sub DataBind()
Dim sConnection As String = "server=(local);uid=sa;pwd=PassWord;database=DatabaseName"
Using Con As New MySqlConnection(sConnection)
Con.Open()
Using Com As New MySqlCommand("SELECT * from hr_record WHERE Emplid='"txt1.Text
"'", Con)
Using RDR = Com.ExecuteReader()
If RDR.HasRows Then
Do While RDR.Read
txt1.Text = RDR.Item("Emplid").ToString()
TextBox1.Text = RDR.Item("Nama").ToString()
TextBox2.Text = RDR.Item("DeptDesc").ToString()
Loop
End If
End Using
End Using
Con.Close()
End Using
End Sub
Note:Try to implement your logic like that and also modified as per your requirements.
Hope it works.
You try to get Emplid in page load,but it's still nothing you should use button to check if Emplid exist
Thanks to all thanks helping me..finally this code it works thanks to all .
this the code will be function
Dim conn As New MySql.Data.MySqlClient.MySqlConnection
Dim strConnectionString As String = ConfigurationManager.ConnectionStrings("testConnectionString").ConnectionString
Using sqlConn As New MySqlConnection(strConnectionString)
sqlConn.Open()
Using sqlComm As New MySqlCommand()
sqlComm.Connection = sqlConn
With sqlComm
.CommandText = "SELECT * from hr_record WHERE Emplid='" & txt1.Text & "'"
End With
Try
Dim sqlReader As MySqlDataReader = sqlComm.ExecuteReader()
While sqlReader.Read()
txt1.Text = sqlReader("Emplid").ToString()
TextBox1.Text = sqlReader("Nama").ToString()
txtdep.Text = sqlReader("DeptDesc").ToString()
End While
Catch ex As MySqlException
MessageBox.Show(ex.Message)
End Try
sqlConn.Close()
End Using
End Using
End Sub

Populating dropdownlist on pageload event

I can't see why this is not working.
I have a dropdownlist named ddlRoomName and a SQL table named roomlist.
When i run the SQL command in SQL editor it works fine. But when I load the page the rooms do not load!
Am i missing something obvious here?
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Page.IsPostBack Then
ddlRoomName.Items.Clear()
ddlRoomName.Items.Add(New ListItem("--Select Room--", ""))
ddlRoomName.AppendDataBoundItems = True
Dim strConnString As String = ConfigurationManager.ConnectionStrings("a_cisco").ConnectionString
Dim strQuery As String = "Select * from roomlist"
Dim con As New SqlConnection(strConnString)
Dim cmd As New SqlCommand()
cmd.CommandType = CommandType.Text
cmd.CommandText = strQuery
cmd.Connection = con
Try
con.Open()
ddlRoomName.DataSource = cmd.ExecuteReader()
ddlRoomName.DataTextField = "RoomName"
ddlRoomName.DataValueField = "intRoom"
ddlRoomName.DataBind()
Catch ex As Exception
Throw ex
Finally
con.Close()
End Try
End If
End Sub
You are only loading them on a postback. Is it really what you want? Maybe you want:
If Not Page.IsPostBack Then
End If
(then the ViewState will keep the items in the DropDownList in a postback)

Resources