Вопрос

I have this program in asp.net using C# .aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div id="first" runat="server">
        Text Boxes
        <asp:TextBox ID="txtnr" runat="server"></asp:TextBox><br />
        <asp:Button ID="btnxt1" runat="server" Text="Next" onclick="btnxt1_Click"/><br />
    </div>
    <div id="second" runat="server">
        <asp:Table ID="tbl" runat="server"></asp:Table>
        <asp:Button ID="btnx2" runat="server" Text="Next" onclick="btnx2_Click"/><br />
    </div>

    <div id="third" runat="server">
        <asp:Label ID="lblxx" runat="server" Text=""></asp:Label><br />
    </div>
    </form>
</body>
</html>

.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{

    static int numr = 0;
    static TableHeaderCell[] tc2;
    static TextBox[] txtb;
    protected void Page_Load(object sender, EventArgs e){}

    protected void btnxt1_Click(object sender, EventArgs e)
    {
        numr = int.Parse(txtnr.Text);
        TableHeaderRow tr;
        tc2 = new TableHeaderCell[numr];
        txtb = new TextBox[numr];
        for (int i = 0; i < numr; i++)
        {
            tr = new TableHeaderRow();
            tc2[i] = new TableHeaderCell();
            txtb[i] = new TextBox();
            txtb[i].Text = "w";
            tc2[i].Controls.Add(txtb[i]);
            tr.Controls.Add(tc2[i]);
            tbl.Controls.Add(tr);
        }
    }

    protected void btnx2_Click(object sender, EventArgs e)
    {
        for (int i = 0; i < numr; i++)
            lblxx.Text += txtb[i].Text+"<br/>";
    }
}

Program steps:

  • enter number of text-boxes to appear (say = 4) and click 'Next'
  • four text-boxes will appear (the program sets the value of textbox = "w",to understand the problem)
  • user can set other value for the text for the four text boxes (say: 1 , 2 , 3 , 4) then click next
  • finally, the program print the values of text boxes, but the problem is the program will print: wwww not "1234" :( ??

How to fix this problem??

Это было полезно?

Решение

The problem is due to the fact that dynamic controls (like yours) do not automatically maintain their state after a post back and you should handle it on your own.

Please follow this link for a very similar question and then this link for the corresponding solution.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top