Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/292.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 动态创建的控件在回发后丢失数据_C#_Asp.net_.net_Runtime - Fatal编程技术网

C# 动态创建的控件在回发后丢失数据

C# 动态创建的控件在回发后丢失数据,c#,asp.net,.net,runtime,C#,Asp.net,.net,Runtime,实际上,我正在Pageload上创建1个TextBox,并将该TextBox添加到面板中。 现在,我有了一个链接按钮,类似于添加另一个 我正在该文本框中输入文本,如果需要,我需要通过单击添加另一个链接按钮来创建新的文本框 实际上,我能够获得计数并重新创建文本框。 但是,问题是,我在先前生成的文本框中输入的文本丢失 谁能给我一个解决方案吗 protected void Page_Load(object sender, EventArgs e) { try {

实际上,我正在
Pageload
上创建1个
TextBox
,并将该
TextBox
添加到
面板中。
现在,我有了一个
链接按钮
,类似于
添加另一个

我正在该
文本框中输入文本,如果需要,我需要通过单击
添加另一个链接按钮来创建新的
文本框

实际上,我能够获得计数并重新创建
文本框。
但是,问题是,我在先前生成的
文本框
中输入的文本丢失

谁能给我一个解决方案吗

protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (!IsPostBack)
            {
                for (int i = 0; i < 5; i++)
                {
                    TableRow row = new TableRow();
                    for (int j = 0; j < 5; j++)
                    {
                        TableCell cell = new TableCell();
                        TextBox tb = new TextBox();                        
                        tb.ID = "TextBoxRow_" + i + "Col_" + j;                        
                        cell.Controls.Add(tb);                        
                        row.Cells.Add(cell);
                    }                    
                    Table1.Rows.Add(row);
                }
            }
        }
        catch (Exception ex)
        {
            throw;
        }        
    }

我在
按钮上得到
计数=0
\u单击

动态生成的控件不保持状态。你必须自己维护它。您可以使用一些隐藏字段来保存控件的状态,这些字段将在服务器端用于提取状态。Asp.net使用隐藏字段来维护请求之间的状态,您可以在源代码中看到
\u VIEWSTATE

在ASP.NET页面中,视图状态表示当 它最后一次是在服务器上处理的。它用于构建调用上下文 并在同一页面的两个连续请求之间保留值。通过 默认情况下,使用隐藏字段在客户端上保留状态 已添加到页面,并在页面之前在服务器上还原 请求已被处理。视图状态会随着时间来回移动 页面本身,但不表示或包含任何 与客户端页面显示相关


使用动态控件时,必须记住,它们仅在下次回发之前存在。ASP.NET不会重新创建动态添加的控件。如果需要多次重新创建控件,则应在PageLoad事件处理程序中执行控件创建(因为当前仅使用条件:!IsPostabck首次创建文本框)。这样做的另一个好处是允许您在动态控件中使用视图状态。尽管视图状态通常在Page.Load事件之前恢复,但如果在处理程序中为PageLoad事件创建控件,ASP.NET将在PageLoad事件处理程序结束后应用其拥有的任何视图状态信息

因此,删除条件:!IsPostback,这样每次加载页面时,也会创建TextBox控件。您还将看到PageLoad处理程序完成后保存的文本框的状态。[显然您没有禁用ViewState!!!]

例如:

protected void Page_Load(object sender, EventArgs e)
{

    TextBox txtBox = new TextBox();
    // Assign some text and an ID so you can retrieve it later. 

    txtBox.ID = "newButton";
    PlaceHolder1.Controls.Add(txtBox);

}

现在,在运行它之后,在文本框中键入任何内容,并查看当您单击导致回发的任何按钮时会发生什么。文本框仍然保持其状态

实际上,我已经使用Javascript完成了我的任务。 事情是这样的:

<form id="form1" runat="server" enctype="multipart/form-data" method="post">
        <span style="font-family: Arial">Click to add files</span>&nbsp;&nbsp;
        <input id="Button1" type="button" value="add" onclick="AddFileUpload()" />
        <br />
        <br />
        <div id="FileUploadContainer">
            <!--FileUpload Controls will be added here -->
        </div>
        <asp:HiddenField ID="HdFirst1" runat="server" Value="" />
        <br />
        <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />
    </form>

