VB dot net session value set in text box not change - asp.net

In one of my vb page i am setting the value of a textbox through the value coming from session. In the same page i want to perform an edit operation of the record. On the page load i displayed the variables in textboxes and after editing values when i submit and take the value from the textboxes, it still take the value i set through session. It do not take the value changed in the textbox rather it shows the value assigned at the time of page load. Please help.
Here is my code,
Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.SessionState.HttpSessionState
Imports System.Drawing
Imports System.Drawing.Printing
Partial Class Default2
Inherits System.Web.UI.Page
Dim cn As New SqlConnection
Dim cmd As New SqlCommand
Dim dr As SqlDataReader
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
cn = New SqlConnection("Data Source=nnn-PC;Initial Catalog=Faculty Housing;Persist Security Info=True;User ID=sa;Password=nnn;")
cn.Open()
Dim var As String
var = Session("S2").ToString()
TextBox1.Text = var
Session.Remove("S2")
cmd = New SqlCommand("select * from HouseDetails where OccupantName= '" & TextBox1.Text & "' ", cn)
dr = cmd.ExecuteReader
While (dr.Read)
Label1.Text = dr(1)
Label2.Text = dr(2)
Label3.Text = dr(3)
TextBox3.Text = dr(4)
DropDownList3.SelectedItem.Text = dr(5)
TextBox2.Text = dr(6)
TextBox4.Text = dr(7)
TextBox5.Text = dr(8)
DropDownList4.Text = dr(9)
End While
cn.Close()
End Sub
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
cn = New SqlConnection("Data Source=nnn-PC;Initial Catalog=Faculty Housing;Persist Security Info=True;User ID=sa;Password=nnn;")
cn.Open()
Dim query As String = ("UPDATE HouseDetails SET OccupantName='" & TextBox1.Text & "' where HouseNum='" & Label3.Text & "'")
cmd = New SqlCommand(query, cn)
Dim x As Integer = cmd.ExecuteNonQuery()
cn.Close()
End Sub
Protected Sub TextBox1_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
End Sub
End Class

Add postback prevention with the line "If (Page.IsPostBack = false) Then", for not assigning the same value again to the textbox,
Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.SessionState.HttpSessionState
Imports System.Drawing
Imports System.Drawing.Printing
Partial Class Default2
Inherits System.Web.UI.Page
Dim cn As New SqlConnection
Dim cmd As New SqlCommand
Dim dr As SqlDataReader
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If (Page.IsPostBack = false) Then
cn = New SqlConnection("Data Source=nnn-PC;Initial Catalog=Faculty Housing;Persist Security Info=True;User ID=sa;Password=nnn;")
cn.Open()
Dim var As String
var = Session("S2").ToString()
TextBox1.Text = var
Session.Remove("S2")
cmd = New SqlCommand("select * from HouseDetails where OccupantName= '" & TextBox1.Text & "' ", cn)
dr = cmd.ExecuteReader
While (dr.Read)
Label1.Text = dr(1)
Label2.Text = dr(2)
Label3.Text = dr(3)
TextBox3.Text = dr(4)
DropDownList3.SelectedItem.Text = dr(5)
TextBox2.Text = dr(6)
TextBox4.Text = dr(7)
TextBox5.Text = dr(8)
DropDownList4.Text = dr(9)
End While
cn.Close()
End If
End Sub
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
cn = New SqlConnection("Data Source=nnn-PC;Initial Catalog=Faculty Housing;Persist Security Info=True;User ID=sa;Password=nnn;")
cn.Open()
Dim query As String = ("UPDATE HouseDetails SET OccupantName='" & TextBox1.Text & "' where HouseNum='" & Label3.Text & "'")
cmd = New SqlCommand(query, cn)
Dim x As Integer = cmd.ExecuteNonQuery()
cn.Close()
End Sub
Protected Sub TextBox1_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
End Sub
End Class

