I am basically creating textboxes dynamically for adding a test to the database. The number of textboxes to be created was passed as a query string from the web page before. Here is the code:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim NoOfQuestions As Integer = Request.QueryString("NoOfQuestions")
Dim txtboxQ(NoOfQuestions - 1) As TextBox
Dim txtboxA(NoOfQuestions - 1) As TextBox
For i = 1 To NoOfQuestions
Placeholder.Controls.Add(New LiteralControl("<span>Question " & i & "</span>"))
Placeholder.Controls.Add(txtboxQ(i - 1))
Placeholder.Controls.Add(New LiteralControl("</br>"))
Placeholder.Controls.Add(New LiteralControl("<span>Correct Answer</span>"))
Placeholder.Controls.Add(txtboxA(i - 1))
Placeholder.Controls.Add(New LiteralControl("</br>"))
Next
End Sub
Protected Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
'Some SQL stuff
Response.Redirect("HomePage.aspx")
End Sub
I am trying to pass both the textbox arrays that were declared in Page_Load to the other sub btnSubmit_Click. I tried to pass it as parameter like this but it didn't seem to work:
Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As EventArgs, ByRef txtboxQ() As TextBox, ByRef txtboxA As TextBox) Handles btnSubmit.Click
'Some SQL stuff
Response.Redirect("HomePage.aspx")
End Sub
Quiet lost here, thanks for your help!
You can pass the textboxes content as output parameters in the querystring, as you did with your input parameter NoOfQuestions
Dim sQuery As String
For i = 1 To NoOfQuestions
sQuery &= "Question" & i & " & txtboxQ(i - 1).Text & "Answer" & i & "=" & txtboxA(i - 1).Text
Next i
Response.Redirect("HomePage.aspx?" & sQuery)
And the parse the query string in the Page Load event of HomePage.aspx. You can also pass the values as session variables
Session("Question1") = txtboxQ(i - 1).Text
...
And then
Dim question1 As String = Session("Question1")
....
Declare a list of text boxes on page level
Public textQ = New List(Of TextBox)
Public textA = New List(Of TextBox)
Change your code to following
For i = 1 To NoOfQuestions
Placeholder.Controls.Add(New LiteralControl("<span>Question " & i & "</span>"))
Dim txtboxq = New TextBox()
txtboxq.ID = "txtq_" & i
Placeholder.Controls.Add(txtboxq)
textQ.Add(txtboxq)
Placeholder.Controls.Add(New LiteralControl("</br>"))
Placeholder.Controls.Add(New LiteralControl("<span>Correct Answer</span>"))
Dim txtboxa = New TextBox()
txtboxa.ID = "txta_" & i
Placeholder.Controls.Add(txtboxa)
textA.Add(txtboxa)
Placeholder.Controls.Add(txtboxa)
Placeholder.Controls.Add(New LiteralControl("</br>"))
Next
then access the values in the list for any purpose, may be print values on submit or whatever..
eg:
For Each tb As TextBox In Me.textQ
Me.label1.Text = Me.label1.Text & tb.Text.Trim()
Next
Wondering why would you want to pass the variables like that when you can declare the variables in page level and access it from any method/function. Any special requirement?
what you are trying to do here is unclear as well.
You can use global variable inside you class, and place it below your class code. And if you want to use it, you just call that global variable.
Related
i had created a text box control array using the following code, where the no.of controls are generated on the basics of the value selected from the combo box
Protected Sub DropDownList1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DropDownList1.SelectedIndexChanged
Dim lstTextBox = New List(Of TextBox)()
For i As Integer = 0 To DropDownList1.SelectedValue
for j as integer =0 to 3
Dim txtbx As New TextBox()
txtbx.ID = String.Format("txtbx{0}", j)
lstTextBox.Add(txtbx)
txtbx.Text = "sample text " & j
form1.Controls.Add(txtbx)
next
Next
Session("lstTextBox") = lstTextBox
End Sub
now i need to insert the value to the database on a single button click, here the code is
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
dim mysql as string
mysql="insert into mytable values("
Dim lstText = New List(Of TextBox)()
lstText = Session("lstTextBox")
For i As Integer = 0 To lstText.Count - 1
for j as integer =0 to 3
mysql= mysql & "'" & trim(lstText(j).Text) & "',"
next
'execute insert for each row with the mysql string
Next
End Sub
now the problem is: only the initial values in the text boxes are inserted to the database, the changes which i had made in the text boxes are not inserted to the database. ie, in session the initial values will not change on text change in the text box.
i need a solution for this problem for proceeding my work. so expert's kind attention please.. positive responses will be appreciated.
Am not sure about VB and as well as My Sql. But i can give you a some way to get rid off from Session
Try like this in DropDownList1_SelectedIndexChanged,
if(Session("lstTextBox"))==null
Session("lstTextBox") = lstTextBox
else
Session.Abandon()
Session("lstTextBox") = lstTextBox
Now you go can check whether session is updating or not. As well as you may get the result as you want. Please let me know the output.
I want to get the value of my textbox that I created dynamically when I click a button
I need to do this cause the value of my textbox is used for retrieve data from database
how could I achieved this thing??
the flow is Button click - creating textbox - filling textbox with value - Button Click - Get Text of textbox
here is my code to make the textbox
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
For i As Integer = 0 To 4
textbox = New TextBox With {.ID = "TextBox" & i}
plchld.Controls.Add(textbox)
Next
End Sub
I have tried something like this but the code didn't work
Protected Sub OkButton_Click(sender As Object, e As EventArgs) Handles OkButton.Click
Dim a(5) As String
For i As Integer = 0 To 4
a(i) = CType(plchld.FindControl("Textbox" & i), TextBox).Text
Next
End Sub
thanks in advance for any help
edit for the answer
I've found the way to solve this. I use request.form to get the value of my textbox.
Thanks for anyone that participating
Regards,
Julian
This is how I have done in my asp.net application.
Creating dynamic control
TextBox txtDate = new TextBox();
txtDate.EnableViewState = true;
txtDate.ID = "PreixValue" + 1;
txtDate.Text = "07 Feb 2014"
pnl.controls.add(txtdate);
To retrieve the value from that textbox
DateTime datefrom = DateTime.Now ;
for (int cnt = 0; cnt < Request.Form.Count; cnt++)
{
if (Request.Form.AllKeys[cnt].Contains("Prefixvalue"))
{
int ParamStartPoint = Request.Form.AllKeys[cnt].IndexOf("Prefix") + 4;
int ParamNameLength = Request.Form.AllKeys[cnt].Length - ParamStartPoint;
string[] ControlName = Request.Form.AllKeys[cnt].Substring(ParamStartPoint, ParamNameLength).Split('$');
if (ControlName[0] == "Date From")
{
datefrom = DateTime.Parse(Request.Form[cnt]);
//datefrom has value now
}
}
}
This is how I have done in my web application, but there may be other ways achieve this.
basically when you create Dynamic control in webform this will be available through Request.Form.
hope this helps you.
Protected Sub OkButton_Click(sender As Object, e As EventArgs) Handles OkButton.Click
Dim a(5) As String
For i As Integer = 0 To 4
Dim anotherObj As TextBox = Me.Controls.Item("Textbox" & i)
a(i) =anotherObj.Text
Next
The issue is that dynamic controls are lost on a postback so when the OkButton click event is handled, there is nothing inside your plchld control. You must recreate your controls with the same ID on postback if you want to retrieve the text in the textboxes.
Using your code, all you need to do is on postback determine if the textboxes were created and if so, recreate them.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
' Determine if the text boxes were created and if so, recreate them.
If CBool(ViewState("TextBoxesCreated")) Then
CreateTextBoxes()
End If
End Sub
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
CreateTextBoxes()
ViewState("TextBoxesCreated") = True
End Sub
Private Sub CreateTextBoxes()
For i As Integer = 0 To 4
plchld.Controls.Add(New TextBox With {.ID = "TextBox" & i})
Next
End Sub
Protected Sub OkButton_Click(ByVal sender As Object, ByVal e As EventArgs) Handles OkButton.Click
Dim a(4) As String
For i As Integer = 0 To 4
a(i) = CType(plchld.FindControl("Textbox" & i), TextBox).Text
Next
End Sub
I don't know the full extent of what you are doing but I would suggest not creating them dynamically if you don't need to. Just show or hide the textboxes instead.
Reference: http://www.codeproject.com/Articles/3684/Retaining-State-for-Dynamically-Created-Controls-i
I am a total beginner at VB.NET so you may need to bear with me but I need to edit this code behind so that a null value is passed to my database for the 'imageurl' field. The front end is a web form where a user can enter details of a book, with the option of uploading a book cover.
I want to change my code so that if the file upload dialog does not fulfil hasFile, the GUID string generated in the database will be a NULL value (this is so I can have a 'no image available' image using the NullImageUrl property in ASP.)
This is what I've tried to implement so far, but intellisense is telling me that "Value of type String cannot be converted to 'System.GUID'.
Code Behind:
Imports System.Data.OleDb
Partial Public Class addBook
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 btn_submission_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btn_submission.Click
Dim noFile As String = Nothing
Dim myGUID = Guid.NewGuid()
Dim newFileName As String = myGUID.ToString() & ".jpg"
Dim fileLocationOnServerHardDisk = Request.MapPath("img/thumb") & "/" & newFileName
If fu_picture.HasFile Then
fu_picture.SaveAs(fileLocationOnServerHardDisk)
Else
myGUID = noFile
End If
Dim oleDbConn As New OleDb.OleDbConnection(ConfigurationManager.ConnectionStrings("BookMeetConnString").ConnectionString)
Dim SqlString As String = "Insert into booklist(Title,Author,PublicationDate,Pages,Publisher,Blurb,imgurl,AverageRating)
Values (#f1,#f2,#f3,#f4,#f5,#f6,#f7,#f8)"
Dim cmd As OleDbCommand = New OleDbCommand(SqlString, oleDbConn)
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("#f1", tb_booktitle.Text)
cmd.Parameters.AddWithValue("#f2", tb_bookauthor.Text)
cmd.Parameters.AddWithValue("#f3", tb_bookpubyear.Text)
cmd.Parameters.AddWithValue("#f4", tb_bookpages.Text)
cmd.Parameters.AddWithValue("#f5", tb_publisher.Text)
cmd.Parameters.AddWithValue("#f6", tb_blurb.Text)
cmd.Parameters.AddWithValue("#f7", "img/thumb/" & newFileName)
cmd.Parameters.AddWithValue("#f8", rbl_Stars.SelectedValue)
oleDbConn.Open()
cmd.ExecuteNonQuery()
System.Threading.Thread.Sleep("2000")
Response.Redirect("~/addedrecord.aspx")
End Sub
Protected Sub rbl_Stars_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles rbl_Stars.SelectedIndexChanged
End Sub
End Class
Please tell me if I'm completely wrong in my line of thinking!
EDIT: At this present moment, even if a file is not uploaded, a guid string + jpg suffix are generated in the database table even if the image itself doesn't exist
You should pass DBNull.Value to your db if you fail the requirement
cmd.Parameters.AddWithValue("#f7", _
if(fu_picture.HasFile, "img/thumb/" & newFileName, DbNull.Value)
The ternary operator allows you to test the flag HasFile just when you create the parameter.
If it is false you set the parameter value to DBNull.Value. If HasFile is true you can build the correct path to your imagefile. Of course this removes the necessity to assign Nothing to myGuid in the code before.
I have a CheckBoxList on my page that isn't behaving very well.
The idea is that once the submit button on the form is clicked, the app should clear the database table of all rows pertaining to the specific user and then re-insert new ones based on the user's CheckBoxList selections.
The problem is that regardless of whether or not any (or all) items in the CheckBoxList are selected, the app keeps getting Selected = False.
Here's my code:
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
loadRegions()
End Sub
Private Sub loadRegions()
Dim db As New Database
Dim sql As String = "select * from regions"
Dim dr As MySqlDataReader = db.execDB(sql, "Text", Nothing, "DataReader", False)
If dr.HasRows Then
cblRegion.DataSource = dr
cblRegion.DataTextField = "regionname"
cblRegion.DataValueField = "regionid"
cblRegion.DataBind()
End If
dr.Close()
End Sub
Protected Sub btnRegister_Click(sender As Object, e As System.EventArgs) Handles btnRegister.Click
' ============================================================
' There's more code in here, but it's irrelevant to this paste
' ============================================================
Dim sql As String = "delete from userregions where userid = " & lblUserID.Text & ";"
For i As Integer = 0 To cblRegion.Items.Count - 1
If cblRegion.Items(i).Selected Then
sql &= "insert into userregions (userid, regionid)" & _
"values(" & UserID & ", " & cblRegion.Items(i).Value & ")"
db.execDB(sql, "Text", Nothing, "None", False)
End If
Next
End Sub
For the record
I'm aware of the potential for SQL Injection here. I'll be going over to using Parameters as soon as I have the loop working.
Thanks for your time.
Any help will be greatly appreciated.
You only need to call loadRegions on the initial load and not on postbacks:
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
loadRegions()
End If
End Sub
Otherwise you'll lose changed values and events are not triggered.
Add this line of copde "If IsPostBack Then Return" in Page_Load method.
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
If IsPostBack Then Return
loadRegions()
End Sub
In page loaded, write the following:
If Not IsPostBack
loadRegions()
End If
I'm trying to sort records in the gridview right after a radio button is selected. My approach is with the dataview, but because the dataset variable doesn't survive a round trip to the server, I don't know how to make this happen. please help!
Public Sub GetCustomers()
db.RunProcedure("usp_customers_get_all")
db.doSort(radList.SelectedValue)
gvCustomers.DataSource = db.MyView
End Sub
Protected Sub radList_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles radList.SelectedIndexChanged
If radList.SelectedValue = 0 Then
db.doSort(0)
gvCustomers.DataSource = db.MyView
End If
If radList.SelectedValue = 1 Then
db.doSort(1)
gvCustomers.DataSource = db.MyView
End If
End Sub
Public Sub doSort(ByVal strIn As Integer)
If strIn = 0 Then
MyView.Sort = "lastname, firstname"
Else
MyView.Sort = "username"
End If
End Sub
Public Sub RunProcedure(ByVal strName As String)
Dim objConnection As New SqlConnection(mstrConnection)
Dim mdbDataAdapter As New SqlDataAdapter(strName, objConnection)
Try
mdbDataAdapter.SelectCommand.CommandType = CommandType.StoredProcedure
Me.mDataset.Clear()
mdbDataAdapter.Fill(mDataset, "tblCustomers")
MyView.Table = mDataset.Tables("tblCustomers")
Catch ex As Exception
Throw New Exception("stored procedure is " & strName.ToString & " error is " & ex.Message)
End Try
End Sub
You could store the dataset in one of the following places and then when the post back happens just load it again from there. I have done many of these on a corporate intranet.
Session Variable
ViewState
QueryString
Cache
I cant really provide more help as you didn't specify if this is done in Ajax or if you do a full postback etc. If you provide more info I would love to help you.