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

标签 c# asp.net visual-studio-2008

我创建了一个简单的 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/

相关文章:

c# - 远程服务器在谷歌翻译中返回错误 : (503) Server Unavailable.

c++ - 在 visual studio(非 .net)中编译 "standard"C++

visual-studio-2008 - 如何停止Visual Studio运行所有Web服务

c# - C# : Cannot implicitly convert type 'MyWidget' to 'IWidget' 中的泛型继承

c# - 如何将数据表中的所有行复制到数据行数组?

c# - 模型内的列表项在发布时始终为空 - Asp.net MVC

c# - 日期时间变量

javascript - 在 Raphael JS 中围绕你的论文绘制边框

c# - 在 WPF 文档查看器中禁用 CTRL+P

c# - 哪些方法在内部调用 GetHashCode?