单击以添加文件



脚本:

 <script type="text/javascript">
        var counter = 0;

        function AddFileUpload() {

            var div = document.createElement('DIV');
            div.innerHTML = '<input id="file' + counter + '"name = "file' + counter + '"type="text"/><input id="file' + counter + '" name = "file' + counter + '" type="file" /><input id="Button' + counter + '" type="button" value="Remove" onclick = "RemoveFileUpload(this)" />';

            document.getElementById("FileUploadContainer").appendChild(div);
            counter++;
        }
        function RemoveFileUpload(div) {
            document.getElementById("FileUploadContainer").removeChild(div.parentNode);
        }

        function mydetails(div) {
            var info;
            for (var i = 0; i < counter; i++) {
                var dd = document.getElementById('file' + i).value;
                info = info + "~" + dd;
            }
            document.getElementById('<%= HdFirst1.ClientID %>').value = info;
        }
    </script>

var计数器=0;
函数AddFileUpload(){
var div=document.createElement('div');
div.innerHTML='';
document.getElementById(“FileUploadContainer”).appendChild(div);
计数器++;
}
函数RemoveFileUpload(div){
document.getElementById(“FileUploadContainer”).removeChild(div.parentNode);
}
功能详细信息(div){
var信息;
对于(变量i=0;i
然后在上载按钮中单击:

for (int i = 0; i < Request.Files.Count; i++)
        {           
           string strname = HdFirst1.Value;
           string[] txtval = strname.Split('~');
            HttpPostedFile PostedFile = Request.Files[i];
            if (PostedFile.ContentLength > 0)
            {
                string FileName = System.IO.Path.GetFileName(PostedFile.FileName);
               // string textname=
                //PostedFile.SaveAs(Server.MapPath("Files\\") + FileName);
            }
        }
for(int i=0;i0)
{
字符串FileName=System.IO.Path.GetFileName(PostedFile.FileName);
//字符串文本名=
//SaveAs(Server.MapPath(“Files\\”)+文件名);
}
}

在回发过程中,每次都需要在页面加载事件之前或之内重新实例化/重新初始化动态控件,并将此控件添加到页面/表单/占位符中。然后,通过父控件调用LoadPostData方法,将发布的数据自动分配给该控件

检查文章以及如何编写动态控制代码-

这是我在大量使用动态控件后的最终答案

static int myCount = 0;
    private TextBox[] dynamicTextBoxes;

    protected void Page_PreInit(object sender, EventArgs e)
    {
        Control myControl = GetPostBackControl(this.Page);

        if ((myControl != null))
        {
            if ((myControl.ClientID.ToString() == "btnAddTextBox"))
            {
                myCount = myCount + 1;
            }
        }
    }

    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        dynamicTextBoxes = new TextBox[myCount];
        int i;
        for (i = 0; i < myCount; i += 1)
        {
            TextBox textBox = new TextBox();
            textBox.ID = "myTextBox" + i.ToString();
            myPlaceHolder.Controls.Add(textBox);
            dynamicTextBoxes[i] = textBox;
            LiteralControl literalBreak = new LiteralControl("<br />");
            myPlaceHolder.Controls.Add(literalBreak);
        }
    }

    protected void btnAddTextBox_Click(object sender, EventArgs e)
    {
        // Handled in preInit due to event sequencing.
    }

    protected void MyButton_Click(object sender, EventArgs e)
    {
        MyLabel.Text = "";
        foreach (TextBox tb in dynamicTextBoxes)
        {
            MyLabel.Text += tb.Text + " :: ";
        }
    }

    public static Control GetPostBackControl(Page thePage)
    {
        Control myControl = null;
        string ctrlName = thePage.Request.Params.Get("__EVENTTARGET");
        if (((ctrlName != null) & (ctrlName != string.Empty)))
        {
            myControl = thePage.FindControl(ctrlName);
        }
        else
        {
            foreach (string Item in thePage.Request.Form)
            {
                Control c = thePage.FindControl(Item);
                if (((c) is System.Web.UI.WebControls.Button))
                {
                    myControl = c;
                }
            }
        }
        return myControl;
    }
