Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to fire up onClick event from a button

Status
Not open for further replies.

BunBo900

MIS
Dec 11, 2009
50
US
I am trying to maintain this site unfortunately I have very basic asp.net experience. I have a simple question for most of you.

The following code on the course.aspx.cs code behind page. The way this code designed is there is a button (btnAddToQueue.Text)
on the pop-up modal message type when that button is clicked it's fired up the (btnAddToQueue_OnClick) event below. However, it doesnot seem to be doing that. I am not sure if it is being called correctly. if not, how do I make it to fire up the (btnAddToQueue_OnClick) event when clicked on the (Add To Queue) button? Thanks


public void gvCourses_OnRowCommand(object sender, GridViewCommandEventArgs e)
{

switch (commandName.ToLower())
{
case "alternate":

break;

case "queue":

btnAddToQueue.Text = "Add To Queue"; <--click on this button
lbtnQueueClose.Text = "Exit";
modalQueue.Show();

case "download":

break;

}

}
catch(Exception ex)
{
err = "Message: gvCourses_onRowCommand: " + ex.Message + "InnerException:" + ex.InnerException;

}
}
}


protected void btnAddToQueue_OnClick(object sender, EventArgs e) <---fire this event
{
try
{
qCourseId = (string)Session["courseId"];
qCourseTitle = (string)Session["courseTitle"];
studentAccessContent.addCourseToQueue(studentId, qCourseId, qCourseTitle, DateTime.Today.AddDays(90), 0);
lbMessage.Text = qCourseTitle + " course has been added to your Queue";
modalMessage.Show();
}
catch (Exception ex)
{
err = "Message: btnAddToQueue_OnClick: " + ex.Message + "InnerException:" + ex.InnerException;
}
}
 
assuming the button is not within the grid view the button's on click event needs to be wired to the handler. I thought webforms could do this automatically with naming conventions.

if not you can add
Code:
protected override void OnInit(EventArgs e)
{
   base.OnInit(e);
   btnAddToQueue.Click += btnAddToQueue_OnClick;
}

if the button is within the datagrid then you must explicitly wire the handler to the event when the button is instantiated. usually the rowdatabound or rowcreated event.
Code:
var button = row.FindControl("btnAddToQueue") as Button;
if(button != null)
{
   btnAddToQueue.Click += btnAddToQueue_OnClick;
}

one other note. there is a lot of clean up that can be done with error handling.
1. remove all the try catch statements
2. create a handler for the page error event.
3. use exception.ToString() to capture the full stack trace.
from there you can log/display/etc. the exception for debugging.

or let exceptions bubble up to the application level and handle them in the Global.Error event. after all exceptions are exceptional and typically you want to stop execution when an error occurs.

Jason Meckley
Programmer

faq855-7190
faq732-7259
 
2. create a handler for the page error event.
3. use exception.ToString() to capture the full stack trace.

Where do I create all this error event/exception in the aspx page or aspx.cs?
Can you give example on this?

Thank you.
 
the aspx is the markup. it's the template for were to put data and what to redner. the aspx.cs/vb in the code behind. this is where you put code that provides data to the template or gets information from the template.

there are a number of examples on the web about wiring up events, the webforms page life cycle and such. you can just as easily use the OnError method.

here is one example where the log4net library will log the details and the user gets a friendly message.
Code:
class MyPage : Page
{
   ... your code goes here

   private static readonly ILog logger = LogManager.GetLogger(typeof(MyPage));

   protected override void OnError(EventArgs e)
   {
      var exception = Server.GetLastException();
      logger.Error(exception.Message, exception);

      SomeLabel.Text = "Oops! An error was encountered, but don't worry were on it.";
   }
}
you can then drop the try/catch blocks from the rest of your code. you can take this a step further and put similar code in the global.asax Error event to log the exception and redirect the user to an error page
Code:
class Global : HttpApplication
{
   private static readonly ILog logger = LogManager.GetLogger(typeof(Global));

