Handling Exception is ASP.NET Webforms using Custom validator - c#

Im having a problem handing an exception in ASP.net WebForms(i'm a beginner)
i want to display the error in the webform using CustomValidator but with no luck, below is my code.
protected void dvEmployeeList_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
GridViewRow rowSelect = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
int rowindex = rowSelect.RowIndex;
string confirmValue = Request.Form["confirm_value"];
if (confirmValue == "Yes")
{
try
{
int empID;
empID = int.TryParse(dvEmployeeList.DataKeys[rowindex].Value.ToString(), out empID) ? empID : 0;
oEmployeeBLL.DeleteEmployee(empID);
dvEmployeeList.DataSource = oEmployeeBLL.GetEmployeeList();
dvEmployeeList.DataBind();
}
catch (Exception ex)
{
var delConstrainsVal = new CustomValidator();
delConstrainsVal.IsValid = false;
delConstrainsVal.ErrorMessage = "Update failed: " + ex.Message;
delConstrainsVal.Text = delConstrainsVal.ErrorMessage;
Page.Validators.Add(delConstrainsVal);
}
}
else
{
this.Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('User cancel!')", true);
}
}
it catch the exception but didnt display the message on the on the form.
Please guide me, thanks!

Validators are meant to validate user input, not to display server errors. You should consider using a simple <asp:Label>.
The reason why the error doesn't appear is probably because validation happens before the control is added.

Related

Retrieve data datagrid to form