I fancy you're missing a check for IsPostBack to see whether or not this is a new request or a submission.
If (Not IsPostBack) Then
' populate for first load
End If

You have to put your code in IsPostback property.
Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.SessionState.HttpSessionState
Imports System.Drawing
Imports System.Drawing.Printing
Partial Class Default2
Inherits System.Web.UI.Page
Dim cn As New SqlConnection
Dim cmd As New SqlCommand
Dim dr As SqlDataReader
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If (!IsPostBack) Then
cn = New SqlConnection("Data Source=nnn-PC;Initial Catalog=Faculty Housing;Persist Security Info=True;User ID=sa;Password=nnn;")
cn.Open()
Dim var As String
var = Session("S2").ToString()
TextBox1.Text = var
Session.Remove("S2")
cmd = New SqlCommand("select * from HouseDetails where OccupantName= '" & TextBox1.Text & "' ", cn)
dr = cmd.ExecuteReader
While (dr.Read)
Label1.Text = dr(1)
Label2.Text = dr(2)
Label3.Text = dr(3)
TextBox3.Text = dr(4)
DropDownList3.SelectedItem.Text = dr(5)
TextBox2.Text = dr(6)
TextBox4.Text = dr(7)
TextBox5.Text = dr(8)
DropDownList4.Text = dr(9)
End While
cn.Close()
End If
End Sub
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
cn = New SqlConnection("Data Source=nnn-PC;Initial Catalog=Faculty Housing;Persist Security Info=True;User ID=sa;Password=nnn;")
cn.Open()
Dim query As String = ("UPDATE HouseDetails SET OccupantName='" & TextBox1.Text & "' where HouseNum='" & Label3.Text & "'")
cmd = New SqlCommand(query, cn)
Dim x As Integer = cmd.ExecuteNonQuery()
cn.Close()
End Sub
Protected Sub TextBox1_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
End Sub
End Class

Related

im creating a program that will automatically search when the textbox change and view it on datagrid but i have this error

'c:\users\gole\documents\visual studio 2010\Projects\WindowsApplication15\bin\Debug\Application.StartupPath & \data.accdb' is not a valid path. Make sure that the path name is specified
heres my code:
System.Data.OleDb
Public Class Form1
Dim con As New OleDbConnection
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source= Application.StartupPath & data.accdb"
End Sub
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
con.Open()
Dim dt As New DataTable
Dim ds As New DataSet
ds.Tables.Add(dt)
Dim da As New OleDbDataAdapter
da = New OleDbDataAdapter("Select * from student where ID like '%" & TextBox1.Text & "%'", con)
da.Fill(dt)
DataGridView1.DataSource = dt.DefaultView
con.Close()
End Sub
End Class
Change
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" _
& "Data Source= Application.StartupPath & data.accdb"
to
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" _
& Application.StartupPath & "\data.accdb"

Adding new object into ArrayList, currently it rewrites the last object