   protected Global()
   {
      Error += (sender, e) =>
      {
         var exception = Server.GetLastException();
         logger.Error(exception.Message, exception);

         var response = HttpContext.Current.Response;
         response.Redirect("~/genericerror.html", true);
      };
}


Jason Meckley
Programmer

faq855-7190
faq732-7259
 
I need to create number 1,2 above because of removing the try/catch statements in the code?


Thanks.
 
we are getting off topic. I would suggest getting your current issue, button click event, addressed. then you can tackle error handling, if it's required or you have time.

to answer your question. either example above would work. and the purpose is to write cleaner, more concise code. nothing about having to do it one way or the other.

also, don't be afraid to fork or create a new project/solution and try out different techniques. if you find one that works, you can integrate these changes back into your main application.

Jason Meckley
Programmer

faq855-7190
faq732-7259
 
I changed the code around and now I am able to add to the table, but generates different error messages.

Message: btnSubmit_OnClick: Object reference not set to an instance of an object.InnerException:
 
because the object is not instantiated, it doesn't exist. check for null before proceeding. also post the entire exception, not just the message. this will give you details into why/where the error occurs.

Jason Meckley
Programmer

faq855-7190
faq732-7259
 
This is how it works. When a student clicks on the enroll button from aspx page, it fires up the enroll case that is how I get the above error message. Thanks.


---------code behind CS file-----------

public void gvCourses_OnRowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
lbltext.Text += " RowCommand";
string args = e.CommandArgument.ToString();
string crsprgId, courseId, courseTitle, mediaType, filename;
string[] str = args.Split('|');

string commandName = e.CommandName;
string errorMessage = String.Empty;
studentObj = new Student(mciId, Student.IDType.MCI_ID);

Session["commName"] = commandName.ToLower();


switch (commandName.ToLower())
{
case "alternate":

crsprgId = str[0];
courseId = str[1];

courseTitle = str[2];
mediaType = str[3];
lbltext.Text += " inside alernate";
enrollCourse(mediaType, courseId);
break;
case "enroll":

courseId = str[0];

courseTitle = str[1];
mediaType = str[2];
lbltext.Text += " inside enroll";
enrollCourse(mediaType, courseId);

break;

case "queue":

courseId = str[0];
courseTitle = str[1];
mediaType = str[2];
lbSelectedCourse.Text = courseTitle;
Session["courseId"] = courseId;

int coursesEnrolledIn = 0;
lbAdded.Text = "Selected Course: " + courseTitle;
studentAccessContent sContentObj = new studentAccessContent();

DataSet dsEnrolled = studentObj.CoursesEnrolled();
if (dsEnrolled.Tables.Count != 0)
{
DataTable dtEnrolled = dsEnrolled.Tables[0];
if (dtEnrolled != null)
coursesEnrolledIn = dtEnrolled.Rows.Count;
}

if (coursesEnrolledIn < 3)
{
lbQueueMessage.Text = "You are not at your maximum enrollment. To enroll now click 'close' and then the 'enroll' button.";
lbtnQueueClose.Text = "Close";
btnAddToQueue.Visible = false;
}
else
{
lbQueueMessage.Text = "I understand that by placing this course into the Course Queue, I will be <b>automatically</b> enrolled into the course as soon as I become eligible for enrollment. I will be enrolled into the course <b>without any</b> materials(textbook, exam, etc). To be eligible for automatic enrollment, I must successfully complete my last course.<br><br>I have read and understand the terms stated above.";

btnAddToQueue.Text = "Add To Queue";
lbtnQueueClose.Text = "Exit without placing Course into Queue";
btnAddToQueue.Visible = true;
}
Session["courseId"] = courseId;
Session["courseTitle"] = courseTitle;
modalQueue.Show();
break;

case "download":
filename = str[1];
Response.Redirect("download.aspx?FILE=" + filename);
break;
case "course":
GridViewRow row = (GridViewRow)((LinkButton)e.CommandSource).Parent.Parent;
Label lbCourseId = (Label)row.Cells[0].FindControl("lbCourseId");
LinkButton lbtnCourseTitle = (LinkButton)row.Cells[1].FindControl("lbtnCourseTitle");

foreach (GridViewRow gRow in gvCourses.Rows)
{
LinkButton lbtn = (LinkButton)gRow.Cells[1].FindControl("lbtnCourseTitle");
if (lbtn != null)
{
Panel pnl = (Panel)gRow.FindControl("pnlInfo");
HiddenField hf = (HiddenField)pnl.FindControl("hfStatus");
if (lbtn.CommandArgument.ToString() == e.CommandArgument.ToString())
{

if (hf != null)
{
if (hf.Value.ToString().Equals("close"))
{
pnl.Visible = true;
hf.Value = "open";
}
else if (hf.Value.ToString().Equals("open"))
{
pnl.Visible = false;
hf.Value = "close";
}
}
}
else
{
pnl.Visible = false;
hf.Value = "close";
}
}
}

break;
}
}
catch (Exception ex)
{
err = "Message: gvCourses_onRowCommand: " + ex.Message + "InnerException:" + ex.InnerException;

}
}
 
start by removing the try catch block. when the error occurs should get the YSOD (yellow screen of death) this will give you all kinds of information as to what happened and where. it's basically a 'pretty' stack trace. with this information you can go to the line of code causing the problem and correct the error.

the other option is to set a break point at the first line of code in your row command and step through the code. when the exception is thrown, stop the debugger, correct the code, test again.

there is also a great deal of room for improving the maintainability and readability of the code, but that can wait for another post. first we should get this working.

Jason Meckley
Programmer

faq855-7190
faq732-7259
 
Hey Jason -

I was able to make this to work.

Thanks for your time and input.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top