asp.net listbox_index更改回发是在每个按钮上触发

时间:2013-05-02 04:46:54

标签: c# asp.net webforms postback

我有一个在按钮上填充的列表框,然后当用户选择或更改列表框上的索引时,它会下载与之相关的文件。

我遇到的问题是,当他们按下按钮搜索新记录时,它会再次下载文件,但会再次触发下面的代码。如何阻止它在其他按钮上调用回发?

protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    string splitval = ListBox1.SelectedValue.ToString();
    string[] newvar = splitval.Split(',');
    GlobalVariables.attachcrq = newvar[0];
    GlobalVariables.num = UInt32.Parse(newvar[1]);
    string filename = ListBox1.SelectedItem.ToString();
    GlobalVariables.ARSServer.GetEntryBLOB("CHG:WorkLog", GlobalVariables.attachcrq, GlobalVariables.num, Server.MapPath("~/TEMP/") + filename);

    FileInfo file = new FileInfo(Server.MapPath("~/TEMP/" + filename));
    Response.Clear();
    Response.AppendHeader("Content-Disposition", "attachment; filename=" + file.Name);
    Response.AppendHeader("Content-Length", file.Length.ToString());
    Response.ContentType = ReturnExtension(file.Extension.ToLower());
    Response.TransmitFile(file.FullName);
    Response.Flush();
    Response.End();
}

1 个答案:

答案 0 :(得分:-1)

IsPostback属性应该在这里使用。

将您的代码包含在条件if(!Page.Ispostback)

以下可以是方法:

protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e) {

       if(!Page.IsPostback)
      {
        string splitval = ListBox1.SelectedValue.ToString();
        string[] newvar = splitval.Split(',');
        GlobalVariables.attachcrq = newvar[0];
        GlobalVariables.num = UInt32.Parse(newvar[1]);
        string filename = ListBox1.SelectedItem.ToString();
        GlobalVariables.ARSServer.GetEntryBLOB("CHG:WorkLog", GlobalVariables.attachcrq, GlobalVariables.num, Server.MapPath("~/TEMP/") + filename);

        FileInfo file = new FileInfo(Server.MapPath("~/TEMP/" + filename));
        Response.Clear();
        Response.AppendHeader("Content-Disposition", "attachment; filename=" + file.Name);
        Response.AppendHeader("Content-Length", file.Length.ToString());
        Response.ContentType = ReturnExtension(file.Extension.ToLower());
        Response.TransmitFile(file.FullName);
        Response.Flush();
        Response.End();
      }
    }

IsPostBack的MSDN Referance:

http://msdn.microsoft.com/en-us/library/system.web.ui.page.ispostback.aspx

使用示例:

http://www.geekinterview.com/question_details/60291

希望它有用。