I am adding products to an ArrayList to display with a repeater
Protected Sub Add_Click(sender As Object, e As EventArgs) Handles Add.Click
Dim ProductID As Integer = ddProduct.SelectedValue
Dim Qty As Integer = QtyBox.Text
Dim TempProduct As OrderEntry = fillProduct(ProductID, Qty)
OrderList.Add(TempProduct)
Orders.DataSource = OrderList
Orders.DataBind()
End Sub
However, when I add a new object, it replaces the old one with a new, and I assume its because it references the old object, instead of creating a new one. Where do I create a new one?
Imports System.Data
Imports System.Data.SqlClient
Partial Class placeOrder
Inherits System.Web.UI.Page
Dim OrderList As New ArrayList
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not Page.IsPostBack() Then
dataFill()
End If
End Sub
Private Sub dataFill()
fillProduct()
End Sub
Private Sub fillProduct()
Dim conn As New SqlConnection(ConfigurationManager.ConnectionStrings("class_readonly").ConnectionString)
'Here bad connection string is a problem
conn.Open()
'Dim cmd As SqlCommand = conn.CreateCommand()
Dim sqlCmd As New SqlCommand()
With sqlCmd
.Connection = conn
.CommandText = "SELECT distinct ProductID, Name FROM dbo.Product;"
End With
Dim objDataAdapter As New SqlDataAdapter()
Dim objDataSet As New DataSet()
objDataAdapter.SelectCommand = sqlCmd
objDataAdapter.Fill(objDataSet)
ddProduct.DataSource = objDataSet.Tables(0)
ddProduct.DataBind()
End Sub
Protected Sub Add_Click(sender As Object, e As EventArgs) Handles Add.Click
Dim ProductID As Integer = ddProduct.SelectedValue
Dim Qty As Integer = QtyBox.Text
Dim TempProduct As OrderEntry = fillProduct(ProductID, Qty)
OrderList.Add(TempProduct)
Orders.DataSource = OrderList
Orders.DataBind()
dataFill()
End Sub
Private Function fillProduct(ByVal ProductID As Integer, ByVal Qty As Integer) As OrderEntry
Dim conn As New SqlConnection(ConfigurationManager.ConnectionStrings("class_readonly").ConnectionString)
'Here bad connection string is a problem
conn.Open()
'Dim cmd As SqlCommand = conn.CreateCommand()
Dim sqlCmd As New SqlCommand()
With sqlCmd
.Connection = conn
.CommandText = "SELECT * FROM dbo.Product WHERE ProductID=#ProductID ;"
.Parameters.Add(New SqlParameter("#ProductID", SqlDbType.Int, 4)).Value = ProductID
End With
Dim objDataAdapter As New SqlDataAdapter()
Dim objDataSet As New DataSet()
objDataAdapter.SelectCommand = sqlCmd
objDataAdapter.Fill(objDataSet)
Dim dtRow As DataRow = objDataSet.Tables(0).Rows(0)
Dim Total_Cost As Decimal = Decimal.Multiply(Qty, dtRow("Wholesale_Price"))
Dim Total_Price As Decimal = Decimal.Multiply(Qty, dtRow("Retail_Price"))
Dim Profit As Decimal = Total_Price - Total_Cost
Dim productInfo As New OrderEntry(dtRow("ProductID"), Qty, Total_Cost, Total_Price, Profit, dtRow("Name"))
sqlCmd.Dispose()
conn.Dispose()
Return productInfo
End Function
End Class
As #OneFineDay points out, if each element of your array is going to be of the same type then use an object of type "List Of" instead of "ArrayList".
This is how your class should look. You are saving your list to a session variable in Add_Click. In Page_Load, you are retrieving this session variable, casting it to a List(Of OrderEntry) and assigning it back to your page level list variable. Also I have removed the unnecessary dataFill procedure. Make sure that you understand the concepts rather than just copying and pasting.
Imports System.Data
Imports System.Data.SqlClient
Partial Class placeOrder
Inherits System.Web.UI.Page
Private m_myOrderList As List(Of OrderEntry)
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not Page.IsPostBack() Then fillProduct()
m_myOrderList = CType(Session("MyOrderList"), List(Of OrderEntry))
End Sub
Private Sub fillProduct()
Dim conn As New SqlConnection(ConfigurationManager.ConnectionStrings("class_readonly").ConnectionString)
'Here bad connection string is a problem
conn.Open()
'Dim cmd As SqlCommand = conn.CreateCommand()
Dim sqlCmd As New SqlCommand()
With sqlCmd
.Connection = conn
.CommandText = "SELECT distinct ProductID, Name FROM dbo.Product;"
End With
Dim objDataAdapter As New SqlDataAdapter()
Dim objDataSet As New DataSet()
objDataAdapter.SelectCommand = sqlCmd
objDataAdapter.Fill(objDataSet)
ddProduct.DataSource = objDataSet.Tables(0)
ddProduct.DataBind()
End Sub
Protected Sub Add_Click(sender As Object, e As EventArgs) Handles Add.Click
If IsNothing(m_myOrderList) = True Then m_myOrderList = New List(Of OrderEntry)
Dim ProductID As Integer = ddProduct.SelectedValue
Dim Qty As Integer = QtyBox.Text
Dim TempProduct As OrderEntry = fillProduct(ProductID, Qty)
m_myOrderList.Add(TempProduct)
Session("MyOrderList") = m_myOrderList
Orders.DataSource = m_myOrderList
Orders.DataBind()
End Sub
Private Function fillProduct(ByVal ProductID As Integer, ByVal Qty As Integer) As OrderEntry
Dim conn As New SqlConnection(ConfigurationManager.ConnectionStrings("class_readonly").ConnectionString)
'Here bad connection string is a problem
conn.Open()
'Dim cmd As SqlCommand = conn.CreateCommand()
Dim sqlCmd As New SqlCommand()
With sqlCmd
.Connection = conn
.CommandText = "SELECT * FROM dbo.Product WHERE ProductID=#ProductID ;"
.Parameters.Add(New SqlParameter("#ProductID", SqlDbType.Int, 4)).Value = ProductID
End With
Dim objDataAdapter As New SqlDataAdapter()
Dim objDataSet As New DataSet()
objDataAdapter.SelectCommand = sqlCmd
objDataAdapter.Fill(objDataSet)
Dim dtRow As DataRow = objDataSet.Tables(0).Rows(0)
Dim Total_Cost As Decimal = Decimal.Multiply(Qty, dtRow("Wholesale_Price"))
Dim Total_Price As Decimal = Decimal.Multiply(Qty, dtRow("Retail_Price"))
Dim Profit As Decimal = Total_Price - Total_Cost
Dim productInfo As New OrderEntry(dtRow("ProductID"), Qty, Total_Cost, Total_Price, Profit, dtRow("Name"))
sqlCmd.Dispose()
conn.Dispose()
Return productInfo
End Function
End Class
OK so it's an ASP.NET webpage. After you click on the button, it's posting the page back to the server. OrderList does not persist between calls and is reinitialised with each click. Try adding OrderList to a session variable as follows in your button click procedure :
OrderList.Add(TempProduct)
Session("OrderList") = OrderList
and in your page load event, insert:
OrderList = Session("OrderList")
Also your dataFill procedure is superfluous. Delete that procedure and replace calls to dataFill with fillProduct. It's not an error but it's untidy.

