简体   繁体   中英

asp.net listbox_index changed postback is firing on every button

I have a listbox that is populating on a buttonclick and then when the user selects or changes the index on the listbox it downloads a file related to it.

The problem I have is when they go to push a button to search a new record it downloads the file again but firing the code below again. How can I stop it from calling the postback on other buttons?

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();
}

IsPostback property should be used over here.

Enclose your code in condition if(!Page.Ispostback)

Following can be the approach:

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();
      }
    }

MSDN Referance For IsPostBack:

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

Usage With Example:

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

Hope Its Helpful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM