Question

Response.Redirect not working properly...

Asked by: rock815

I'm running into a weird issue with the response.redirect.  This code is in the RowCommand event of a DataGrid.  Anyway, the code runs fine and processes the response.redirect.  

When you stop through the code, it takes you to the Assign.aspx page properly.  However, if you do not step through the code by pressing F5 (but run it in debug), it processes, runs some of the code in assign.aspx, and then comes back to the RowCommand Event hitting the cntAssign again (this time getting the value of 1) and redirects you to Response.Redirect("~/Admin/Default.aspx?LocKey=" + _lockey + "&AlreadyTaken=yes", true);

Any ideas?

int RIndex = Convert.ToInt32(e.CommandArgument);
        GridViewRow row = dgStudents.Rows[RIndex];
 
        string _studentid = row.Cells[0].Text;
        string _assignid = row.Cells[9].Text;
        string _userid = Master.UserID;
 
        if (e.CommandName == "AssignMe")
        {
            int cntAssign = Convert.ToInt32(SQLTasks.ExecuteScalar("SELECT dbo.fncStudentTaken('" + row.Cells[9].Text + "')"));
 
            if (cntAssign > 0)
            {
                Response.Redirect("~/Admin/Default.aspx?LocKey=" + _lockey + "&AlreadyTaken=yes", true);
            }
 
            SQLTasks.ExecuteNonQuery("UPDATE Assignments SET StaffAssignedto = '" + _userid + "', DateAssigned = GetDate() WHERE [id] = '" + _assignid + "'");
            Response.Redirect("~/Admin/Assign.aspx?id=" + _studentid + "&AssignmentID=" + _assignid + "&LocKey=" + _lockey, true);
        }

                                  
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:

Select allOpen in new window

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2008-12-02 at 09:03:43ID23950338
Tags

asp.net 2.0 c#

Topics

Programming for ASP.NET

,

.NET Framework 2.x

,

WebApplications

Participating Experts
1
Points
250
Comments
20

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. weird problems with Datagrid command
    hi guys, I got a problem when using DataGrid Command. I have an EditCommand Column with the "Edit" Link button in it, and I have written the corresponding functions to handle the "Edit", "Update" and "Cancle" commands as below: public ...
  2. Rowcommand only works for first row in GridView
    Ok, I got this to work however it's only being applied to the very first row in my GridView. I'm not sure why. In my GridView, I click on the imagebutton, and this all works but when I try the second row, I would think that the RowCommand would know which row it's workign w...
  3. RowCommand Event Doesn't fire when using AJAX Updat…
    How do I programatically set a gridview control to fire the rowcommand event when the gridview is inside of an ajax updatepanel control? I tried the following logic and it doesn't work: <Triggers> <asp:AsyncPos...
  4. problem with default.aspx
    hi experts, I changed default.aspx with sharepoint designer yesterday,and after that my site dont work any more,I cant see my first page,I get PARSER ERROR...I put these tags in my web.config <PageParserPaths> <PageParserPath VirtualPath="/_catalogs/masterpage/...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: prairiedogPosted on 2008-12-02 at 09:07:49ID: 23078718

Remove the last parameter in Response.Redirect, which means "True".

 

by: rock815Posted on 2008-12-02 at 09:10:12ID: 23078741

I have removed it and tried "false".  No luck, same result.

 

by: prairiedogPosted on 2008-12-02 at 09:17:45ID: 23078834

You have two Response.Redirect, did you remove "true" from both of them?

 

by: rock815Posted on 2008-12-02 at 09:24:12ID: 23078876

Yeah, I have removed both.  I guess I should elaborate more.  In testing, the 1st time the RowCommand event is fired, cntAssign ends up being the value of 0.  So it bypasses the first Redirect() and then runs the Redirect( to Assign.aspx) like it is supposed to.  However, it also, somehow, fires the RowCommand event AGAIN and this time cntAssign=1 and redirects to the wrong place....

 

by: prairiedogPosted on 2008-12-02 at 09:31:29ID: 23078941

Do you have anything in Assign.aspx that redirects back? I think more information is needed to pinpoint the problem.

 

by: rock815Posted on 2008-12-02 at 09:33:40ID: 23078964

No, nothing to redirect it back...  That's whats *odd* about the issue.  Even if I did redirect it back to Default.aspx it would still somehow need to fire the RowCommand event again.

It's like it runs RowCommand once, runs the proper redirect, then fires RowCommand a 2nd time.. ugh

 

by: prairiedogPosted on 2008-12-02 at 09:42:03ID: 23079029

Can I take a look at your complete RowCommand event handler?

 