ASP.NET Downloading files from an SQL table

I'm trying to download a file from an SQL Server table. I am using a GridView. Whenever I try to download a file, I get a corrupted file.
I am using ASP.NET and VB.NET with SQL Server 2012 Express.
Any ideas why ?
Protected Sub GridView1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles GridView1.SelectedIndexChanged
Dim ContentID = Convert.ToInt32(GridView1.SelectedRow.Cells(1).Text)
Dim ContentName = GridView1.SelectedRow.Cells(2).Text
Dim ContentType = GridView1.SelectedRow.Cells(3).Text
lblContentName.Text = "[ " + ContentName + " ]"
lblContentName.Visible = True
End Sub
Protected Sub GridView1_RowCommand(sender As Object, e As GridViewCommandEventArgs)
Dim cn As New SqlConnection("Data Source=BRIAN-PC\SQLEXPRESS;Initial Catalog=master_db;Integrated Security=True;")
If e.CommandName = "Download" Then
Dim filename As String = String.Empty
Dim id As Integer = Convert.ToInt32(e.CommandArgument)
Dim cmd As New SqlCommand("SELECT content_name,content_type,content_data FROM content WHERE content_id = " & id, cn)
cn.Open()
Dim dr As SqlDataReader = cmd.ExecuteReader
Dim bytes As Byte()
dr = cmd.ExecuteReader()
If dr.Read() Then
filename = dr("content_name").ToString()
Response.ContentType = dr("content_type").ToString()
Response.AddHeader("Content-Disposition", "attachment;filename=" & filename)
bytes = DirectCast(dr("content_file"), Byte())
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.BinaryWrite(bytes)
Response.Flush()
Response.[End]()
End If
End If
End Sub
Private Sub BindGrid()
Dim constr As String = ConfigurationManager.ConnectionStrings("ConnStringDb1").ConnectionString
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand()
cmd.CommandText = "SELECT content_id, content_name FROM content"
cmd.Connection = con
con.Open()
GridView1.DataSource = cmd.ExecuteReader()
GridView1.DataBind()
con.Close()
End Using
End Using
End Sub
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not IsPostBack Then
BindGrid()
End If
End Sub

