Pregunta

Editar: si alguien también pudiera sugerir una forma más sensata de hacer que suceda lo que intento a continuación, también sería muy apreciado

Estoy creando un formulario multipágina que toma una cantidad (de producto) de un método POST y muestra una secuencia de formulario que se basa en ese número. cuando el usuario pasa a la página siguiente, se supone que el formulario debe recopilar esta información y mostrarla (para confirmación), que luego enviará esta información a un servicio que proporcionará las URL para mostrar.

No hace falta decir que tengo problemas para hacer que esto funcione. Aquí están las partes relevantes de mi código (anónimo):

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)

Perdón por la cantidad retorcida de (código aficionado). Lo que sospecho si falla es que FindControl () no funciona, pero no puedo entender por qué ...

si se puede dar alguna ayuda, estaría muy agradecido.

Editar: mostrar el error podría ayudar:

Error (Línea 112) Detalles de excepción: System.NullReferenceException: referencia de objeto no establecida en una instancia de un objeto.

Error de origen:

Línea 111: Hashtable tempUser = new Hashtable ();
Línea 112: tempUser.Add (" name ", name.Text);
Línea 113: tempUser.Add (" email ", email.Text);
Línea 114: this.Users.Add (tempUser);

¿Fue útil?

Solución 2

Lo descubrí:

FindControl () funciona como una búsqueda directa de los elementos secundarios del control al que se llama.

cuando lo estaba llamando, era (automáticamente) Page.FindControl () había anidado la creación de la tabla dentro de un campo y un control Table

cuando llamé a tableID.FindControl () encontró los controles exactamente como debería.

Gracias por la ayuda, Gregory, y por todos los comentarios a todos.

-Matt

Otros consejos

Su problema se debe al hecho de que está recargando el formulario cada vez en Page_Load. Asegúrese de cargar solo los cuadros de texto dinámicos una vez y podrá encontrarlos cuando los necesite para su confirmación. Mientras se reconstruya Page_Load, no encontrará la respuesta y correrá el riesgo de no encontrar nada.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top