gpt4 book ai didi

c# - 如何获取动态填充控件的值

转载 作者:IT王子 更新时间:2023-10-29 04:19:17 25 4
gpt4 key购买 nike

我在 aspx 页面中有一个包含面板的 div

<div id="divNameofParticipants" runat="server">
<asp:Panel ID="panelNameofParticipants" runat="server">
</asp:Panel>
</div>

我正在使用以下代码从代码隐藏动态填充面板:

void btnSubmitCountParticipant_Click(object sender, EventArgs e)
{
StringBuilder sbparticipantName=new StringBuilder();

try
{
int numberofparticipants = Convert.ToInt32(drpNoofparticipants.SelectedValue);
ViewState["numberofparticipants"] = numberofparticipants;
Table tableparticipantName = new Table();
int rowcount = 1;
int columnCount = numberofparticipants;
for (int i = 0; i < rowcount; i++)
{
TableRow row = new TableRow();
for (int j = 0; j < columnCount; j++)
{
TableCell cell = new TableCell();
TextBox txtNameofParticipant = new TextBox();
txtNameofParticipant.ID = "txtNameofParticipant" + Convert.ToString(i);
cell.ID = "cell" + Convert.ToString(i);
cell.Controls.Add(txtNameofParticipant);
row.Cells.Add(cell);


}
tableparticipantName.Rows.Add(row);
panelNameofParticipants.Controls.Add(tableparticipantName);

}

}
catch(Exception ex)
{


}
}

现在我想在代码隐藏中访问这些动态生成的文本框的值,我的代码如下:

public void CreateControls()
{

try
{
//String test1 = test.Value;
List<string> listParticipantName = new List<string>();
if (ViewState["numberofparticipants"] != null)
{
int numberofparticipants = Convert.ToInt32(ViewState["numberofparticipants"]);
for (int i = 0; i < numberofparticipants; i++)
{
string findcontrol = "txtNameofParticipant" + i;
TextBox txtParticipantName = (TextBox)panelNameofParticipants.FindControl(findcontrol);
listParticipantName.Add(txtParticipantName.Text);

}
}
}
catch (Exception ex)
{

}
}

但我无法在代码隐藏中获取值。

 TextBox txtParticipantName = (TextBox)panelNameofParticipants.FindControl(findcontrol);

上面的代码无法找到控件,它总是给出 null。我做错了什么。我也在页面加载中重新创建了控件,因为回发是无状态的,但仍然没有成功。

提前致谢

最佳答案

您需要在 PreInit 而不是 OnLoad 中创建动态控件。请参阅此处的文档:https://msdn.microsoft.com/en-us/library/ms178472.aspx

在页面加载时重新/创建控件将导致 ViewState 不绑定(bind)到控件,因为 View 状态绑定(bind)发生在 OnLoad 之前。

关于c# - 如何获取动态填充控件的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30871093/

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