gpt4 book ai didi

c# - 如何从 asp.net c# 中动态生成的控件中获取值?

转载 作者:太空狗 更新时间:2023-10-30 00:05:07 25 4
gpt4 key购买 nike

我知道这是一个问得很好的问题,我找到了一些标记为答案的问题,但这些并没有解决我的问题。请看看我的代码..

显示动态控件的方法

private void ShowControlsByFormId()
{
List<FormControlsBO> list = new List<FormControlsBO>();

list = new FormControlsDA().FormControls_GetByFormId(Convert.ToInt32(ddlForm.SelectedValue.ToString()));

if (list.Count > 0)
{
for (int i = 0; i < list.Count; i++)
{
DynamicControl dynamicControl = CommonUtility.GenerateControl(list[i]);
pnlInput.Controls.Add(new LiteralControl("<tr><td>"));
pnlInput.Controls.Add(dynamicControl.GeneratedControlLiteral);
pnlInput.Controls.Add(new LiteralControl("</td><td></td><td>"));
pnlInput.Controls.Add(dynamicControl.GeneratedControl);
pnlInput.Controls.Add(new LiteralControl("</td><tr><br/><br/>"));
}
pnlAction.Visible = true;
}
else
{
pnlAction.Visible = false;
}
}

生成动态控件的方法

public static DynamicControl GenerateControl(FormControlsBO bo)
{
DynamicControl dynamicControl = new DynamicControl();
Control control = new Control();

LiteralControl literal = new LiteralControl();

switch (bo.FieldType)
{
case "TextBox":
control = new TextBox();
control.ID = bo.FieldName;
literal.Text = bo.FieldLabel;
break;
case "RadioButton":
control = new RadioButton();
control.ID = bo.FieldName;
literal.Text = bo.FieldLabel;
break;
case "CheckBox":
control = new CheckBox();
control.ID = bo.FieldName;
literal.Text = bo.FieldLabel;
break;
case "DropDownList":
control = new DropDownList();
control.ID = bo.FieldName;
literal.Text = bo.FieldLabel;
break;
}

control.ClientIDMode = ClientIDMode.Static;
dynamicControl.GeneratedControl = control;
dynamicControl.GeneratedControlLiteral = literal;

return dynamicControl;
}

保存数据的方法

    private void FormRecords_Save()
{
List<FormControlsBO> list = new List<FormControlsBO>();
FormControlsBO bo = new FormControlsBO();

foreach (Control ctl in pnlInput.Controls)
{
CommonUtility.DataFiller(bo, ctl);
list.Add(bo);
}

Boolean result = false;
result = new FormControlsDA().FormRecords_Save(list);

if(result == true)
{
lblMessage.Text = "Form data saved successfully";
}
else
{
lblMessage.Text = "Form data not saved";
}
}

问题是,当我调试代码时,pnlInput.Controls 显示零计数。请帮忙 !!

最佳答案

我已经回答了here所有动态控件都应在页面的 Init 事件中重新启动,因为 View 状态管理器值是在每个请求中设置的。你可以查看页面的lifecycle . 所以现在,当您不在 init 事件中创建控件时,viewstates 在设置回发数据时会错过它们,而当您尝试获取值时,它们等于零。 请记住,您必须创建具有相同名称的相同控件类型。

关于c# - 如何从 asp.net c# 中动态生成的控件中获取值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18733477/

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