gpt4 book ai didi

asp.net - 获取在运行时生成的控制

转载 作者:行者123 更新时间:2023-12-04 05:26:46 24 4
gpt4 key购买 nike

我正在通过后端在文本更改事件上创建一些文本框,如下所示:

protected void txtHowMany_TextChanged(object sender, EventArgs e)
{
int totalSections = Convert.ToInt32(txtHowMany.Text.Trim());

for (int i = 1; i <= totalSections; i++)
{
TextBox tbx = new TextBox();
tbx.Text = "";
tbx.ID = "section" + i;
tbx.Style.Add("width", "90%");
tdSectionsAdd.Controls.Add(tbx);
}
trSectionsName.Visible = true;
}

自动回发适用于 txtHowMany ,所以当我输入一个数字时,它会生成文本框并将其添加到表分区

现在的问题是,我正在尝试从生成的文本框中获取文本,如下所示:
protected void btnSave_click(object sender, EventArgs e)
{
int numbersOfSectionsToSave = 1;
int sectionsToSave =Convert.ToInt32(txtHowMany.Text.Trim());

for (int i = 1; i < sectionsToSave; i++)
{
Sections section = new Sections();
section.CourseId = result;
section.OrganizationId = course.OrganizationId;

foreach (Control c in tdSectionsAdd.Controls)
{
if (c.GetType() == typeof(TextBox))
{
TextBox txtBox = (TextBox)c;
string id = "section" + i;
if (txtBox.ID == id)
{
section.Name = txtBox.Text.Trim();
}
}
}

string name = Request.Form["section1"];
section.CreatedBy = "Admin";
section.CreationDate = DateTime.Now;
section.ModifiedBy = "Admin";
section.ModificationDate = DateTime.Now;
numbersOfSectionsToSave += section.SaveSection();
}

但它显示 中的控件计数为 0 tdSectionsAdd , 在我尝试访问它们之前添加了控件,但它仍然没有在 td 中显示任何控件。
请帮忙,我怎样才能得到这些文本框?

谢谢!

最佳答案

您需要在每个回发中添加它们。存储 totalSections ViewState 中的变量,因此您也可以在页面加载时添加它们:

protected void AddTextBoxes()
{
int totalSections;
if (int.TryParse(Convert.ToString(ViewState["TotalSections"]), out totalSections)
{
for (int i = 1; i <= totalSections; i++)
{
TextBox tbx = new TextBox();
tbx.Text = "";
tbx.ID = "section" + i;
tbx.Style.Add("width", "90%");
tdSectionsAdd.Controls.Add(tbx);
}
trSectionsName.Visible = true;
}
}
protected void txtHowMany_TextChanged(object sender, EventArgs e)
{
ViewState["TotalSections"] = Convert.ToInt32(txtHowMany.Text.Trim());

tdSectionsAdd.Controls.Clear();
AddTextBoxes();
}

protected void Page_Load(object sender, EventArgs e)
{
AddTextBoxes();
}

关于asp.net - 获取在运行时生成的控制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13124255/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com