by: rock815Posted on 2008-12-02 at 09:47:07ID: 23079066

This is OLD code, so please forgive all the *crap*... :)

NOTE:  The other CommandName's work fine...

Thanks for your time

    protected void dgStudents_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        int RIndex = Convert.ToInt32(e.CommandArgument);
        GridViewRow row = dgStudents.Rows[RIndex];
 
        string _studentid = row.Cells[0].Text;
        string _assignid = row.Cells[9].Text;
        string _userid = Master.UserID;
 
        if (e.CommandName == "AssignMe")
        {
            int cntAssign = Convert.ToInt32(SQLTasks.ExecuteScalar("SELECT dbo.fncStudentTaken('" + row.Cells[9].Text + "')"));
 
            if (cntAssign > 0)
            {
                Response.Redirect("~/Admin/Default.aspx?LocKey=" + _lockey + "&AlreadyTaken=yes");
            }
 
            SQLTasks.ExecuteNonQuery("UPDATE Assignments SET StaffAssignedto = '" + _userid + "', DateAssigned = GetDate() WHERE [id] = '" + _assignid + "'");
            Response.Redirect("~/Admin/Assign.aspx?id=" + _studentid + "&AssignmentID=" + _assignid + "&LocKey=" + _lockey);
        }
 
        if (e.CommandName == "NoShow")
        {
            string ip = (string)Request.ServerVariables["REMOTE_ADDR"];
            SQLTasks.ExecuteNonQuery("UPDATE Assignments SET LastActionIP = '" + ip + "', StaffAssignedto = '" + _userid + "', isNoShow = 1, isClosed = 1, DateClosed = GetDate() WHERE [id] = '" + _assignid + "'");
            Response.Redirect("~/Admin/Default.aspx?LocKey=" + _lockey);
        }
 
        if (e.CommandName == "TextPhone")
        {
            string SMSTo = row.Cells[10].Text + row.Cells[12].Text;
            SendSMS(SMSTo, row.Cells[7].Text);
            Response.Redirect("~/Admin/Default.aspx?LocKey=" + _lockey);
        }        
    }

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:

Select allOpen in new window

 

by: prairiedogPosted on 2008-12-02 at 10:02:06ID: 23079191

Hmmm, I don't see anything wrong with your code here.

 

by: rock815Posted on 2008-12-02 at 10:14:20ID: 23079290

