如何在VB.NET(Web应用程序)中的两个过程之间传递变量

时间:2014-03-03 00:29:49

标签: asp.net vb.net

我基本上是动态创建文本框,以便为数据库添加测试。要创建的文本框的数量作为查询字符串从之前的网页传递。这是代码:

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

我试图将在Page_Load中声明的文本框数组传递给另一个子btnSubmit_Click。我试图将它作为参数传递给它,但它似乎不起作用:

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

安静的失去了,谢谢你的帮助!

4 个答案:

答案 0 :(得分:1)

您可以将文本框内容作为输出参数传递给查询字符串,就像输入参数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)

并在HomePage.aspx的Page Load事件中解析查询字符串。您还可以将值作为会话变量传递

Session("Question1") = txtboxQ(i - 1).Text
...

然后

Dim question1 As String = Session("Question1")
....

答案 1 :(得分:0)

想知道当你可以在页面级别声明变量并从任何方法/函数访问变量时,为什么要传递这样的变量。有什么特殊要求吗?

你在这里想做的事情也不清楚。

答案 2 :(得分:0)

您可以在类中使用全局变量,并将其放在类代码下面。如果你想使用它,你只需要调用那个全局变量。

答案 3 :(得分:0)

在页面级别声明文本框列表

Public textQ = New List(Of TextBox)
Public textA = New List(Of TextBox)

将您的代码更改为以下

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

然后出于任何目的访问列表中的值,可以是提交时的打印值或其他..

例如:

    For Each tb As TextBox In Me.textQ
        Me.label1.Text = Me.label1.Text & tb.Text.Trim()
    Next