I have created a form to insert data. When data inserted it shows into datagridview1. I use dataGridView1_MouseClick event to retrieve data into the form. I successfully retrieved textbox data only into my form. I want to retrieve checkbox value which is checked or not. How can i retrieve checkbox value by clicking dataGridView1_MouseClick event.
I use following code for that:
private void dataGridView1_MouseClick(object sender, MouseEventArgs e)
{
try
{
txtID.Text = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
Name.Text = dataGridView1.SelectedRows[0].Cells[1].Value.ToString();
}
catch (ApplicationException ex)
{
MessageBox.Show("Error: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
}
}
My result is here
But I want like this:
U can retrive values of other fields in similar like u did
This is for WPF control Checkbox link
I assume checkbox name of movie is movie_chbox
movie_chbox.IsChecked =
dataGridView1.SelectedRows[0].Cells[3].Value.toString() == "1" ?true:false
Similarly you can do same for other too.
This is for winforms control Checkbox link
movie_chbox.Checked =
dataGridView1.SelectedRows[0].Cells[3].Value.toString() == "1" ?true:false
Instead of displaying 0 or 1 in datagridview display "Interested"/"Not Interested" and when you insert/update to database that time insert/update as 0 or 1 for better database mentainance.
Use the checked property of the check box control in your code and change the code for different categories. In your case the final code will be be something like below:
private void dataGridView1_MouseClick(object sender, MouseEventArgs e)
{
try
{
txtID.Text = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
txtName.Text = dataGridView1.SelectedRows[0].Cells[1].Value.ToString();
string isCheckedMovie = dataGridView1.SelectedRows[0].Cells[2].Value.ToString();
string isCheckedSports = dataGridView1.SelectedRows[0].Cells[3].Value.ToString();
string isCheckedReading = dataGridView1.SelectedRows[0].Cells[4].Value.ToString();
string isCheckedWriting = dataGridView1.SelectedRows[0].Cells[5].Value.ToString();
if (isCheckedMovie == "1")
movieBox.Checked = true;
else
movieBox.Checked = false;
if (isCheckedSports == "1")
sportsBox.Checked = true;
else
sportsBox.Checked = false;
if (isCheckedReading == "1")
readingBox.Checked = true;
else
readingBox.Checked = false;
if (isCheckedWriting == "1")
writingBox.Checked = true;
else
writingBox.Checked = false;
}
catch (ApplicationException ex)
{
MessageBox.Show("Error: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
}

DotNetNuke WebForm Alert Dialog box

I am currently developing a DotNetNuke module. However, I failed to prompt user an alert dialog box in certain situations like record duplication.
I am using the following code to display an alert box in Controller class.
EditForm edForm = new EditForm();
ScriptManager.RegisterClientScriptBlock(edForm, edForm.GetType(), "alertMessage", "alert('Record Inserted Successfully')", true);
The following is my full code.
Form.ascx.cs
void cmdUpdate_Click(object sender, EventArgs e)
{
UdtController.UpdateRow(Data, ModuleId, False);
}
UdtController.cs
public void UpdateRow(DataSet ds, int rowNr, bool isDataToImport)
{
var values = new Dictionary<int, string>();
string strIsUnique = "";
foreach (DataRow field in ds.Tables[DataSetTableName.Fields].Rows)
{
var strColumnName = field[FieldsTableColumn.Title].ToString();
strIsUnique = field[FieldsTableColumn.Searchable].ToString();
var strValueColumn = ((!isDataToImport &&
ds.Tables[DataSetTableName.Data].Columns.Contains(strColumnName +
DataTableColumn.
Appendix_Original))
? strColumnName + DataTableColumn.Appendix_Original
: strColumnName);
if (strIsUnique == "True")
{
int uniqueDataCount = FieldController.uniqueData(currentRow[strValueColumn].AsString());
if (uniqueDataCount == 0)
{
if (ds.Tables[DataSetTableName.Data].Columns.Contains(strValueColumn))
{
values.Add(field[FieldsTableColumn.Id].AsInt(), currentRow[strValueColumn].AsString());
}
}
else
{
EditForm edForm = new EditForm();
ScriptManager.RegisterClientScriptBlock(edForm, edForm.GetType(), "alertMessage", "alert('Record Inserted Successfully')", true);
break;
}
}
else
{
if (ds.Tables[DataSetTableName.Data].Columns.Contains(strValueColumn))
{
values.Add(field[FieldsTableColumn.Id].AsInt(), currentRow[strValueColumn].AsString());
}
}
}
FieldController.UpdateData(userDefinedRowId, values);
}
You need to reference the Page, not create a new form.
Page page = HttpContext.Current.CurrentHandler as Page;
ScriptManager.RegisterStartupScript(page, page.GetType(), "alertMessage", "alert('Record Inserted Successfully')", true);
However DNN has it's own message box you could use:
http://uxguide.dotnetnuke.com/UIPatterns/AlertDialog.html

Prepopulated Form causing issues for DbContext.SaveChanges()

After doing lots of debugging, I've narrowed down as to why my dbContext update does not work.
I have a script that runs on Page_Load that will populate a form based on the query string category_Id which is the primary key of my table.
protected void Page_Load(object sender, EventArgs e)
{
// Populate Edit Fields
if (Request.QueryString["categoryId"] != null)
{
CategoryDAL categoryDAL = new CategoryDAL();
RecipeCategory myCategory = new RecipeCategory();
try
{
addDiv.Attributes["class"] = "hidden";
editDiv.Attributes["class"] = "display";
int categoryToGet = Convert.ToInt32(Request.QueryString["categoryId"]);
myCategory = categoryDAL.GetCategory(categoryToGet);
tbEditCategoryName.Text = myCategory.Category_Name;
tbEditCategoryDescription.Text = myCategory.Description;
ddlEditCategoryGroupList.SelectedValue = Convert.ToString(myCategory.CatGroup_Id);
ddlEditCategoryGroupList.DataBind();
}
catch(Exception ex)
{
updateStatus.Attributes["class"] = "alert alert-info alert-dismissable fade in";
updateStatus.Visible = true;
lblStatus.Text = "Could not get Category Info, please try again.";
}
}
This is my script that runs when the edit_Button is clicked, it should update the row in the database and redirect to the viewCategories page.
protected void btnEditCategory_Click(object sender, EventArgs e)
{
if (Request.QueryString["categoryId"] != null)
{
CategoryDAL categoryDAL = new CategoryDAL();
RecipeCategory myCategory = new RecipeCategory();
try
{
int categoryToEdit = Convert.ToInt32(Request.QueryString["categoryId"]);
myCategory.Category_Name = tbEditCategoryName.Text;
myCategory.Description = tbEditCategoryDescription.Text;
myCategory.CatGroup_Id = Convert.ToInt32(ddlEditCategoryGroupList.SelectedValue);
try
{
bool editStatus = categoryDAL.EditCategory(categoryToEdit, myCategory);
if (editStatus)
{
HttpContext.Current.Session["editStatus"] = "Successful";
Response.Redirect("~/Admin/ManageCategories.aspx");
}
else
{
lblEditStatus.Text = "Unable to update category, please try again";
lblEditStatus.CssClass = "alert-danger";
}
}
catch (Exception ex)
{
lblEditStatus.Text = Convert.ToString(ex);
lblEditStatus.CssClass = "alert-danger";
}
}
catch (Exception ex)
{
updateStatus.Attributes["class"] = "alert alert-info alert-dismissable fade in";
updateStatus.Visible = true;
lblStatus.Text = "Invalid categoryId.";
}
}
else
{
updateStatus.Attributes["class"] = "alert alert-info alert-dismissable fade in";
updateStatus.Visible = true;
lblStatus.Text = "Nothing to update.";
}
}
And this is in my DALayer which holds the functions that has anything to do with categories.
public bool EditCategory(int categoryToEdit, RecipeCategory newCategoryInfo)
{
RecipeXchangeDBContext dbContext = new RecipeXchangeDBContext();
RecipeCategory myCategory = new RecipeCategory();
bool status = false;
myCategory = (from c in dbContext.RecipeCategories
where c.Category_Id == categoryToEdit
select c).First();
myCategory.Category_Name = newCategoryInfo.Category_Name;
myCategory.Description = newCategoryInfo.Description;
myCategory.CatGroup_Id = newCategoryInfo.CatGroup_Id;
try
{
if (dbContext.SaveChanges() == 1)
status = true;
else
status = false;
}
catch (InvalidOperationException ex)
{
status = false;
}
return status;
}
For some reason, whenever I try to update a row with a prepopulated form, the code will always return 0 from dbContext.SaveChanges() and does not update the row in the database.
Note: if I do not populate the form, it works perfectly as normal.
Page_Load doesn't just run the first time the page is loaded, it runs every time the page is loaded, including when the user submits the form. The result is that you're overwriting the user's input before saving it.
In this case, since you're using regular browser navigation to go to a specific category page, you can just check Page.IsPostBack in Page_Load and not set anything in that case.

Not able to catch user identity on windows 10 in vs2015

I'm trying to catch user identity but not able to catch it.
I turned windows features on or off and update Windows authentication,
but still not able to catch the login ID.
Any idea would be appreciated.
c# code
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string uid = "";
try { uid = Session["uid"].ToString(); }
catch { uid = ""; }
if (uid == "" || uid == null)
{
uid = Page.User.Identity.Name;
if (uid.Length > 0)
{
uid = uid.Substring(10);
}
}
}
}

C# Catching exception

Am quite new to this, so please help.
I have the following image clicked code.
However, an error will occur if the user does not click on a image.
How can i do an error check to catch that if the user does not click on an image and attempts to proceed, a messagebox will display notifying him to click an image.
Error msg: The error is at "ListViewItem selectedItem = listView1.SelectedItems[0] Error Msg: Invalid Argument = Value of '0' is not valid for 'index
Below is my code:
private void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
int i = e.ProgressPercentage;
object fbUserObject = e.UserState;
if (fbUserObject is DataRow)
{
var fbUser = fbUserObject as DataRow;
var item = new ListViewItem(fbUser["friend_name"].ToString());
item.Tag = fbUser["friend_id"];
item.ImageIndex = i;
listView1.Items.Add(item);
}
else if (fbUserObject is Image)
{
imageList.Images.Add(fbUserObject as Image);
}
}
private void imageClicked(Object sender, System.EventArgs e)
{
ListViewItem selectedItem = listView1.SelectedItems[0];
selectedFBId = selectedItem.Tag as string;
selectedFBName = selectedItem.Text;
DialogResult dialogA = MessageBox.Show("Analyse employee data?", "SOC", MessageBoxButtons.YesNo);
if (dialogA == DialogResult.Yes)
{
TargetEmployee.Text = "Selected Target: " + selectedFBName;
pf.Show();
ThreadPool.QueueUserWorkItem(LoadUserDetails);
}
}
You shouldn't catch an exception, you should handle when there aren't any selected items
if(listView1.SelectedItems.Count == 0)
{
MessageBox.Show(this, "No image");
return;
}
Exceptions should be caught when you don't expect something to happen, if you are aware of a possible issue, you should handle that before it becomes an issue
change your code like this
private void imageClicked(Object sender, System.EventArgs e)
{
if(listView1.SelectedItems.Count < 1)
return;
ListViewItem selectedItem = listView1.SelectedItems[0];
selectedFBId = selectedItem.Tag as string;
selectedFBName = selectedItem.Text;
DialogResult dialogA = MessageBox.Show("Analyse employee data?", "SOC", MessageBoxButtons.YesNo);
if (dialogA == DialogResult.Yes)
{
TargetEmployee.Text = "Selected Target: " + selectedFBName;
pf.Show();
ThreadPool.QueueUserWorkItem(LoadUserDetails);
}
}
You can use a try { } catch { } statement for your error handling.
Once you locate the line of code that generates an exception, you can wrap it into a block like this
try
{
int a = int.Parse("pedantic"); // This throws an error because you cannot convert
}
catch (Exception e)
{
// Handle your error here instead of crashing your program
}

Categories