gpt4 book ai didi

c# - 组合框的 ASPX 回发问题

转载 作者:太空宇宙 更新时间:2023-11-03 22:08:21 25 4
gpt4 key购买 nike

我创建了一个简单的 ASPX 页面,它在 GridView 中列出了记录。记录是事件列表,其中一列是报告事件的人的 ID。

初始页面显示所有记录,但我想为 ReportedBy 列提供过滤器。我通过允许用户在文本框中输入 ReportedByID 然后单击提交按钮来实现此功能。这会使用过滤后的 View 按预期刷新页面。

该页面的代码如下:

public MyPage()
{
this.Load += new EventHandler(Page_Load);
}

protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
DataAccessObj daObj = new DataAccessObj();
IncidentGrid.DataSource = daObj.GetIncidentsByReportedById(0);
IncidentGrid.DataBind();
}
}

protected void btnSubmit_Click(object sender, EventArgs e)
{
int reportedById = 0;

if (int.TryParse(txtReportedById.Text, out reportedById) == false)
{
reportedById = 0;
}

DataAccessObj daObj = new DataAccessObj();
IncidentGrid.DataSource = daObj.GetIncidentsByReportedById(reportedById);
IncidentGrid.DataBind();
}

为了使它更加用户友好,我决定添加一个下拉框,其中填充了 ReportedBy 名称,供用户选择,然后在单击提交按钮时用于过滤。下拉框将名称作为显示项,但值仍应设置为 ID。

我遇到的问题是,我从下拉框中获得的 ID 号总是作为列表的第一个元素出现,而不是用户在单击提交按钮时选择的那个。

此页面的代码如下:

public MyPage()
{
this.Load += new EventHandler(Page_Load);
}

protected void Page_Load(object sender, EventArgs e)
{
DataAccessObj daObj = new DataAccessObj();

foreach (ReportedByItem repByItem in daObj.GetAllReportedBy())
{
ListItem listItem = new ListItem(repByItem.Name, repByItem.Id.ToString());
combobox.Items.Add(listItem);
}

if (IsPostBack == false)
{
IncidentGrid.DataSource = daObj.GetIncidentsByReportedById(0);
IncidentGrid.DataBind();
}
}

protected void btnSubmit_Click(object sender, EventArgs e)
{
int reportedById = 0;

if (combobox.SelectedItem != null)
{
if (int.TryParse(combobox.SelectedItem.Value, out reportedById) == false)
{
reportedById = 0;
}
}

DataAccessObj daObj = new DataAccessObj();
IncidentGrid.DataSource = daObj.GetIncidentsByReportedById(reportedById);
IncidentGrid.DataBind();
}

如有任何帮助,我们将不胜感激。时间差

最佳答案

请记住,对于 WebForms,Page_Load 代码在创建回发的控件的事件处理程序代码之前执行。

您必须在检查回发标志的部分填充列表,就像您对网格所做的那样。

if (IsPostBack == false){
//bind the combobox
}

否则,在回发时,列表将重新填充并且选择将消失。

关于c# - 组合框的 ASPX 回发问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7582376/

25 4 0