如何用VB引用动态创建的控制在asp.net 3.5 [英] how to reference dynamically created control in asp.net 3.5 with VB

查看:208
本文介绍了如何用VB引用动态创建的控制在asp.net 3.5的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写动态插入控件到一个WebForm上的程序。根据一个变量,我要么添加一个文本框,一组单选按钮,或一组复选框。后来,用户点击提交按钮后,我需要使用控制,以确定用户是否提交了正确的答案,但是当我尝试引用一个控件的ID,我得到txtAnser未声明,它可能无法访问由于它的保护级别。

I'm writing a program that inserts controls onto a webform dynamically. Depending on a variable, I add either a textbox, a set of radio buttons, or a set of checkboxes. Later, after a user clicks a submit button I need to use the controls to determine if the user is submitting the correct answer, but when I try to reference the id of a control, I get "txtAnser is not declared. It may be inaccessible due to it's protections level.

下面是.aspx页(这是一个母版页的标准内容页):

Here is the .aspx page (it's the standard content page of a master page):

<%@ Page Title="" Language="VB" MasterPageFile="~/top.master" AutoEventWireup="false" 
CodeFile="test_page.aspx.vb" Inherits="Default2" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="PageContent" Runat="Server">
    <asp:SqlDataSource ID="sdsQuestionPuller" runat="server" 
    ConnectionString="<%$ ConnectionStrings:SchoolhouseConnectionString6 %>" 
    SelectCommand="SELECT QuestionText, AnswerType, PossibleAnswers,    CorrectAnswers        
    FROM Questions WHERE (SubjectID = @SubjectID) AND (QuestionOrder = @QuestionOrder)">
    <SelectParameters>
        <asp:SessionParameter Name="SubjectID" SessionField="SubjectID" />
        <asp:SessionParameter Name="QuestionOrder" SessionField="PageNumber" />
    </SelectParameters>
</asp:SqlDataSource>
    <asp:SqlDataSource ID="sdsMaxQuestions" runat="server" 
        ConnectionString="<%$ ConnectionStrings:SchoolhouseConnectionString7 %>" 
        SelectCommand="SELECT MAX(QuestionOrder) AS LastQuestion FROM Questions GROUP     BY SubjectID HAVING (SubjectID = @SubjectID)">
        <SelectParameters>
            <asp:SessionParameter Name="SubjectID" SessionField="SubjectID" />
        </SelectParameters>
    </asp:SqlDataSource>
<div>
    <asp:Label ID="lblInstructionHolder" runat="server"></asp:Label>
</div>
<div>
    <asp:Label ID="lblQuestionHolder" runat="server"></asp:Label>
</div>
    <asp:PlaceHolder ID="plhQuestionHolder" runat="server"></asp:PlaceHolder>
<div>
    <asp:Button ID="btnSubmit" Text="Submit" runat="server" />
</div>
</asp:Content>

这里是code的背后,我遇到了在提交按钮单击事件的问题,我尝试引用在select case语句的txtAnswer控制:

And here is the code behind, I'm running into problems in the submit button click event where I try to reference the txtAnswer control in the select case statement:

Imports System.Data

Partial Class Default2
    Inherits System.Web.UI.Page

    Dim intMaxPage As Integer
    'QuestionText, AnswerType, PossibleAnswers, CorrectAnswers
    Dim strQuestion As String
    Dim strQuestionType As String
    Dim astrPossibleAnswers() As String
    Dim intNumberOfPossAnswers As Integer
    Dim astrCorrectAnswers() As String
    Dim intNumberOfCorrectAnswers As Integer

    Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init

    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        'Load up the variables(make sure data is retrieved, create a view from the source, retrieve the only row, assing the item(s) from the row to variables)
        sdsMaxQuestions.DataBind()
        Dim dtvLastPageView As DataView = CType(sdsMaxQuestions.Select(DataSourceSelectArguments.Empty), DataView)
        Dim dtrLastPageRow As DataRowView = dtvLastPageView.Item(0)
        intMaxPage = CInt(Trim(dtrLastPageRow.Item(0).ToString))

        Dim dtvQuestionsView As DataView = CType(sdsQuestionPuller.Select(DataSourceSelectArguments.Empty), DataView)
        Dim dtrQuestionsRow As DataRowView = dtvQuestionsView.Item(0)
        strQuestion = Trim(dtrQuestionsRow.Item(0).ToString)
        strQuestionType = Trim(dtrQuestionsRow.Item(1).ToString)
        astrPossibleAnswers = Split(Trim(dtrQuestionsRow.Item(2).ToString), ";")
        intNumberOfPossAnswers = astrPossibleAnswers.Count
        astrCorrectAnswers = Split(Trim(dtrQuestionsRow.Item(3).ToString), ";")
        intNumberOfCorrectAnswers = astrCorrectAnswers.Count

        'Finish loading controls
        lblQuestionHolder.Text = strQuestion
        Select Case strQuestionType
            Case "checkbox"
                lblInstructionHolder.Text = "Choose the correct answer(s)."
            Case "radio"
                lblInstructionHolder.Text = "Choose the best answer."
            Case "fillintheblank"
                lblInstructionHolder.Text = "Please fill in the blank, case doesn't count, spelling does."
            Case Else
                lblInstructionHolder.Text = "Somethings wrong, contact admin"
        End Select

        'Generate the controls for answers...
        GenerateControls()

    End Sub

    Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click
        'Declare the variables, get any existing values, then check to see if the answer is correct, display a message and go to the next page or store the score.
        Dim intNumberRight As Integer = 0
        Dim intNumberTotal As Integer = 0

        If Not (Session("NumberRight") = Nothing) Then
            intNumberRight = CInt(Session("NumberRight"))
        End If
        If Not (Session("NumberTotal") = Nothing) Then
            intNumberTotal = CInt(Session("NumberTotal"))
        End If

        Select Case strQuestionType
            Case "checkbox"

            Case "radio"

            Case "fillintheblank"
                'Here is where I am having issues
                If txtAnswer Is Not Nothing Then

                End If
                If txtAnswer.text.ToLower = astrCorrectAnswers(0).ToLower Then

                End If
            Case Else
                MsgBox("Somethings wrong, contact admin")
        End Select

        If intMaxPage = CType(Session("PageNumber"), Integer) Then
            Response.Redirect("user_landing.aspx")
        Else
            Session("PageNumber") = CType(Session("PageNumber"), Integer) + 1
            Response.Redirect("test_page.aspx")
        End If
    End Sub

    Private Sub GenerateControls()
        'Make the correct controls depending on the type
        Dim conDivHolder As HtmlGenericControl = New HtmlGenericControl("div")

        Select Case strQuestionType
            Case "checkbox"
                For i As Integer = 0 To intNumberOfPossAnswers - 1
                    Dim chkAnswer As CheckBox = New CheckBox
                    With chkAnswer
                        .ID = "chkAnswer" + i.ToString
                        .Text = astrPossibleAnswers(i)
                    End With
                    conDivHolder.Controls.Add(chkAnswer)
                Next

            Case "radio"
                For i As Integer = 0 To intNumberOfPossAnswers - 1
                    Dim rdoAnswer As RadioButton = New RadioButton
                    With rdoAnswer
                        .ID = "rdoAnswer" + i.ToString
                        .Text = astrPossibleAnswers(i)
                        .GroupName = "rdoGroup"
                    End With
                    conDivHolder.Controls.Add(rdoAnswer)
                Next

            Case "fillintheblank"
                Dim txtAnswer As TextBox = New TextBox
                txtAnswer.ID = "txtAnswer"
                conDivHolder.Controls.Add(txtAnswer)

            Case Else
                Dim lblOops As Label = New Label
                lblOops.Text = "Oops, contact admin"
                conDivHolder.Controls.Add(lblOops)
        End Select

        plhQuestionHolder.Controls.Add(conDivHolder)
    End Sub

End Class

如果任何人都可以指出什么我需要做的,我会AP preciate它。

If anyone could point out what I need to do, I would appreciate it.

谢谢,
西蒙

推荐答案

首先,要生成您的Page_Load中的控件(回发或没有),所以无论txtAnswer的状态是被点击提交按钮之前,它的现在没有了 - txtAnswer已再次与初始状态再生。你应该动态地呈现你的控件仅当​​的IsPostBack是假的。

First of all, you're generating your controls on Page_Load (PostBack or not), so whatever the state of txtAnswer was before the submit button was clicked, it's gone now - txtAnswer has been regenerated again with an initial state. You should dynamically render your controls only if IsPostBack is false.

其次,你可能应该访问txtAnswer的Text属性是不是在咱这语句块。否则,你可能会得到一个空引用异常。

Secondly, you should probably be accessing the txtAnswer's Text property within the Is Not Nothing if statement block. Otherwise you may get a null reference exception.

第三,去你的TextBox控件的参考,你可以尝试找到其占位符内标识的控制,像这样的东西(我在C#中这样做 - 你可以转换到VB你自己):

Thirdly, to get a reference to your TextBox control you can try to find the control by ID within its placeholder, with something like this (I'm doing this in C# - you can translate to VB on your own):

定义函数来寻找一个递归控制:

Define function to look for a control recursively:

protected Control FindControl(Control parent, string controlID)
{
  Control control = parent.FindControlByID("controlID");

  if (control != null) 
  {
    return control;
  }

  foreach(Control child in control.Controls)
  {
    Control childControl = FindControl(child , controlID);

    if (childControl != null) 
    {
      return childControl;
    }
  }

  return null;
}

打电话给你的递归查找功能:

Call your recursive find function:

Control ctrl = FindControl(plhQuestionHolder, "txtAnswer");

这code都不是实际测试,所以不要对我大喊大叫,如果它不作为是工作。这仅仅是一个导

None of this code is actually tested, so don't yell at me if it doesn't work as is. This is merely a guide.

这篇关于如何用VB引用动态创建的控制在asp.net 3.5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