I was afraid that might be your response.  Thanks for trying... :(  

If I put the breakpoint on the redirect(to assign.aspx) and step through with F11 all the way to the end, it works just like it should....

If I keep the breakpoint, but hit F5, it redirects goes to Assign.aspx and back to Default.aspx based on cntAssign=1 then redirects to the wrong page..... strange!

 

by: rock815Posted on 2008-12-02 at 10:26:08ID: 23079409

Threw it in a try / catch block and got this error on System.Threading.ThreadAbortException

Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.

try
            {
                Response.Redirect("~/Admin/Assign.aspx?id=" + _studentid + "&AssignmentID=" + _assignid + "&LocKey=" + _lockey);
            }
            catch (System.Threading.ThreadAbortException ex)
            {
                Response.Write(ex.ToString());
            }
            catch (Exception ex)
            {
                Response.Write(ex.ToString());
            }

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:

Select allOpen in new window

 

by: prairiedogPosted on 2008-12-02 at 10:31:06ID: 23079445

When you remove "true" from Response.Redirect, it will always throw ThreadingAbortException. It is a normal behavior for Response.Redirect, so you can ignore this type of exception error.

 

by: rock815Posted on 2008-12-02 at 10:33:39ID: 23079467

Bummer.  If I put "false" there, it doesn't throw an error, by design, but it also doesn't redirect properly

 

by: prairiedogPosted on 2008-12-02 at 10:34:12ID: 23079470

The strange thing is there has to be something to trigger the RowCommand event, it can't be executed all by itself.

 

by: rock815Posted on 2008-12-02 at 10:42:47ID: 23079539

I'm missing something because I put a breakpoint on it and it IS being called twice.  But I'm not sure how to determine what's calling it the 2nd time...

 

by: prairiedogPosted on 2008-12-02 at 10:55:27ID: 23079642

You got me, man. I am sorry.

 

by: rock815Posted on 2008-12-02 at 11:20:39ID: 23079864

Thanks to one of my co-workers, Steve, I was able to implement a "hack".

It's not pretty coding, but nonetheless it works.  I'm still baffled to why it's not working *properly* though..

Here is the code snippet.

I also put Session["hackbln"] = null; on the Page Load event of Assign.aspx.

protected void dgStudents_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        int RIndex = Convert.ToInt32(e.CommandArgument);
        GridViewRow row = dgStudents.Rows[RIndex];
 
        string _studentid = row.Cells[0].Text;
        string _assignid = row.Cells[9].Text;
        string _userid = Master.UserID;
 
        if (e.CommandName == "AssignMe")
        {
            int cntAssign = Convert.ToInt32(SQLTasks.ExecuteScalar("SELECT dbo.fncStudentTaken('" + row.Cells[9].Text + "')"));
 
            if (Session["hackbln"] == null)
            {
                Session["hackbln"] = "false";
            }
 
            if (cntAssign > 0 && !bool.Parse(Session["hackbln"].ToString()))
            {
                Session["hackbln"] = "false";
            }
            else
            {
                Session["hackbln"] = "true";
                SQLTasks.ExecuteNonQuery("UPDATE Assignments SET StaffAssignedto = '" + _userid + "', DateAssigned = GetDate() WHERE [id] = '" + _assignid + "'");
                //Response.Redirect("~/Admin/Assign.aspx?id=" + _studentid + "&AssignmentID=" + _assignid + "&LocKey=" + _lockey);
            }
 
            if (bool.Parse(Session["hackbln"].ToString()))
            {
                Response.Redirect("~/Admin/Assign.aspx?id=" + _studentid + "&AssignmentID=" + _assignid + "&LocKey=" + _lockey);
            }
            else
            {
                Response.Redirect("~/Admin/Default.aspx?LocKey=" + _lockey + "&AlreadyTaken=yes");           
            }
        }
 
        if (e.CommandName == "NoShow")
        {
            string ip = (string)Request.ServerVariables["REMOTE_ADDR"];
            SQLTasks.ExecuteNonQuery("UPDATE Assignments SET LastActionIP = '" + ip + "', StaffAssignedto = '" + _userid + "', isNoShow = 1, isClosed = 1, DateClosed = GetDate() WHERE [id] = '" + _assignid + "'");
            Response.Redirect("~/Admin/Default.aspx?LocKey=" + _lockey);
        }
 
        if (e.CommandName == "TextPhone")
        {
            string SMSTo = row.Cells[10].Text + row.Cells[12].Text;
            SendSMS(SMSTo, row.Cells[7].Text);
            Response.Redirect("~/Admin/Default.aspx?LocKey=" + _lockey);
        }        
    }

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:

Select allOpen in new window

 

by: prairiedogPosted on 2008-12-02 at 11:53:20ID: 23080155

but it doen't explain why the RowCommand event handler gets called twice. There has to be something triggers the event.

Just thought of one thing, is the GridView defined in Assign.aspx? In another word, is Response.Redirect("~/Admin/Assign.aspx") redirecting to itself?

 

by: rock815Posted on 2008-12-02 at 11:56:34ID: 23080180

Nope, it's not redirecting to itself.  :(

I just now changed Assign.aspx to actually handle the assignment in SQL (instead of the old way from the code above)....

But here is the Page Load Event

btnSave.Attributes.Add("onClick", "return confirm('This Student will be marked complete.  No other changes can be made after you save.  Continue?')");
        btnReturn.Attributes.Add("onClick", "return confirm('This will send the Student back to the Queue so another Representative can Assign them. Do you wish to continue?')");
        Response.ClearHeaders();
        Response.Clear();
        Response.AddHeader("cache-control", "no-cache");
        Response.AddHeader("Refresh", "");
        Session["hackbln"] = null;
 
        if (!IsPostBack)
        {
            string sql = "UPDATE Assignments SET StaffAssignedto = @AssignTo, DateAssigned = GetDate() WHERE [id] = @AssignId";
 
            Guid _uid = new Guid(Master.UserID);
            Guid _aid = new Guid(Request.QueryString["AssignmentId"].ToString());
 
            using (SqlConnection sqlconn = new SqlConnection(_conn))
            {
                SqlCommand cmd = new SqlCommand(sql, sqlconn);
                cmd.CommandType = CommandType.Text;
 
                cmd.Parameters.Add("@AssignTo", SqlDbType.UniqueIdentifier).Value = _uid;
                cmd.Parameters.Add("@AssignId", SqlDbType.UniqueIdentifier).Value = _aid;
 
                sqlconn.Open();
                cmd.ExecuteNonQuery();
            }
        }

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:

Select allOpen in new window

 

by: rock815Posted on 2008-12-09 at 09:12:55ID: 31521935

Never did find an end all be all solution to this, but the work around seemed to work for the time being.  I appreciate all your help!

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...