Pergunta

Editar: se alguém também poderia sugerir uma maneira mais sensata de fazer o que estou tentando abaixo para acontecer, que também seria muito apreciada

Eu estou construindo um formulário com várias que leva uma quantidade (de produto) de um método POST, e exibe uma seqüência forma contando com esse número. quando o usuário vai para a próxima página, o formulário é suposto para coletar essas informações e exibi-lo (para confirmação), que irá, em seguida, enviar essa informação para um serviço que irá fornecer URL de exibir.

É desnecessário dizer que eu estou tendo problemas para fazer este trabalho. Aqui está as partes relevantes do meu código (anónima):

public partial class foo : System.Web.UI.Page
{
    Int quantityParam    = 3;
    ArrayList Users  = new ArrayList();
    //the information for each user is held in a hashtable the array list will be an array list of the user hashtables


protected void Page_Init(object sender, EventArgs e)
{
    if(null != Request["quantity1"])
       { 
             this.quantityParam = Request["quantity1"];
       }
}
protected void Page_Load(object sender, EventArgs e)
{
    int quantity = this.quantityParam;
    if(quantity < 1){ mviewThankYou.SetActiveView(View4Error);} 
    else 
    { //create a form for each user
        mviewThankYou.SetActiveView(View1EnterUsers);
        for(int user = 0;user < quantity; user++)
        {
            createUserForm(user);       
        }
    }   
}
protected void BtnNext1_Click(object sender, EventArgs e)
{
    if(Page.IsValid)
    {
        for(int i = 0; i < quantity; i++)
        {
            String ctrlName = "txtUser" + i.ToString();
            String ctrlEmail = "txtEmail" + i.ToString();
            TextBox name = (TextBox)FindControl(ctrlName);
            TextBox email = (TextBox)FindControl(ctrlEmail);

            /*BONUS QUESTION: How can I add the Hashtables to the Users Array without them being destroyed when I leave the function scope?

            this is where the failure occurs: 
            System.NullReferenceException: Object reference not set to an instance of an object. on: "tempUser.Add("name",name.Text); 
            */

            Hashtable tempUser = new Hashtable();
            tempUser.Add("name",name.Text);
            tempUser.Add("email",email.Text);
            this.Users.Add(tempUser);
        }
        for(int i = 0; i < quantity; i++)
        {
            v2Content.Text +="<table><tr><td>Name: </td><td>"+
            ((Hashtable)Users[i])["name"]+
            "</td></tr><tr><td>Email:</td><td>"+
            ((Hashtable)Users[i])["email"]+
            "</td></tr></table>";
        }
        mviewThankYou.SetActiveView(View2Confirm);
    }
}
private void createUserForm(int userNum){
    DataTable objDT = new DataTable();
        int rows = 2;
        int cols = 2;

    //create the title row..
    TableRow title = new TableRow();
    TableCell titleCell = new TableCell();
    formTable.Rows.Add(title);
    Label lblUser = new Label();
    lblUser.Text = "<b>User "+ (userNum+1) + "</b>";
    lblUser.ID = "lblTitle"+ userNum;
    titleCell.Controls.Add(lblUser);
    title.Cells.Add(titleCell);

    for(int i = 0; i < rows; i++)
    {
        TableRow tRow = new TableRow();     
        formTable.Rows.Add(tRow);
        for(int j = 0; j < cols; j++)
        {
            TableCell tCell = new TableCell();
            if(j == 0){
                Label lblTitle = new Label();
                if(i == 0){
                    lblTitle.Text = "User Name:";
                    lblTitle.ID = "lblUser" + userNum;
                }
                else{
                    lblTitle.Text = "User Email:";
                    lblTitle.ID = "lblEmail" + userNum;
                }
                tCell.Controls.Add(lblTitle);
            } else {
                TextBox txt = new TextBox();
                if(i==0){
                    txt.ID = "txtUser" + userNum;
                }
                else{
                    txt.ID = "txtEmail" + userNum;
                }
                RequiredFieldValidator val = new RequiredFieldValidator();
                val.ID = txt.ID + "Validator";
                val.ControlToValidate = txt.UniqueID;
                val.ErrorMessage = "(required)";

                tCell.Controls.Add(txt);
                tCell.Controls.Add(val);
            }
            tRow.Cells.Add(tCell);
        }//for(j)
    }//for(i)

    //create a blank row...
    TableRow blank = new TableRow();
    TableCell blankCell = new TableCell();
    formTable.Rows.Add(blank);
    Label blankLabel = new Label();
    blankLabel.Text = " ";
    blankLabel.ID = "blank" + userNum;
    blankCell.Controls.Add(blankLabel);
    blank.Cells.Add(blankCell);         

}//CreateUserForm(int)

Sorry for a quantidade gnarly de (código amador). O que eu suspeito que se não é que FindControl () não está funcionando, mas eu não consigo descobrir por que ...

Se qualquer ajuda pode ser dada, eu ficaria muito grato.

Edit: mostrando a ajuda erro pode:

Erro (Linha 112) Detalhes da exceção: System.NullReferenceException: Referência de objeto não definida para uma instância de um objeto.

Fonte de erro:

Linha 111: Hashtable TempUser = new Hashtable ();
Linha 112: tempUser.Add ( "nome", name.Text);
Linha 113: tempUser.Add ( "email", email.Text);
A linha 114: this.Users.Add (TempUser);

Foi útil?

Solução 2

Eu percebi isso:

FindControl () funciona como uma busca direta dos filhos do controle é chamado por diante.

quando eu estava chamando-o, era (automaticamente) Page.FindControl () Eu tinha aninhada a criação da tabela dentro de um campo e um controle Table

quando liguei tableID.FindControl () encontrou os controles apenas como deveria.

Obrigado pela ajuda, Gregory, e por todos os comentários todos.

-Matt

Outras dicas

Você problema vem no fato de que você está recarregando a forma cada vez em Page_Load. Certifique-se que você só carregar as caixas de texto dinâmicas uma vez e você será capaz de encontrá-los quando precisar deles para confirmação. Enquanto Page_Load reconstrói, você não vai encontrar a resposta, e o risco de não encontrar nada.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top