.aspx

<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div style="text-align: center">
    <div style="background-color: Aqua; width: 250px;">
    <br />
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
            <asp:PlaceHolder runat="server" ID="myPlaceHolder"></asp:PlaceHolder>
        </ContentTemplate>
        <Triggers>
            <asp:AsyncPostBackTrigger ControlID="btnAddTextBox" EventName="Click" />
        </Triggers>
    </asp:UpdatePanel>
    <br />
    </div>
    <br />
    <asp:Button ID="btnAddTextBox" runat="server"  Text="Add TextBox" OnClick="btnAddTextBox_Click" />
    <br /><br />
    <asp:UpdatePanel ID="UpdatePanel2" runat="server">
        <ContentTemplate>
            <asp:Button runat="server" ID="MyButton" Text="Get Values." OnClick="MyButton_Click" />
            <br /><br />
            <asp:Label runat="server" ID="MyLabel"></asp:Label>
        </ContentTemplate>
    </asp:UpdatePanel>
 </div>
</form>








.aspx.cs

static int myCount = 0;
    private TextBox[] dynamicTextBoxes;

    protected void Page_PreInit(object sender, EventArgs e)
    {
        Control myControl = GetPostBackControl(this.Page);

        if ((myControl != null))
        {
            if ((myControl.ClientID.ToString() == "btnAddTextBox"))
            {
                myCount = myCount + 1;
            }
        }
    }

    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        dynamicTextBoxes = new TextBox[myCount];
        int i;
        for (i = 0; i < myCount; i += 1)
        {
            TextBox textBox = new TextBox();
            textBox.ID = "myTextBox" + i.ToString();
            myPlaceHolder.Controls.Add(textBox);
            dynamicTextBoxes[i] = textBox;
            LiteralControl literalBreak = new LiteralControl("<br />");
            myPlaceHolder.Controls.Add(literalBreak);
        }
    }

    protected void btnAddTextBox_Click(object sender, EventArgs e)
    {
        // Handled in preInit due to event sequencing.
    }

    protected void MyButton_Click(object sender, EventArgs e)
    {
        MyLabel.Text = "";
        foreach (TextBox tb in dynamicTextBoxes)
        {
            MyLabel.Text += tb.Text + " :: ";
        }
    }

    public static Control GetPostBackControl(Page thePage)
    {
        Control myControl = null;
        string ctrlName = thePage.Request.Params.Get("__EVENTTARGET");
        if (((ctrlName != null) & (ctrlName != string.Empty)))
        {
            myControl = thePage.FindControl(ctrlName);
        }
        else
        {
            foreach (string Item in thePage.Request.Form)
            {
                Control c = thePage.FindControl(Item);
                if (((c) is System.Web.UI.WebControls.Button))
                {
                    myControl = c;
                }
            }
        }
        return myControl;
    }
static int myCount=0;
私有文本框[]动态文本框;
受保护的无效页\u PreInit(对象发送方,事件参数e)
{
Control myControl=GetPostBackControl(this.Page);
如果((myControl!=null))
{
if((myControl.ClientID.ToString()=“btnAddTextBox”))
{
myCount=myCount+1;
}
}
}
受保护的覆盖无效OnInit(事件参数e)
{
碱基.奥尼特(e);
DynamicTextBox=新文本框[myCount];
int i;
对于(i=0;i if (!IsPostBack)
public Dictionary<Guid, string> UcList
{
    get { return ViewState["MyUcIds"] != null ? (Dictionary<Guid, string>)ViewState["MyUcIds"] : new Dictionary<Guid, string>(); }
    set { ViewState["MyUcIds"] = value; }
}

public void InitializeUC()
{
    int index = 1;
    foreach (var item in UcList)
    {
        var myUc = (UserControls_uc_MyUserControl)LoadControl("~/UserControls/uc_MyUserControl.ascx");
        myUc.ID = item.Value;
        pnlMyUC.Controls.AddAt(index, myUc);
        index++;
    }
}

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
        LoadControl();
    else
        InitializeUC();
}