Insert text from dynamic text boxes to database - asp.net

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.

Related

trying get total from grid view textbox

i want to get value from grid view text box in Text Change Event but error comes
Object refrence is not set of an instance of an Object
Protected Sub onDebitChange(ByVal sender As Object, ByVal e As EventArgs)
Dim a, b As Integer
With GridView3
Dim rows As Integer = .Rows.Count
For i As Integer = 0 To rows - 1
Dim txtDebit As TextBox = CType(GridView3.Rows(i).FindControl("TotalDebit"), TextBox)
a = Val(txtDebit.Text)
b += a
Next
DebitBalance.Text = b
End With
End Sub
i also had tried for each loop but error is same
please help
You need to put the name of the ItemTemplate control correctly, in onDebitChange method please fix the control name to "Debit" not "TotalDebit" only:
Dim txtDebit As TextBox = CType(GridView3.Rows(i).FindControl("Debit"), TextBox)
Hope this helps.

How to pass variables between 2 procedures in VB.NET (Web Application)

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.

how to get the text value of dynamically created textbox

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

asp.net vb.net gridview, get row id when pressing template field button

I have a template field with a button. I want to press the button and get the row Id so I can return the users selection. I have a regular select button which works fine but the user want the people who are not employee’s to hide the select button. I have this working but since it’s a template field it fires the RoW_command procedure and I cannot seem to get the row index since it is a template field and not the regular Select button. Or I cannot seem to name the Regular select button since it Command field does not have a Name or ID property?
Like I said this works hiding the template field called btnSelect
Private Sub GridView3_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView3.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
If (DataBinder.Eval(e.Row.DataItem, "LegacyPersonType") <> "Employee") Then
e.Row.ForeColor = Drawing.Color.Black
e.Row.BackColor = Drawing.Color.Yellow ' This will make row back color yellow
e.Row.FindControl("btnSelect").Visible = False
Else
e.Row.ForeColor = Drawing.Color.Black
e.Row.BackColor = Drawing.Color.White ' the normal employees make white
End If
End If
End Sub
I need to find the Row index when I press btnSelect
Private Sub GridView3_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView3.RowCommand
Dim index As Integer = Convert.ToInt32(e.CommandArgument) ‘ Error invalid
‘ in other words when pressing the tem-plate field there is no e.CommandArgument
‘But clicking the regular select there is
Dim row As GridViewRow = GridView3.Rows(index)
Session("EnterpriseID") = HttpUtility.HtmlDecode(GridView3.Rows(index).Cells(2).Text)
Dim EmployeeType As String = HttpUtility.HtmlDecode(GridView3.Rows(index).Cells(7).Text)
Dim CommonName As String = HttpUtility.HtmlDecode(GridView3.Rows(index).Cells(1).Text)
Dim EnterpriseID = HttpUtility.HtmlDecode(GridView3.Rows(index).Cells(6).Text)
The GridViewRow object knows its row index via the RowIndex property in the RowCommand event, like this:
Private Sub GridView3_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView3.RowCommand
' Get the row by finding the grandparent of the control (button)
' that initiated the command
Dim theGridViewRow As GridViewRow
theGridViewRow = CType(CType(e.CommandSource, Button).Parent.Parent, GridViewRow)
' Get the index value from the grid view row
Dim index As Integer = theGridViewRow.RowIndex
End Sub
Ok I figured it out myself, I made the default Select button on the grid a Template field. since it was the default button it had the necessary code to make it fire. This was the problem with making a template field from scratch. And by making it a template field it then also gave it a name. So in the RowDataBound code the FindControl method above hides it when a person is not an employee. – R2 Builder 1 min ago edit

How to match the answer in vb.net and asp.net?

I random the 3 question to display on asp.net page. I want to match the security question with correct answer in database. But after I enter the correct answer in textbox and click the "Next" button, the answer cannot match the current question displayed on screen. But if I click the "Next" button, the next question displayed is matched with answer I enter on textbox in previous question. I think this is because the answer is match the question and answer after refresh the page. Please help. Here is my code. thanks
vb.net code
Dim SecurityQuestion As New DBDataContext
Dim randomNumber As Integer
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim SecurityQuestion As New DBDataContext
Dim rowCount As Integer = (From t In SecurityQuestion.tblSecurityQuestions Select t).Count + 1
End Sub
Protected Sub btnNext_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnNext.Click
ValidateAnswer()
End Sub
Private Sub LoadSecurityQuestion()
Dim SecurityQuestion As New DBDataContext
Dim mySecurityQuestion = (From c In SecurityQuestion.tblSecurityQuestions Where c.PkID = randomNumber Select c)
Dim rowCount As Integer = (From t In SecurityQuestion.tblSecurityQuestions Select t).Count + 1
randomNumber = New Random().Next(1, rowCount)
With gvQuestion
.DataSource = mySecurityQuestion
.DataBind()
End With
End Sub
Private Sub ValidateAnswer()
Dim SecurityQuestion As New DBDataContext
Dim validate = (From r In SecurityQuestion.tblRegistrations From s In SecurityQuestion.tblSecurityQuestions _
Where s.PkID = r.Q01 And r.A01 = txtSecurityAns.Text And r.UserID = ad And s.PkID = randomNumber _
Select r)
If validate.Count > 0 Then
Msg3.Text = "Correct Answer"
Else
Msg3.Text = "Invalid Answer"
End If
End Sub
At the time I posted this answer, it looked like a small bit of your code might have been missing. As an example, I couldn't see where you were actually calling the method LoadSecurityQuestion, but it sounds like you may be acidentally re-calling the method LoadSecurityQuestion even after validation succeeds.
I think you can fix this problem by wrapping your call to LoadSecurityQuestion with an "if" qualifier. As an example, lets suppose that you were calling LoadSecurityQuestion in your Load Event handler. If you did that, your new Load event handler might read something like this:
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
...
If IsPostBack Then
' If you wrap all of your Me.LoadSecurityQuestion calls
' with "If" statements like this one, then it should keep
' the security question from changing when the user
' enters the correct answer
If Msg3.Text <> "Correct Answer" Then
Me.LoadSecurityQuestion()
End If
End If
...
End Sub

Resources