Unable to reflect changes in dataset or dataadapter on page reload

What is the problem in my this code?
The code is working fine but when i enter new record in table and refresh the page then the changes will not be reflected...
what was the problem iam confused..
Protected Sub Page_PreInit(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit
Dim ds As New DataSet()
Dim connStr As String = "Data Source=DOBRIYAL-PC;Initial Catalog=MenuDb;Integrated Security=True"
Using conn As New SqlConnection(connStr)
Dim sql As String = "Select MenuID, Text, Description, ParentID from Menu"
Dim da As New SqlDataAdapter(sql, conn)
da.Fill(ds)
da.Dispose()
da.AcceptChangesDuringFill = True
End Using
ds.DataSetName = "Menus"
ds.Tables(0).TableName = "Menu"
ds.GetChanges()
Dim relation As New DataRelation("ParentChild", ds.Tables("Menu").Columns("MenuID"), ds.Tables("Menu").Columns("ParentID"), True)
relation.Nested = True
ds.Relations.Add(relation)
XmlDataSource1.Data = ds.GetXml()
If Request.Params("Sel") IsNot Nothing Then
Page.Controls.Add(New System.Web.UI.LiteralControl("You selected " + Request.Params("Sel")))
End If
XmlDataSource1.DataBind()
RadMenu1.DataBind()
End Sub
I have refatored your source code now you should see your new records on page load
Private Sub BindData()
Dim ds As New DataSet()
Dim connStr As String = "Data Source=DOBRIYAL-PC;Initial Catalog=MenuDb;Integrated Security=True"
Using conn As New SqlConnection(connStr)
Dim sql As String = "Select MenuID, Text, Description, ParentID from Menu"
Dim da As New SqlDataAdapter(sql, conn)
da.Fill(ds)
da.Dispose()
da.AcceptChangesDuringFill = True
End Using
ds.DataSetName = "Menus"
ds.Tables(0).TableName = "Menu"
ds.GetChanges()
Dim relation As New DataRelation("ParentChild", ds.Tables("Menu").Columns("MenuID"), ds.Tables("Menu").Columns("ParentID"), True)
relation.Nested = True
ds.Relations.Add(relation)
XmlDataSource1.Data = ds.GetXml()
If Request.Params("Sel") IsNot Nothing Then
Page.Controls.Add(New System.Web.UI.LiteralControl("You selected " + Request.Params("Sel")))
End If
XmlDataSource1.DataBind()
RadMenu1.DataBind()
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Me.BindData()
End Sub

asp.net Check if the string from a textBox exist in my access table

This is the code I try
Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim ds As New DataSet
Dim strSQL As String = "SELECT * FROM Client WHERE UserName = '" & TextBox1.Text & "'"
Dim da As New OleDbDataAdapter(strSQL, con)
Try
con.Open()
Dim builder As New OleDbCommandBuilder(da)
da.Fill(da)
If ds.Tables.Count > 0 Then
MsgBox("exist")
Else
MsgBox("not exist")
End If
con.Close()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
The ds.table.count its every time = 1 whatever the TextBox1.Text.
Thanks for helping me to Check if the string from a textBox exist in my access table.

Resources