gpt4 book ai didi

c# - 通过按钮 onclick 事件在 ASP.NET 中创建动态表

转载 作者:太空狗 更新时间:2023-10-30 01:08:49 26 4
gpt4 key购买 nike

这是我的要求:

  • 我有一个下拉列表和文本框(appName 和配置文件)。
  • 我想从下拉列表和文本框中获取值并将它们添加到表格(或呈现为表)
  • 有时我希望能够遍历表并将值提交到数据库。

我的问题:

  • 由 onClick 引起的回发甚至将表格封装为仅显示最后输入的值,并且不保留任何以前的值值(value)观。

注意事项:

  • 我尝试使用绑定(bind)到数据网格的数据列表来解决这个问题,但没有成功。

代码:

    protected void addAppButton_Click(object sender, EventArgs e)
{
DropDownList appList = (DropDownList)newEntryFV.FindControl("appList");
TextBox profileTextBox = (TextBox)newEntryFV.FindControl("profileTextBox");
addAppsToTable(appList.SelectedValue.ToString(), profileTextBox.Text.ToString());
}

private void addAppsToTable(string appName, string profileName)
{
Table appsTable = (Table)newEntryFV.FindControl("appTable");
TableRow newRow = new TableRow();
TableCell appNameCell = new TableCell();
TableCell profileCell = new TableCell();
appNameCell.Text = appName;
profileCell.Text = profileName;
newRow.Cells.Add(appNameCell);
newRow.Cells.Add(profileCell);
appsTable.Rows.Add(newRow);
}

解决我问题的代码:

    [Serializable]
public class securityApps
{
public string secAppID { get; set; }
public string secAppName { get; set; }
public string secProfile { get; set; }
}

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

protected void addAppButton_Click(object sender, EventArgs e)
{
DropDownList appList = (DropDownList)newEntryFV.FindControl("appList");
TextBox profileTextBox = (TextBox)newEntryFV.FindControl("profileTextBox");
addAppsToListVS(appList.SelectedValue.ToString(), appList.SelectedItem.Text.ToString(), profileTextBox.Text.ToString());
BindApps();

}

private void addAppsToListVS(string appID, string appName, string profile)
{
securityApps secApp = new securityApps();
secApp.secAppID = appID;
secApp.secAppName = appName;
secApp.secProfile = profile;
((List<securityApps>)ViewState["appsListVS"]).Add(secApp);
}
// Binds apps to Grid View
private void BindApps()
{
GridView appsListGV = (GridView)newEntryFV.FindControl("appsListGV");
if (ViewState["appsListVS"] != null)
{
appsListGV.DataSource = (List<securityApps>)ViewState["appsListVS"];
appsListGV.DataBind();
}
else
{
List<securityApps> appsListVS = new List<securityApps>();
ViewState["appsListVS"] = appsListVS;
}
}

最佳答案

如何在 ViewState 中存储一个对象列表(它们甚至可以是简单的键值对)。您可以将该数据用作 GridView 的数据源。我认为这是最简单的方法。如果您需要更多详细信息,请告诉我。

编辑——你上面的解决方案看起来不错——我可能会通过为你的 ViewState 值设置一个属性来让它更容易一些。

List<securityApps> AppsListVS{
get
{
if(ViewState["AppListVS"] == null
this.AppListVS = new List(securityApps)();
return (List<securityApps>)ViewState["AppListVS"];
}
set
{
ViewState["AppListVS"] = value;
}
}

关于c# - 通过按钮 onclick 事件在 ASP.NET 中创建动态表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8318279/

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