Dataset is NULL after clicking form button.
I want to learn and understand Visual Basic 2017.
On a test webform some textboxes are filled with dataset (DS) items (during pageload).
This works well without problems .
There is also a SAVE button on the form that must fill a textbox with a dataset item after clicking.
But then the dataaet appears to be to be NULL.
How is that possible?
I hope someone can tell me what is wrong, I understood thata dataset stays dukkws while running.
Aftr clicking the SAVEbutton this error appears: ==========================================
System.NullReferenceException: Object reference not set to an instance of an object.
at NW_DB_update_test.NWtest.testDS() in S:\P2 S VS tests\NW DB
update test\NW DB update test\NWtest.aspx.vb:line 46
Thw VB soutce is ==================================
Option Explicit On
Option Strict On
Imports System.Data.SqlClient
Public Class NWtest
Inherits System.Web.UI.Page
Public DA As SqlDataAdapter
Public DS As System.Data.DataSet
Public CB As SqlCommandBuilder
Public Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
Call GETNWDS()
Call testDS()
End If
End Sub
Public Sub GETNWDS()
'' opencustumorDataAdapterdaaset DS
Dim connectionString = ConfigurationManager.ConnectionStrings("NW testConnectionString").ConnectionString
Dim queryString As String = "SELECT CustomerID, CompanyName, ContactName FROM Customers where CustomerID='ALFKI'"
Dim conn As New SqlConnection(connectionString)
DA = New SqlDataAdapter(queryString, conn)
DS = New System.Data.DataSet
DA.Fill(DS)
CustomerIDbox.Text = DS.Tables(0).Rows(0).Item("CustomerID").ToString
CompanyNamebox.Text = DS.Tables(0).Rows(0).Item("CompanyName").ToString
ContactNamebox.Text = DS.Tables(0).Rows(0).Item("ContactName").ToString
End Sub
Public Sub testDS()
Try
Dim v As String
v = "in DS= " + DS.Tables(0).Rows(0).Item("ContactName").ToString
Textbox.Text = v
'Error after clicking the save button:
' System.NullReferenceException
' Object reference Not set to an instance of an object.
' at NW_DB_update_test.NWtest.testDS() in S: \P2 S VS tests\NW DB update test\NW DB update test\NWtest.aspx.vb:line 46
Catch x As Exception
Textbox.Text = x.ToString
End Try
End Sub
End Class
========================================================================================
I am not sure what you are trying to achieve, but as ADyson explained, the variables you have declared on page load are non-existent after the postback. On the other hand, if you just want to read the ContactName, you can get it directly from the textbox it was written to, as controls do persist between postbacks, if not otherwise stated.
Textbox.Text=ContactNamebox.Text
Related
I'm trying to do display multiple rows with two column values on a list box so when a user selects an option they have a little extra information.
It should look like this:
ej. 3 BestBuy
I use the same method to output data to my GridViews but it doesn't display anything on the listbox. What is the correct method to output data from a db to a listbox.
SQL Control Class Functions
Public Function ExecQuery(query As String) As DataTable
Dim DBDT = New DataTable
Using DBCon As New SqlConnection(ConStr),
DBCmd As New SqlCommand(query, DBCon)
Params.ForEach(Sub(p) DBCmd.Parameters.Add(p))
Params.Clear()
DBCon.Open()
DBDT.Load(DBCmd.ExecuteReader)
End Using
Return DBDT
End Function
'Add Params
Public Sub AddParam(Name As String, Value As Object)
Dim NewParam As New SqlParameter(Name, Value)
Params.Add(NewParam)
End Sub
How im trying to add data to the listbox
Protected Sub DivisionListBox_DataBinding(sender As Object, e As EventArgs) Handles DivisionListBox.DataBinding
Try
dt = SQL.ExecQuery("Select STR_GRP_ID, GROUP_DESC
FROM Store_Group_Desc ")
Catch ex As Exception
MsgBox(ex.Message)
Exit Sub
End Try
DivisionListBox.DataSource = dt
DivisionListBox.DataBind()
End Sub
What I would do is return the STR_GRP_ID as well as create an aliased column that concatenated the STR_GRP_ID and GROUP_DESC fields.
Then you would bind the DataTable to the ListBox like you're doing but specifying that the ListBox's DisplayMember is your aliased column and the ValueMember is the id:
Try
dt = SQL.ExecQuery("Select STR_GRP_ID, CONCAT_WS(' ', STR_GRP_ID, GROUP_DESC GROUP_DESC) AS DisplayText FROM Store_Group_Desc;")
Catch ex As Exception
MessageBox.Show(ex.Message)
Return
End Try
With DivisionListBox
.DataSource = dt
.DisplayMember = "DisplayText"
.ValueMember = "STR_GRP_ID"
End With
I don't think the DataBinding event will ever be triggered in you code. You can set a break point inside the event and see if it is ever triggered.
I chose to use the Page.Load event to fill the list box. I separated the user interface code that actually fills the list box from the data access code.
I had the server do the work to build the string your want to display. I assumed the id field was some type of number field so I cast it to a varchar. Then added a space and the description field. This new select field is called IDDesc.
IDDesc is the field name that I want to display in the list box.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not IsPostBack Then
FillListBox()
End If
End Sub
Private Sub FillListBox()
Dim ListBoxData = GetListBoxData()
ListBox1.DataTextField = "IDDesc"
ListBox1.DataSource = ListBoxData
ListBox1.DataBind()
End Sub
Private Function GetListBoxData() As DataTable
Dim DBDT = New DataTable
Dim Query = "Select Cast(STR_GRP_ID As varchar) + ' ' + GROUP_DESC As IDDesc
FROM Store_Group_Desc "
Using DBCon As New SqlConnection(ConStr),
DBCmd As New SqlCommand(Query, DBCon)
DBCon.Open()
DBDT.Load(DBCmd.ExecuteReader)
End Using
Return DBDT
End Function
My new application page is getting a timeout error every hour or so after getting some traffic on the page, and by traffic I mean users submitting 5-10 applications. How do I find the cause of the connections getting tied up?
This has been an issue in the past so whenever I use a sql data reader object I make sure to implement the "Using" statement. I've also made sure that the thread isn't aborted before the data reader is disposed of. I doubt that my use of data readers is the issue, so maybe it's my non-query code that's causing the issue, but I can't see why.
I also use a few sqldatasource objects for my dropdownlist controls, and as far as I know it wouldn't be the source of my issue.
See code example for how I use my sql objects.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Using drApp As SqlDataReader = LookupAppByID()
'some code
drApp.Close()
End Using
End Sub
Public Function LookupAppByID() As SqlDataReader
Dim Command As New SqlClient.SqlCommand
Command.Connection = GetDBConnection()
Command.CommandType = CommandType.Text
Command.CommandText = "select statement"
Return Command.ExecuteReader(CommandBehavior.CloseConnection)
End Function
Public Function UpdateAppStatus() As Integer
UpdateAppStatus = 0
Using Command As New SqlClient.SqlCommand("update statement", GetDBConnection())
UpdateAppStatus = Command.ExecuteNonQuery()
Command.Connection.Close()
Command.Connection.Dispose()
Command.Dispose()
End Using
End Function
Public Function GetDBConnection() As SqlClient.SqlConnection
Dim connection As New SqlClient.SqlConnection
connection.ConnectionString = "connection string"
connection.Open()
Return connection
End Function
Obviously I expect it to chug along without a hitch but when users start hitting the page it gets this error: Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.
Is there a problem with my code?
How can I narrow down what is causing this issue?
I would keep the database objects local so I can ensure that they are closed and disposed. Create and dispose within one method. I created a class so you can easily pass all its properties in a single variable.
'User Interface Code
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Dim id As Integer 'No sure where the value comes from
Using dtApp As DataTable = DataAccess.LookupAppByID(id)
'some code
End Using
End Sub
Protected Sub Update_Click(sender As Object, e As EventArgs) Handles Update.Click
Dim Applic As New ApplicationData()
Applic.ApplicantsName = txtName.Text
Applic.ID = CInt(txtID.Tex)
Applic.ApplicationStatus = "Approved"
Dim retVal = DataAccess.UpdateAppStatus(Applic)
If retVal = 1 Then
'Alert user of success
Else
'Alert user of failure
End If
End Sub
Public Class ApplicationData
Public Property ID As Integer
Public Property AppDate As Date
Public Property ApplicantsName As String
Public Property ApplicationStatus As String
End Class
Public Class DataAccess
Private Shared ConString As String = "Your connection string"
Public Shared Function LookupAppByID(AppID As Integer) As DataTable
Dim dt As New DataTable
Using cn As New SqlConnection(ConString)
Using Command As New SqlCommand("select * From YourTable Where ID = #ID", cn)
Command.Parameters.Add("#ID", SqlDbType.Int).Value = AppID
cn.Open()
dt.Load(Command.ExecuteReader)
End Using
End Using
Return dt
End Function
Public Shared Function UpdateAppStatus(App As ApplicationData) As Integer
Dim AppStatus = 0
Using cn As New SqlConnection(ConString)
Using Command As New SqlClient.SqlCommand("Update YourTable Set Status = #Status Where ID = #ID;", cn)
Command.Parameters.Add("#Status", SqlDbType.VarChar, 50).Value = App.ApplicationStatus
Command.Parameters.Add("#ID", SqlDbType.Int).Value = App.ID
cn.Open()
AppStatus = Command.ExecuteNonQuery()
End Using
End Using
Return AppStatus
End Function
End Class
I worked on a VB.NET project and I have a problem in how to connect between tables.
I have access database [database1]
tables : T1 , RequestDetails
T1: U_ID Name Address Phone
RequestDetails: U_ID RqNo Requestport country_of_request RqMethod
On first page, the user should enter his information Name Address Phone. When a buttom is clicked, this data is inserts into the database and navigates to the second page.
On the second page, the user should complete entering his data based on the U_ID
I have 3 dropdownlists: Requestport, country_of_request, and RqMethod
Andd also when a button is clicked, it should insert data and go next.
Everything's ok; I worked on each page in separate. Now I want to make connection between U_ID in T1 and RequestDetails to make data connected from page 1 and page 2.
I don't know how to explain problem I hope every thing was clear.
My code for page 1 :
I build connection class to do connection staff
Imports System.Data
Imports System.Data.OleDb
Imports System
Public Class connection
Dim str As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\hp\Documents\Visual Studio 2010\Projects\WebApplication1\WebApplication1\bin\Database1.accdb"
Dim con As New OleDbConnection(str)
Public Sub Insert(ByVal Name As String, ByVal Address As String, ByVal Phone As String)
If con.State = ConnectionState.Closed Then
con.Open()
End If
Dim adp As New OleDbCommand("insert into T1 values(" & GetMaxID() & ",'" & Name & "','" & Address & "','" & Phone & "') ", con)
adp.ExecuteNonQuery()
con.Close()
End Sub
Public Function GetMaxID() As Integer
Dim x As Integer = 1
If con.State = ConnectionState.Closed Then
con.Open()
End If
Dim adp As New OleDbCommand("select max(ID) from T1", con)
Try
x = adp.ExecuteScalar
Return x + 1
Catch ex As Exception
Return x
End Try
End Function
End Class
Then in the button :
Public Class _Default
Inherits System.Web.UI.Page
Dim x As New connection
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
x.Insert(TextBox1.Text, TextBox2.Text, TextBox3.Text)
Response.Redirect("~/ReqDetails.aspx")
End Sub
End Class
There is no problem here.
In the second page in the button:
Imports System.Data
Imports System.Data.OleDb
Imports System
Public Class shipmentDetails
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
Dim str As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\hp\Documents\Visual Studio 2010\Projects\WebApplication1\WebApplication1\bin\Database1.accdb"
Dim con As New OleDbConnection(str)
con.Open()
Dim Command As New OleDbCommand("INSERT INTO RequestDetails( Requestport," & "country_of_request," & "RqMethod,")VALUES(#Requestport,#country_of_request,#RqMethod)", con)"
Command.Parameters.Add(New OleDbParameter("#Requestport", Requestport.SelectedItem.Text))
Command.Parameters.Add(New OleDbParameter("#country_of_request", country_of_request.SelectedItem.Text))
Command.Parameters.Add(New OleDbParameter("#RqMethod", RqMethod.SelectedItem.Text))
)
Command.ExecuteNonQuery()
con.Close()
Label1.Text = "Thank You. Your transaction was successful."
Label1.Visible = True
End Sub
End Class
Here is the problem:
If I fill the data and click next it shows me an error because U_Id not fill and it should not null
That means it should read u_id from the page 1...How can I do it?
This looks like VB.NET code within an ASP project. If that's the case, I'd ask you to at least put that in the tags, but you can also use POST to send the U_ID to page two.
If this is a pure VB.NET application opening a second window you should be able to make the second window a child of the parent, make a global public variable called U_ID and be able to call parent.U_ID (Parent should ideally be the name of your original form.). I think ideally you can use the parent call in ASP as well, but I've never tried it myself.
I would have actually asked for some clarification, but I can't seem to do that just yet. If you'd care to confirm which of the two it actually is then I could edit in a little sample code if you need.
EDIT:
Here is something considerably easier than the HTTP Post methodology. For reference, read The msdn article.
Create the following in the main form.
Public ReadOnly Property U_ID() As Integer
Get
Return ID
End Get
End Property
Then append your one function like this (It's about the easiest way I can figure this to work:
Public ID as Integer
Public Function GetMaxID() As Integer
Dim x As Integer = 1
If con.State = ConnectionState.Closed Then
con.Open()
End If
Dim adp As New OleDbCommand("select max(ID) from T1", con)
Try
x = adp.ExecuteScalar
ID=x+1
Return x + 1
Catch ex As Exception
Return x
End Try
End Function
Now you have a public variable your second page can read like this:
<%# PreviousPageType VirtualPath="~/SourcePage.aspx" %>
Public U_ID as Integer = PreviousPage.U_ID
Try that. You should be able to access the previous page's U_ID.
I have created a form to update an access DB table. My issue is that when the text in the text boxes is changed and the form is submitted, the .text values stay the same as they were when the datareader loaded them on the page load event. How can I submit the values that the user updates, not what is already there from page load.
Code:
Public Property vehicleid As Integer
Public Property connstring As String = "myconnectionstring..."
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
vehicleid = Integer.Parse(Request.QueryString("vehicID"))
Dim svEnterdate, stocknum, make, model, color As String
Dim conn As New OleDbConnection(connstring)
Dim sql As String = "select * from vehicle where vehicleid=#vid"
Dim cmd As New OleDbCommand(sql, conn)
cmd.Parameters.AddWithValue("#vid", vehicleid)
conn.Open()
Dim dr As OleDbDataReader = cmd.ExecuteReader
While dr.Read
svEnterdate = dr("enterdate").ToString()
stocknum = dr("stock_num").ToString()
make = dr("make").ToString()
model = dr("model").ToString()
color = dr("color").ToString()
End While
conn.Close()
EnterDateTXT.Text = svEnterdate
StockNumTXT.Text = stocknum
MakeTxt.Text = make
ModelTXT.Text = model
ColorTxt.Text = color
End Sub
'inbetween these 2 events the user can manipulate all the controls .text values, yet the
' .text values of the submitted controls below are the same as the ones filled by the
'datareader
Protected Sub SubmitBTN_Click(ByVal sender As Object, ByVal e As EventArgs) Handles SubmitBTN.Click
Dim conn As New OleDbConnection(connstring)
Dim sql As String = "UPDATE Vehicle" & _
" SET stock_num=#stock, make=#make, model=#model, color=#color, enterdate=#enter " & _
"WHERE vehicleid=#vid"
Dim cmd As New OleDbCommand(sql, conn)
cmd.Parameters.AddWithValue("#vid", vehicleid)
cmd.Parameters.AddWithValue("#stock", StockNumTXT.Text)
cmd.Parameters.AddWithValue("#make", MakeTxt.Text)
cmd.Parameters.AddWithValue("#model", ModelTXT.Text)
cmd.Parameters.AddWithValue("#color", ColorTxt.Text)
cmd.Parameters.AddWithValue("#enter", EnterDateTXT.Text)
conn.Open()
cmd.ExecuteNonQuery()
conn.Close()
End Sub
In your page load code, Check For Post back
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
' Write your code to read data from database here
End
End Sub
If you dont check for postback in your page load event, Everytime when you click the submit button, It is going to excute the code in your page load ( load the content again to the text box) first. So whatever you entered in the textbox will be overwritten by the content form the database and that will be saved back again to the database.
To undestand this. Put a breakpoint in your Page_load event code and another in your button click event code. Now enter some value in textbox and click the button and see whether your code block in pageload is executing or not.
Checking the Postback check in your page_load will fix the problem.
http://msdn.microsoft.com/en-us/library/system.web.ui.page.ispostback.aspx
This task is a little out of my reach so i dont even really know where to start...
I want a user to click the command field "select" in my gridview. I then want them to be redirected ( response.redirect()) to an input form that will have its various asp.net text boxes filled with data from that selected item.
I also need the ability to do this logical process:
IF the form is loaded from user
selecting item in gridview THEN
''Populate controls with data from selected gridview item Else Load
form as normal and have the controls
blank endif
I was suggested to use this command for the redirect load...Not sure if its correct:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If InStr(Request.ServerVariables("HTTP_REFERER"), "LogViewer.aspx") Then
'FILL the text boxes with the data from data source!
End If
End Sub
+++++++++++++++++++++++++++++++++++++++++++++++++++++++
EDIT
I got it working thanks to A Tuliper...now how can i get my drop down list to select the correct item based on the data in the gridview??
Private Sub getData(ByVal user As String)
Dim dt As New DataTable()
Dim connection As New SqlConnection("My Connection ")
connection.Open()
Dim sqlCmd As New SqlCommand("SELECT * from AppMaster WHERE RecNum = #recnum", connection)
Dim sqlDa As New SqlDataAdapter(sqlCmd)
sqlCmd.Parameters.AddWithValue("#recnum", user)
sqlDa.Fill(dt)
If dt.Rows.Count > 0 Then
NameTxt.Text = dt.Rows(0)("UserName").ToString()
'''''''''this drop down list needs to be the correct item'''''''''''''''''
'AppDropDownList.SelectedValue = dt.Rows("Application").ToString()
SelectedDateTxt.Text = dt.Rows(0)("DateOfChange").ToString()
DescriptionTxt.Text = dt.Rows(0)("Description").ToString()
SnipetTxt.Text = dt.Rows(0)("Snippet").ToString()
End If
connection.Close()
End Sub
The easiest unhacky method here is to simply create a link in your gridview with the parameters in the URL going to say:
Details
And then in your second page read them:
string param1 = Request.QueryString["Param1"]; //or whatever its called - change it of course