Hello im learning c# at the moment and wish to If a statement is true then redirect to another ASpage so far with no luck.
My attempt is below, what the code does is check the text boxes to see if they have a value and if they do then it will save that record in the database as a new user.The code works its just the redirect at the end that isn't working.
Any help would be great
protected void Button2_Click(object sender, EventArgs e)
{
if (!String.IsNullOrWhiteSpace(txtTitle.Text))
{
user.Title = txtTitle.Text;
}
if (!String.IsNullOrWhiteSpace(txtFirstName.Text))
{
user.Forename = txtFirstName.Text;
}
if (!String.IsNullOrWhiteSpace(txtSurname.Text))
{
user.Surname = txtSurname.Text;
}
if (!String.IsNullOrWhiteSpace(txtUsername.Text))
{
user.Username = txtUsername.Text;
}
// call save function at end of statements
if (!String.IsNullOrWhiteSpace(txtAddress.Text))
{
user.Address1 = txtAddress.Text;
}
if (!String.IsNullOrWhiteSpace(txtAddress2.Text))
{
user.Address2 = txtAddress.Text;
}
if (!String.IsNullOrWhiteSpace(txtPostcode.Text))
{
user.PostCode = txtPostcode.Text;
}
if (!String.IsNullOrWhiteSpace(txtCode.Text))
{
user.CountryCode = txtCode.Text;
}
if (!String.IsNullOrWhiteSpace(txtEmail.Text))
{
user.Email = txtEmail.Text;
}
//if (!string.IsNullOrWhiteSpace(txtDate.Text))
//{
// DateTime _entrydate;
// if (DateTime.TryParse(txtDate.Text, out _entrydate))
// {
// user.EntryDate = _entrydate;
// }
//}
user.CompanyID = AppSession.Company.ID;
user.Status = 1;
user.PasswordHash = "test";
user.EntryDate = DateTime.Now;
user.UpdateDate = DateTime.Now;
user.Deleted = false;
bool result = userDao.SaveNewUser(user);
if (result == true)
{
Response.Redirect("User/List/");
}
}
}
}
You need to Redirect to another ASPX page, not a directory.
Something like
Response.Redirect("User/List/UserList.aspx");
Private static string CheckValues(TextBox t)
{
if(!string.IsnullOrEmpty(t.Text.Trim())
{
return t.Text;
}
}
protected void Button2_Click(object sender, EventArgs e)
{
user.Title =CheckValues(txtTitle.Text);
user.Forename = CheckValues(txtFirstName.Text);
user.Surname = CheckValues(txtSurname.Text);
user.Username = CheckValues(txtUsername.Text);
user.Address1 = CheckValues(txtAddress.Text);
user.Address2 = CheckValues(txtAddress.Text);
user.PostCode = CheckValues(txtPostcode.Text);
user.CountryCode = CheckValues(txtCode.Text);
user.Email = CheckValues(txtEmail.Text);
if(CheckValues(txtDate.Text))
{
DateTime _entrydate;
if (DateTime.TryParse(txtDate.Text, out _entrydate))
{
user.EntryDate = _entrydate;
}
}
bool result = userDao.SaveNewUser(user);
if (result)
{
Response.Redirect("~/User/List/somepage"); //~ for root directory , if there is any page use that or use the exact url here.
}
}
Kindly note the above url format will only work if you have URL Rewriting/Routing in your app
Related
I'm trying with some code to disable/enable button based on user permission.
However, the code seem like nothing change to the system.
Anyone can advice/guide me on these? Thanks in advance.
public partial class frmTest : Form
{
public string UserID;}
private void frmTest_Load(object sender, EventArgs e)
{
RefreshActivate();
private void RefreshActivate()
{
DataSet ds = new DataSet();
MySQLClass.query(ds, "SELECT * FROM users WHERE username = '" + UserID + "'");
string strPermission = ds.Tables[0].Columns["permission"].ToString();
if (strPermission == "Admin")
{
btnActivate.Enabled = true;
}
else if (strPermission == "ReadOnly")
{
btnActivate.Enabled = false;
}
else
{
btnActivate.Enabled = false;
}
}}
Picture: https://i.stack.imgur.com/BevH8.png
Try to check first the permission if not null
if(!strPermission.Equals(null)//or ""
{
if (strPermission == "Admin")
{
btnActivate.Enabled = true;
}
else if (strPermission == "ReadOnly")
{
btnActivate.Enabled = false;
}
}else{
//value of permision is empty
MessageBox.Show("Permission is empty");
}
Now if the permission is empty it is something to do or fix when retrieving the data
i have this sets of code with setsession and getsession in it
protected void btnCall_Click(Object sender, EventArgs e)
{
if (isCallComplete())
{
Collection<Greeting> collGreeting = sessionHelper.GetSession("CurrentGreetingData") as Collection<Greeting>;
if (collGreeting.Count > 0)
{
Collection<CounterbySA> collCounterBySA = new ServiceFacade(User).SelectByFieldName<CounterbySA>("SAID", 106);//CurrentApplicationUser.id
if (collCounterBySA.Count > 0)
{
Counter counter = new ServiceFacade(User).SelectById<Counter>(collCounterBySA[0].CounterID);
Greeting greeting = collGreeting[0];
BoardQueue boardQueue = new BoardQueue();
boardQueue.BranchID = CurrentApplicationUser.BranchID;
boardQueue.CounterID = counter.ID;
boardQueue.SAID = 106; //CurrentApplicationUser.ID
boardQueue.PlatNumber = greeting.PlatNumber;
boardQueue.Status = (int)CallCustomerStatus.Open;
ResultStatus rs = new ServiceFacade(User).InsertBoardQueue(boardQueue);
voiceCall(string.Format("{0}di{1}", greeting.PlatNumber, counter.Name));
MessageBox.Show(string.Format("{0} Silahkan ke {1}", greeting.PlatNumber, counter.Name));
btnCall.Enabled = false;
btnReCall.Enabled = true;
btnComplete.Enabled = true;
sessionHelper.SetSession("CurrentCallData", boardQueue);
sessionHelper.SetSession("CurrentGreetingTemp", greeting);
}
else
{
MessageBox.Show("SA ini Belom terdaftar di Loket, Silahkan ke manu AssignSA untuk mendaftarkan/menempatkan SA ke Loket");
}
}
else
{
MessageBox.Show("Tidak Ada Customer Untuk Di panggil");
}
}
else if (isCurrentUser())
{
MessageBox.Show("sedang memanggil customer, click panggil ulang apabila customer belum datang");
btnCall.Enabled = true;
btnReCall.Enabled = true;
btnComplete.Enabled = true;
}
else
{
MessageBox.Show("SA lain sedang memanggil Customer, harap menunggu");
}
so if i click button call it will set the 2 session
and this where i get the session
protected void btnReCall_Click(Object sender, EventArgs e)
{
BoardQueue boardQueue = sessionHelper.GetSession("CurrentCallData") as BoardQueue;
if (boardQueue != null)
{
Counter counter = new ServiceFacade(User).SelectById<Counter>(boardQueue.CounterID);
voiceCall(string.Format("{0}di{1}", boardQueue.PlatNumber, counter.Name));
MessageBox.Show(string.Format("{0} Silahkan ke {1}", boardQueue.PlatNumber, counter.Name));
btnNext.Enabled = true;
}
else
{
MessageBox.Show("Harap Memanggil Customer terlebih Dahulu");
}
}
Before the page is refresh it works fine. but after the page refresh the session is gone.
i have done some research about this topic but i couldn't get the answer
Here are the get and set method for the session
public void SetSession(string sKey, object sValue)
{
HttpContext.Current.Session[sKey] = sValue;
AddSession(sKey, true);
}
public object GetSession(string sKey)
{
return ((object)(HttpContext.Current.Session[sKey]));
}
I am selecting a row from Gridview, working good except for checkbox, like I am assigning value of checkbox retreived from gridview to checkbox that is placed on web form but it isn't represented by checkbox on form, it shows empty checkbox in every case
if (gridviewDesignations.SelectedRow.Cells[5].Text == " ")
{
chkIsHead.Text = gridviewDesignations.SelectedRow.Cells[5].Text;
}
in short, checkbox is not picking value from gridview
Update:
tried this too:
CheckBox chkIsHead = (CheckBox) gridviewDesignations.SelectedRow.Cells[5].Controls[0];
if (chkIsHead.Checked == false)
{
chkIsHead.Checked = false;
}
else
{
chkIsHead.Checked = true;
}
Update:
my full code:
public partial class frmDesignations : System.Web.UI.Page
{
AccessibleVariables accessVariables = new AccessibleVariables(); //Used to access global variables
public void Clear(params TextBox[] txtBoxes)
{
foreach (TextBox txtbx in txtBoxes)
{
txtbx.Text = "";
}
}
public void fillddlDepartments()
{
ManageDepartmentsBizz mngDepBizz = new ManageDepartmentsBizz();
DataSet ds = (DataSet)mngDepBizz.SelectDepartments();
if (ds.Tables[0].Rows.Count != 0)
{
ddlDepartments.DataValueField = "DepID";
ddlDepartments.DataTextField = "DepName";
ddlDepartments.DataSource = ds.Tables[0];
// ddlDepartments.SelectedIndex = -1;
ddlDepartments.DataBind();
ddlDepartments.Items.Insert(0, "--Select--");
}
//else
// ddlDepartments.SelectedIndex = -1;
}
protected void Page_Load(object sender, EventArgs e)
{
if (Session.Count <= 0)
{
Response.Redirect("login.aspx");
}
lblMsgPopUp.Visible = false;
if (!IsPostBack)
{
fillddlDepartments();
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
try
{
int DepartmentID = Convert.ToInt32(ddlDepartments.SelectedValue);
bool IsHead = Convert.ToBoolean(chkIsHead.Checked);
DesignationsBizz DesigBizz = new DesignationsBizz(-1, txtTitle.Text, DepartmentID, txtContactNo.Text, IsHead);
//-1 is bogus,used to fill parameters criteria i.e no of params
ManageDesignationsBizz mngDesigBizz = new ManageDesignationsBizz();
bool Result = mngDesigBizz.Insert(DesigBizz);
if (Result == true)
{
HiddenFieldSetMessage.Value = "Saved";
HiddenFieldShowMessage.Value = "True";
Clear(txtTitle, txtSelectedID, txtContactNo);
}
else
{
HiddenFieldSetMessage.Value = "RecordAlreadyExists";
HiddenFieldShowMessage.Value = "True";
}
}
catch (Exception)
{
HiddenFieldSetMessage.Value = "NotSaved";
HiddenFieldShowMessage.Value = "True";
}
}
protected void btnSearchPopup_Click(object sender, EventArgs e)
{
string DesignationTitle = txtDesignationPopUp.Text;
ManageDesignationsBizz mngDepsBizz = new ManageDesignationsBizz();
DataSet ds = (DataSet)mngDepsBizz.Select(DesignationTitle);
if (ds.Tables[0].Rows.Count != 0)
{
lblMsgPopUp.Visible = false;
gridviewDesignations.DataSource = ds.Tables[0];
gridviewDesignations.DataBind();
gridviewDesignations.Visible = true;
}
else
{
lblMsgPopUp.Visible = true;
gridviewDesignations.Visible = false;
}
}
protected void gridviewDesignations_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
string DesignationTitle = txtDesignationPopUp.Text;
ManageDesignationsBizz mngDepBizz = new ManageDesignationsBizz();
DataSet ds = (DataSet)mngDepBizz.Select(DesignationTitle);
if (ds.Tables[0].Rows.Count != 0)
{
gridviewDesignations.PageIndex = e.NewPageIndex;
gridviewDesignations.DataSource = ds.Tables[0];
gridviewDesignations.DataBind();
gridviewDesignations.Visible = true;
}
}
protected void btnEdit_Click(object sender, EventArgs e)
{
if (gridviewDesignations.SelectedRow != null)
{
if (gridviewDesignations.SelectedRow.Cells[1].Text == " ")
{
txtSelectedID.Text = string.Empty;
}
else
{
txtSelectedID.Text = gridviewDesignations.SelectedRow.Cells[1].Text;
}
if (gridviewDesignations.SelectedRow.Cells[2].Text == " ")
{
txtTitle.Text = string.Empty;
}
else
{
txtTitle.Text = gridviewDesignations.SelectedRow.Cells[2].Text;
}
if (gridviewDesignations.SelectedRow.Cells[3].Text == " ")
{
ddlDepartments.SelectedValue = string.Empty;
}
else
{
ddlDepartments.SelectedValue = gridviewDesignations.SelectedRow.Cells[3].Text;
accessVariables.DepID = Convert.ToInt32(gridviewDesignations.SelectedRow.Cells[3].Text);
ViewState["depID"] = accessVariables.DepID;
}
if (gridviewDesignations.SelectedRow.Cells[4].Text == " ")
{
txtContactNo.Text = string.Empty;
}
else
{
txtContactNo.Text = gridviewDesignations.SelectedRow.Cells[4].Text;
}
CheckBox chkIsHead = (CheckBox) gridviewDesignations.SelectedRow.Cells[5].Controls[0];
if (chkIsHead.Checked == false)
{
chkIsHead.Checked = false;
}
else
{
chkIsHead.Checked = true;
}
gridviewDesignations.DataBind();
gridviewDesignations.SelectedIndex = -1;
HiddenFieldShowHideButtons.Value = "True";
}
}
protected void btnUpdatePopUp_Click(object sender, EventArgs e)
{
try
{
int id = Convert.ToInt32(txtSelectedID.Text);
int DepartmentID = Convert.ToInt32(ddlDepartments.SelectedValue);
bool IsHead = Convert.ToBoolean(chkIsHead.Checked);
DesignationsBizz DesigBizz = new DesignationsBizz(id, txtTitle.Text, DepartmentID, txtContactNo.Text, IsHead );
ManageDesignationsBizz mngDesigBizz = new ManageDesignationsBizz();
bool Result = mngDesigBizz.Update(DesigBizz);
if (Result == true)
{
HiddenFieldSetMessage.Value = "Updated";
HiddenFieldShowMessage.Value = "True";
Clear(txtSelectedID, txtTitle, txtContactNo);
}
else
{
HiddenFieldSetMessage.Value = "NotUpdated";
HiddenFieldShowMessage.Value = "True";
}
}
catch (Exception)
{
HiddenFieldSetMessage.Value = "NotUpdated";
HiddenFieldShowMessage.Value = "True";
}
}
protected void btnDeletePopUp_Click(object sender, EventArgs e)
{
try
{
int ID = Convert.ToInt32(txtSelectedID.Text.Trim());
ManageDesignationsBizz mngDepBizz = new ManageDesignationsBizz();
mngDepBizz.Delete(ID);
Clear(txtTitle, txtSelectedID, txtContactNo);
HiddenFieldSetMessage.Value = "Deleted";
HiddenFieldShowMessage.Value = "True";
}
catch (Exception)
{
HiddenFieldSetMessage.Value = "NotDeleted";
HiddenFieldShowMessage.Value = "True";
}
}
protected void btnClosePopup_Click(object sender, EventArgs e)
{
Clear(txtTitle, txtSelectedID, txtContactNo);
}
protected void ddlDepartments_SelectedIndexChanged(object sender, EventArgs e)
{
if (txtSelectedID.Text != "")
{
accessVariables.DepID = Convert.ToInt32(ddlDepartments.SelectedValue);
ViewState["depID"] = accessVariables.DepID;
}
else
{
accessVariables.DepID = Convert.ToInt32(ddlDepartments.SelectedValue);
ViewState["depID"] = accessVariables.DepID;
}
}
protected void chkIsHead_CheckedChanged(object sender, EventArgs e)
{
if (txtSelectedID.Text != "")
{
int DepID = Convert.ToInt32(ViewState["depID"]);
ManageDesignationsBizz mngDesig = new ManageDesignationsBizz();
bool isHead = mngDesig.SelectIsHeadExistsByDepID(DepID);
if (isHead == true)
{
HiddenFieldSetMessage.Value = "HeadExists";
HiddenFieldShowMessage.Value = "True";
chkIsHead.Checked = false;
}
}
else
{
int DepID = Convert.ToInt32(ViewState["depID"]);
ManageDesignationsBizz mngDesig = new ManageDesignationsBizz();
bool isHead = mngDesig.SelectIsHeadExistsByDepID(DepID);
if (isHead == true)
{
HiddenFieldSetMessage.Value = "HeadExists";
HiddenFieldShowMessage.Value = "True";
chkIsHead.Checked = false;
}
}
}
}
I believe the following is what you need to do:
Then select EditProgrammatically.
I'm not sure if yoou'll need to manually put data into the grid though but that won't be too hard. Examples can be seen here : http://msdn.microsoft.com/en-us/library/system.data.datatable(v=vs.110).aspx
PS : You can set the DataSource in the grid view to the DataTable.
My code is working fine if the statement (numtickets > tickav) is true (if tickets available is greater than tickets ordered) But if other wise, it throws in this error "FormatException was unhandled by user code, Input string was not in a correct format" on int numTick = Convert.ToInt32(txtNumberOfTickets.Text);
I do know that somehow I can use tryparse, i need help putting it in the code.
Any help would be appreciated, thank you
namespace TicketsApp
{
public partial class TicketOrder : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["description"] != null && Session["EventID"] != null && Session["numtickets"] != null && Session["ticketcost"] != null
&& Session["State"] != null && Session["Section"] != null && Session["Row"] != null && Session["date"] != null)
{
if (!IsPostBack)
{
try
{
txtEventDescription.Text = Session["description"].ToString();
txtEventID.Text = Session["EventID"].ToString();
txtTicketsAvailable.Text = Session["numtickets"].ToString();
txtTicketCost.Text = Session["ticketcost"].ToString();
txtState.Text = Session["State"].ToString();
txtSectionNumber.Text = Session["Section"].ToString();
txtRowNumber.Text = Session["Row"].ToString();
txtNumberOfTickets.Focus();
lblOutput.Visible = false;
}
catch
{
lblError.Text = "Please Search for Tickets First!";
lblError.Visible = true;
btnOrderTickets.Visible = false;
Response.Redirect("TicketSearch.aspx");
return;
}
}
}
}
protected void btnOrderTickets_Click(object sender, EventArgs e)
{
TicketsDataAccessDataContext NewOrder = new TicketsDataAccessDataContext();
int numTick = Convert.ToInt32(txtNumberOfTickets.Text);
string s = txtTotalCost.Text.Substring(1);
int totc = Convert.ToInt32(s);
int id = Convert.ToInt32(txtEventID.Text);
DateTime dt = Convert.ToDateTime(Session["date"]);
int returnedValue = NewOrder.PlaceOrderFull(id, txtEventDescription.Text, dt, Session["State"].ToString(), Session["section"].ToString(), Session["Row"].ToString(), numTick, totc, "vfateev");
if (returnedValue != 0)
{
lblOutput.Text = "Error has occured. Please try again";
lblOutput.Visible = true;
btnOrderTickets.Visible = false;
}
else
{
lblOutput.Visible = true;
lblOutput.Text = "Thank you";
btnOrderTickets.Visible = false;
}
}
protected void txtNumberOfTickets_TextChanged1(object sender, EventArgs e)
{
int cos = Convert.ToInt32(txtTicketCost.Text);
int numtickets = Convert.ToInt32(txtNumberOfTickets.Text);
int tickav = Convert.ToInt32(txtTicketsAvailable.Text);
if (numtickets > tickav)
{
lblError.Text = "Please Enter a valid ticket quantity";
lblError.Visible = true;
lblOutput.Text = "";
txtNumberOfTickets.Text = "";
}
else
{
int cost = cos * numtickets + 5;
txtTotalCost.Text = "$" + cost.ToString();
lblOutput.Visible = false;
lblFee.Text = "There is a $5 shipping fee";
lblFee.Visible = true;
lblError.Text = "";}
}
}
}
You can use int.TryParse which returns a boolean and does not throw an exception.
int numTick = 0;
bool result = int.TryParse(txtNumberOfTickets.Text, out numTick );
You can also do some client side validation to ensure that the field is filled in and contains a number.
Here is one of your methods rewritten using Int32.TryParse. I assumed you're doing txtTotalCost.Substring(1) to trim off the currency symbol. There are probably safe ways to do this, I'm just going to trim "$" for this example.
protected void btnOrderTickets_Click(object sender, EventArgs e)
{
int numberOfTickets, ticketCost, eventId;
if(Int32.TryParse(txtNumberOfTickets.Text, out numberOfTickets) &&
Int32.TryParse(txtTotalCost.Text.TrimStart('$'), out ticketCost) &&
Int32.TryParse(txtEventID.Text, out eventId))
{
DateTime dt = Convert.ToDateTime(Session["date"]);
TicketsDataAccessDataContext NewOrder = new TicketsDataAccessDataContext();
int returnedValue = NewOrder.PlaceOrderFull(eventId, txtEventDescription.Text, dt, Session["State"].ToString(), Session["section"].ToString(), Session["Row"].ToString(), numberOfTickets, ticketCost, "vfateev");
if (returnedValue != 0)
{
lblOutput.Text = "Error has occured. Please try again";
lblOutput.Visible = true;
btnOrderTickets.Visible = false;
}
else
{
lblOutput.Visible = true;
lblOutput.Text = "Thank you";
btnOrderTickets.Visible = false;
}
}
else
{
lblOutput.Visible = true;
lblOutput.Text = "Some validation error message here...";
}
}
You will need to make similar modifications to txtNumberOfTickets_TextChanged1 to ensure the user has entered valid text.
simply use something like
To use IsNumeric in C#, add a reference to Microsoft.VisualBasic.dll then
if (Information.IsNumeric(value))
{
DoSomthing();
}
else
{
DoSomethingElse();
}
UPDATE
OPEN VISUAL STUDIO ==> YOUR PROJECT
Click on solution and add reference, choose Microsoft.VisualBasic.dll confrim the new reference will be add to your references into the project.
Go at the top of your page and declare the import statemnet for Microsoft.VisualBasic.dll alias
using Microsoft.VisualBasic.dll;
then where you need to check the value of your textbox
if (Information.IsNumeric(yourtextbox.text.trim()))
{
//case true alias your value is numeric
//do what you need here like assing value to a var or any
//else
}
else
{
//put your logic here in case result is false and value
//is not numeric
}
I have created a contact form using c# and web services. I would like to get an alert message if the user hasn't filled his name or when his name is a number. This is my C# code:
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Validation.WebService validate = new Validation.WebService();
bool ismail = validate.isEmail(TextBox2.Text);
if (!ismail)
{ Label1.Text = "your mail is wrong!!"; }
Validation.nameVal valid = new Validation.nameVal();
bool isname = valid.isName(TextBox1.Text);
if (!isname )
{ Label2.Text = "Your name is wrong!!"; }
else if (isname==null)
{ Label2.Text = "Please fill in your name"; }
if (isname && ismail)
{
{ Label1.Text = null; Label2.Text = null;
Label3.Text = "Your message has been send!";}
}
}
}
With this code, I have a null exception.
From your comment that the exception is on the line:
bool isname = valid.isName(TextBox1.Text);
then either valid or TextBox1 is null. Given that the line before is:
Validation.nameVal valid = new Validation.nameVal();
this points to it being the latter.
You need to check that TextBox1 isn't null before de-referencing it or make sure that it is initialised correctly.
Try changing the last bit of the code where you set Label1.Text and Label2.Text to null to:
Label1.Text = String.Empty; Label2.Text = String.Empty;
I am guessing that perhaps the validate is failing, or, possibly the setting of the label text to null is causing the issues. The code below should help
Validation.WebService validate = new Validation.WebService();
bool ismail = (!string.IsNullOrEmpty(Textbox2.Text)) && validate.isEmail(TextBox2.Text);
if (!ismail)
{
Label1.Text = "your mail is wrong!!";
}
Validation.nameVal valid = new Validation.nameVal();
bool isname = (!string.IsNullOrEmpty(Textbox1.Text)) && valid.isName(TextBox1.Text);
if (!isname)
{
Label2.Text = "Your name is wrong!!";
}
else if (string.IsNullOrEmpty(Textbox1.Text))
{
Label2.Text = "Please fill in your name";
}
if (isname && ismail)
{
{
Label1.Text = "";
Label2.Text = "";
Label3.Text = "Your message has been send!";
}
}
}