I am in a C# class and have been stuck all day trying to get this, I have tried it a bunch of different ways.
We are working with session state I have 5 fields that I need to record to session state, validate to make sure they are not empty, if they are change the filed to yellow and then display a message to a label stating what filed or fields where left blank and they they cannot be blank.
I have it working except for the message part.
I tried using the same variable errMsg in all 5 if statements trying to string them together using the + sign but that would not work.
Now I have defined a variable for each of the 5 if statements and then towards the bottom combining them to display the message for each filed left blank, and now I just get error:
Use of unassigned local variable
Here is my code I have been working on this most of the day I know it is basic but not sure how to get these individual messages to display to the label if there fields are blank.
Thanks.
protected void btnSubmit_Click(object sender, EventArgs e)
{
//Assigning our form data so session state values
Session["txtFirstName"] = txtFirstName.Text;
Session["txtLastName"] = txtLastName.Text;
Session["txtPayRate"] = txtPayRate.Text;
Session["txtStartDate"] = txtStartDate.Text;
Session["txtEndDate"] = txtEndDate.Text;
string errFN;
string errLN;
string errPD;
string errSD;
string errED;
//Validation of each session state making sure they are not empty
//(probably a better way to do this but what I came up with)
if(string.IsNullOrEmpty(txtFirstName.Text))
{
txtFirstName.BackColor = System.Drawing.Color.Yellow;
errFN = Convert.ToString("First Name may not be empty.");
}
if(string.IsNullOrEmpty(txtLastName.Text))
{
txtLastName.BackColor = System.Drawing.Color.Yellow;
errLN = Convert.ToString("Last Name may not be empty.");
}
if(string.IsNullOrEmpty(txtPayRate.Text))
{
txtPayRate.BackColor = System.Drawing.Color.Yellow;
errPD = Convert.ToString("Pay Rate may not be empty.");
}
if(string.IsNullOrEmpty(txtStartDate.Text))
{
txtStartDate.BackColor = System.Drawing.Color.Yellow;
errSD = Convert.ToString("Start Date may not be empty.");
}
if(string.IsNullOrEmpty(txtEndDate.Text))
{
txtEndDate.BackColor = System.Drawing.Color.Yellow;
errED = Convert.ToString("End Date may not be empty.");
}
if (string.IsNullOrEmpty(txtFirstName.Text) || string.IsNullOrEmpty(txtLastName.Text) || string.IsNullOrEmpty(txtPayRate.Text) ||
string.IsNullOrEmpty(txtStartDate.Text) || string.IsNullOrEmpty(txtEndDate.Text))
{
lblError.Text = errFN + errLN + errPD + errSD + errED;
}
else
{
Response.Redirect("~/frmPersonalVerified.aspx");
}
}
Use of unassigned local variable is because of here
lblError.Text = errFN + errLN + errPD + errSD + errED;
you use an unsigned variable if there's no error.
you should initialize your variables like this
string errFN = System.String.Empty;
string errLN = System.String.Empty;
string errPD = System.String.Empty;
or
string errSD = "";
string errED = "";
So if there's no error, the variable will be initialized and empty
1.you need to Trim the values before comparing for Empty Check.
sometimes whitespaces (which will not be visible on TextBox) does not match with Empty string
2.you need to always assign the local variables.
Try this Code:
protected void btnSubmit_Click(object sender, EventArgs e)
{
//Assigning our form data so session state values
Session["txtFirstName"] = txtFirstName.Text;
Session["txtLastName"] = txtLastName.Text;
Session["txtPayRate"] = txtPayRate.Text;
Session["txtStartDate"] = txtStartDate.Text;
Session["txtEndDate"] = txtEndDate.Text;
string errFN="";
string errLN="";
string errPD="";
string errSD="";
string errED="";
//Validation of each session state making sure they are not empty
//(probably a better way to do this but what I came up with)
if(txtFirstName.Text.ToString().Trim().Equals(""))
{
txtFirstName.BackColor = System.Drawing.Color.Yellow;
errFN = Convert.ToString("First Name may not be empty.");
}
if(txtLastName.Text.ToString().Trim().Equals(""))
{
txtLastName.BackColor = System.Drawing.Color.Yellow;
errLN = Convert.ToString("Last Name may not be empty.");
}
if(txtPayRate.Text.ToString().Trim().Equals(""))
{
txtPayRate.BackColor = System.Drawing.Color.Yellow;
errPD = Convert.ToString("Pay Rate may not be empty.");
}
if(txtStartDate.Text.ToString().Trim().Equals(""))
{
txtStartDate.BackColor = System.Drawing.Color.Yellow;
errSD = Convert.ToString("Start Date may not be empty.");
}
if(txtEndDate.Text.ToString().Trim().Equals(""))
{
txtEndDate.BackColor = System.Drawing.Color.Yellow;
errED = Convert.ToString("End Date may not be empty.");
}
if (txtFirstName.Text.ToString().Trim().Equals("") || txtLastName.Text.ToString().Trim().Equals("") || txtPayRate.Text.ToString().Trim().Equals("") ||
txtStartDate.Text.ToString().Trim().Equals("") || txtEndDate.Text.ToString().Trim().Equals(""))
{
lblError.Text = errFN + errLN + errPD + errSD + errED;
}
else
{
Response.Redirect("~/frmPersonalVerified.aspx");
}
}
Related
I have a gridview in which every row contains a checkbox for selection. That selection will be used for Approve or Reject purpose.
But issue here is If I select 2 rows from the gridview it loops atleast 4-5 times and gives me multiple emails of the same row.
Below is my code. Please suggest.
protected void btnApproveCMM_Click(object sender, EventArgs e)
{
string strDate = "";
string strMailContent = "";
DataTable dtApprove = new DataTable();
CommonDB ObjDB = new CommonDB();
try
{
bool flgCMM = false;
IPColoFields ObjIPColoFields = new App_Code.IPColoFields();
List<IPColoBilling_BKP.App_Code.UMS.UMSGroupDetails> UMSGroupDetails = (List<IPColoBilling_BKP.App_Code.UMS.UMSGroupDetails>)Session["lstUMSGroupDetails"];
Session["lstUMSGroupDetails"] = UMSGroupDetails;
string strApprove = "";
if (ViewState["CheckedCheckboxes_CMM"] != null)
{
foreach (GridViewRow row in grdDisplayCMMData.Rows)
{
if (((CheckBox)row.FindControl("chkApprRejCMM")).Checked)
{
Label SAPID_CMM = (Label)row.FindControl("lblSAP_ID_CMM");
Label ID = (Label)row.FindControl("lblID_CMM");
int Id = Convert.ToInt32(ID.Text);
ObjIPColoFields.Unique_Id = Id;
ObjIPColoFields.UMS_GRP_BY_ID = intCurrentGrpId;
ObjIPColoFields.UMS_GRP_BY_NAME = strCurrentGrp;
ObjIPColoFields.UMS_GRP_TO_ID = UMSGroupDetails[1].GroupID;
ObjIPColoFields.UMS_GRP_TO_NAME = UMSGroupDetails[1].GroupName;
ObjIPColoFields.FCA_STATUS = "1";
ObjIPColoFields.LAST_UPDATED_BY = lblUserName.Text;
strDate = DateTime.Now.ToString();
strApprove = CommonDB.Approve_IPCOLO_CMMLevel(ObjIPColoFields);
if (ObjIPColoFields.Unique_Id != null || ObjIPColoFields.Unique_Id != 0)
{
strMailContent = Get_Email_Content(ObjIPColoFields.LAST_UPDATED_BY, SAPID_CMM.Text, strIPCOLO_CMM, Convert.ToString(Id), strDate, "Approved");
SendEmail(lblUserName.Text, strMailContent, strIPCOLO_CMM);
}
}
}
}
BindCMMData();
if (flgCMM == false)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Please check atleast one row'); window.location ='IpColoDefault.aspx';", true);
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Record Approved successfully'); window.location ='IpColoDefault.aspx';", true);
}
}
catch (Exception ex)
{
string strErrorMsg = ex.Message.ToString() + " " + "StackTrace :" + ex.StackTrace.ToString();
CommonDB.WriteLog("ERROR:" + strErrorMsg, ConfigurationManager.AppSettings["IPCOLO_LOG"].ToString());
}
}
Use this code
foreach (GridViewRow row in grdDisplayCMMData.Rows)
{
if (((Checkbox)row.FindControl("chkApprRejCMM")).Checked)
{
Label SAPID_CMM = (Label)row.FindControl("lblSAP_ID_CMM");
ObjIPColoFields.Unique_Id = Id;
ObjIPColoFields.UMS_GRP_BY_ID = intCurrentGrpId;
ObjIPColoFields.UMS_GRP_BY_NAME = strCurrentGrp;
ObjIPColoFields.UMS_GRP_TO_ID = UMSGroupDetails[1].GroupID;
ObjIPColoFields.UMS_GRP_TO_NAME = UMSGroupDetails[1].GroupName;
ObjIPColoFields.FCA_STATUS = "1";
ObjIPColoFields.LAST_UPDATED_BY = lblUserName.Text;
strDate = DateTime.Now.ToString();
strApprove = CommonDB.Approve_IPCOLO_CMMLevel(ObjIPColoFields);
if (ObjIPColoFields.Unique_Id != null || ObjIPColoFields.Unique_Id != 0)
{
strMailContent = Get_Email_Content(ObjIPColoFields.LAST_UPDATED_BY, SAPID_CMM.Text, strIPCOLO_CMM, Convert.ToString(Id), strDate, "Approved");
SendEmail(lblUserName.Text, strMailContent, strIPCOLO_CMM);
}
}
}
I'm attempting to write a try/catch, and failing obviously. I'm not sure I fully understand try/catch, but I do know that I'm having troubles wrapping my head around what I would need to happen in order to verify that a correct date is being entered submit via form. I mean, I gather it needs to be in DateTime format, not string, and should be (MM/dd/yyyy), but this try/check thing is throwing me for a loop.
Instructions: Go back to the validation code that you added in the
frmPersonnel code and add a try/catch with logic to prevent an invalid
date from causing a server error.
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class frmPersonnel : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
btnSubmit.Click += new EventHandler(this.btnSubmit_Click);//event for button
}
private void btnSubmit_Click(object sender, EventArgs e)
{
//DECLARATIONS
int count = 0;
string Msg = "You must enter a value in the following fields: <br/> ";
Boolean validatedState = true;
Boolean validateEntry = false;
DateTime endDate = new DateTime(2016, 03, 01);
DateTime startDate = new DateTime(2016, 03, 01);
//BEGIN SERIES OF IF/ELSE FOR CONFIRMING ENTRIES
if (Request["txtFirstName"].ToString().Trim() == "")
{
//displays yellow bg for missing input
txtFirstName.BackColor = System.Drawing.Color.Yellow;
Msg = Msg + "First Name <br/> ";
}//endif
else
{
txtFirstName.BackColor = System.Drawing.Color.White;
count += 1;
}//end else
if (Request["txtLastName"].ToString().Trim() == "")
{
//displays yellow bg for missing input
txtLastName.BackColor = System.Drawing.Color.Yellow;
Msg = Msg + "Last Name <br/> ";
}//endif
else
{
txtFirstName.BackColor = System.Drawing.Color.White;
count += 1;
}//end else
if (Request["txtPayRate"].ToString().Trim() == "")
{
//displays yellow bg for missing input
txtPayRate.BackColor = System.Drawing.Color.Yellow;
Msg = Msg + "Pay Rate <br/> ";
}//endif
else
{
txtFirstName.BackColor = System.Drawing.Color.White;
count += 1;
}//end else
if (Request["txtStartDate"].ToString().Trim() == "")
{
//displays yellow bg for missing input
txtStartDate.BackColor = System.Drawing.Color.Yellow;
validateEntry = false;
Msg = Msg + "Start Date <br/> ";
}//endif
else
{
try
{
//Conversion to DateTime format?
startDate = DateTime.Parse(Request["txtStartDate"]);
//How do I write the format I want, and when it should be checked?
}
catch (Exception ex)
{
//Exception should be caught here, not sure how to write this out though?
}
validateEntry = true;
}//end else
if (Request["txtEndDate"].ToString().Trim() == "")
{
//displays yellow bg for missing input
txtEndDate.BackColor = System.Drawing.Color.Yellow;
validateEntry = false;
Msg = Msg + "End Date <br/> ";
}//endif
else
{
try
{
//Conversion to DateTime format?
endDate = DateTime.Parse(Request["txtEndDate"]);
//How do I write the format I want, and when it should be checked?
}
catch (Exception ex)
{
//Exception should be caught here, not sure how to write this out though?
}
validateEntry = true;
}//end else
//END SERIES OF IF/ELSE FOR CONFIRMING ENTRIES
//START IF VALIDATE ENTRY
if (validateEntry == true)
{
if (DateTime.Compare(startDate, endDate) >= 0)
{
txtStartDate.BackColor = System.Drawing.Color.Yellow;
txtEndDate.BackColor = System.Drawing.Color.Yellow;
Msg = Msg + "Start Date <br/>" + "End Date <br/> <br/>The end date must be a later date than the start date.";
//The Msg text will be displayed in lblError.Text after all the error messages are concatenated
validatedState = false;
//Boolean value - test each textbox to see if the data entered is valid, if not set validState=false.
//If after testing each validation rule, the validatedState value is true, then submit to frmPersonnelVerified.aspx, if not, then display error message
}
else //goes to this if dates are correct
{
validatedState = true;
count += 2;
txtStartDate.BackColor = System.Drawing.Color.White;
txtEndDate.BackColor = System.Drawing.Color.White;
}
}
//END IF VALIDATE ENTRY
//SENDS DATA & ERROR MESSAGES
if (count == 5 && validatedState == true)
{
Session["txtFirstName"] = txtFirstName.Text;
Session["txtLastName"] = txtLastName.Text;
Session["txtPayRate"] = txtPayRate.Text;
Session["txtStartDate"] = txtStartDate.Text;
Session["txtEndDate"] = txtEndDate.Text;
Response.Redirect("frmPersonnelVerified.aspx");
//sends to other page
}
else
{
//Writes out error messages
Response.Write("<br/><span style = 'color: red ; position: absolute; top: 360px; left: 90px;'>" + Msg + "</span>");
}
//ENDS DATA AND ERROR MESSAGES
}//end Function: private void BtnSubmit_click...
}
From MSDN: https://msdn.microsoft.com/en-us/library/0yd65esw.aspx
When an exception is thrown, the common language runtime (CLR) looks for the catch statement that handles this exception. If the currently executing method does not contain such a catch block, the CLR looks at the method that called the current method, and so on up the call stack. If no catch block is found, then the CLR displays an unhandled exception message to the user and stops execution of the program.
The try block contains the guarded code that may cause the exception. The block is executed until an exception is thrown or it is completed successfully.
You can logically think of a try... catch... block kind of like a conditional.
For example, lets say you have this code:
string someString = "ABC";
DateTime someDate = DateTime.Parse(someString);
Obviously "ABC" is not a valid DateTime, so what happens? Your application crashes due to an unhandled exception (error).
When you wrap something in a try... catch... block, you are basically saying:
If an exception occurs in my try block, then STOP executing the code in my try block, execute the code in the catch block, and continue on like nothing happened. Otherwise, just ignore code in my catch block.
This is referred to as structured exception handling. You are anticipating "dangerous" areas of your code, and adding contingency code in case that worst-case scenario happens. Structured exception handling is especially useful for dealing with unsafe user input as well as external or unreliable systems (like external webservices).
An example:
string someString = "ABC";
DateTime someDate;
try
{
someDate = DateTime.Parse(someString);
}
catch
{
// someString must not have been a valid DateTime!
// Console.WriteLine($"Hey, {someString} is not a valid DateTime!");
Console.WriteLine(String.Format("Hey, {0} is not a valid DateTime!", someString));
}
// Code continues executing because the exception was "caught"
You could use TryParse to check for a valid date
// valid Date
DateTime goodDate;
if (DateTime.TryParse("2000-02-02", out goodDate))
{
Console.WriteLine(goodDate);
}
// not a date
DateTime badDate;
if (DateTime.TryParse("???", out badDate))
{
Console.WriteLine(badDate);
}
else
{
Console.WriteLine("Invalid");
}
You might also want to include the culture if you are expecting a format based on a region
string dateString;
CultureInfo culture;
DateTimeStyles styles;
DateTime dateResult;
// Parse a date and time with no styles.
dateString = "03/01/2009 10:00 AM";
culture = CultureInfo.CreateSpecificCulture("en-US");
styles = DateTimeStyles.None;
if (DateTime.TryParse(dateString, culture, styles, out dateResult))
Console.WriteLine("{0} converted to {1} {2}.",
dateString, dateResult, dateResult.Kind);
else
Console.WriteLine("Unable to convert {0} to a date and time.",
dateString);
Move the validateEntry = true; to within the try so you won't be setting it even if DateTime.Parse throws an exception. Your try-catchs are fine. They will catch any errors in the DateTime.Parses.
If you really want to be exact:
DateTime dateValue;
var isDatePass = DateTime.TryParseExact("03/08/2002", "MM/dd/yyyy", new CultureInfo("en-US"), DateTimeStyles.None, out dateValue);
Keep in mind, you could always use upfront validation.
I have to do a form for new user in my project.
I do not know what is wrong with it.
This is the method:
private void NewUserMethod() {
try {
NewUserTbl newUserTbl = new NewUserTbl();
newUserTbl.FName = txtFName.Text;
newUserTbl.LName = txtLName.Text;
newUserTbl.UserName = txtUserName.Text;
newUserTbl.NewPassword = txtPass.Text;
newUserTbl.ConfirmPassword = txtAgainPass.Text;
txtFName.Text = "";
txtLName.Text = "";
txtUserName.Text = "";
txtPass.Text = "";
txtAgainPass.Text = "";
if (txtPass == txtAgainPass) {
DB_Admin.NewUserTbls.InsertOnSubmit(newUserTbl);
DB_Admin.SubmitChanges();
MessageBox.Show("new user created");
} else {
MessageBox.Show("Wrong Password");
}
} catch (Exception)
{
MessageBox.Show("You entered wrong data");
}
}
I'm new at C# programming.
You were comparing two controls instead of their text property
if (txtPass == txtAgainPass)
{
}
However if you start comparing with it's Text property
like this
if (txtPass.Text == txtAgainPass.Text)
{
}
this won't bring any change because you are making empty
txtPass.Text = "";
txtAgainPass.Text = "";
Try like this
if (newUserTbl.NewPassword == newUserTbl.ConfirmPassword)
{
}
I'm assuming these are textboxes : if (txtPass == txtAgainPass). hence, they are different and not the same ...
try comparing the actual strings in them
to get the text of TextBox for comparison or any thing ,
you should write " .text " after the name
Like txtName.Text
I have an Asp.Net page (named 'PostAD') which allows user to upload up to 4 pictures. The file upload button function is as follows:
protected void btnUpload_Click(object sender, EventArgs e)
{
if ((ViewState["Img1"] != null) && (ViewState["Img2"] != null) && (ViewState["Img3"] != null) && (ViewState["Img4"] != null))
{
lblUploadMsg.Text = "You cannot upload more than 4 pictures";
return;
}
if (FileUpload1.HasFile)
{
//FileUpload1.Attributes.Clear();
string fileExtension = System.IO.Path.GetExtension(FileUpload1.FileName);
if (fileExtension.ToLower() == ".jpg")
{
int fileSize = FileUpload1.PostedFile.ContentLength;
if (FileUpload1.PostedFile.ContentLength < 2097152)
{
//FileUpload1.SaveAs(Server.MapPath("~/Temp/" + FileUpload1.FileName));
//Response.Write("Successfully Done");
string sp = Server.MapPath("~/ItemPictures/");
String fn = Guid.NewGuid().ToString() + FileUpload1.FileName.Substring(FileUpload1.FileName.LastIndexOf("."));
if (sp.EndsWith("\\") == false)
sp += "\\";
sp += fn;
FileUpload1.PostedFile.SaveAs(sp);
lblUploadMsg.ForeColor = System.Drawing.Color.Green;
lblUploadMsg.Text = "Picture Uploaded successfully. You can upload upto 4 pictures";
if (ViewState["Img1"] == null)
{
ViewState["Img1"] = "~/ItemPictures/" + fn;
}
else if (ViewState["Img2"] == null)
{
ViewState["Img2"] = "~/ItemPictures/" + fn;
}
else if (ViewState["Img3"] == null)
{
ViewState["Img3"] = "~/ItemPictures/" + fn;
}
else if (ViewState["Img4"] == null)
{
ViewState["Img4"] = "~/ItemPictures/" + fn;
}
}
else
{
lblUploadMsg.Text = "Maximum 2MB files are allowed";
}
}
else
{
lblUploadMsg.Text = "Only JPG files are allowed";
}
}
else
{
lblUploadMsg.Text = "No File was Selected";
}
ShowAvailblImgs();
}
I have four Asp.Net images that are invisible at page load time. To show them i have the following code.
private void ShowAvailblImgs()
{
if (ViewState["Img1"] != null)
{
//The string URL variable is used just to show what value ViewState["image1"] currently has.
string URL = (string)ViewState["img1"];
Response.Write(URL);
Image1.ImageUrl = (string)ViewState["img1"];
Image1.Width = 130;
Image1.Height = 130;
Image1.Visible = true;
}
else
Image1.Visible = false;
if (ViewState["Img2"] != null)
{
Image2.ImageUrl = (string)ViewState["img2"];
Image2.Width = 130;
Image2.Height = 130;
Image2.Visible = true;
}
else
Image2.Visible = false;
if (ViewState["Img3"] != null)
{
Image3.ImageUrl = (string)ViewState["img3"];
Image3.Width = 130;
Image3.Height = 130;
Image3.Visible = true;
}
else
Image3.Visible = false;
if (ViewState["Img4"] != null)
{
Image4.ImageUrl = (string)ViewState["img4"];
Image4.Width = 130;
Image4.Height = 130;
Image4.Visible = true;
}
else
Image4.Visible = false;
}
I am having very strange behaviour of ViewState variable. Upon loading images, they are not shown in Asp.Net image control. Instead empty image areas are shown. Though the URL variable i used print exact path to the image. Upon saving the image (which are really blank image areas), it get saved my .aspx page. I was using Session variable which worked fine but due to some reasons, i want to use ViewState variable.
ViewState is fine. You are using different case for your ViewState index string, so they don't refer to the same ViewState property. "Img1" is not equal to "img1".
ViewState["Img1"] != null)
{
Image2.ImageUrl = (string)ViewState["img1"];
I recommend either using a constant for the value name, as below.
const string image1 = "img1";
const string image2 = "img2";
const string image3 = "img3";
const string image4 = "img4";
Or refer to my blog post to create strongly-typed pseudo-properties using extension methods.
http://coding.grax.com/2013/06/simple-strongly-typed-pattern-for.html
I don't want to say a wrong thing, but, reading from documentation, it was written that
"Viewstate is used to preserve page and control values between round trips"
http://msdn.microsoft.com/en-us/library/ms178198(v=vs.85).aspx
Have you tried to put the URLs in variables, and then assigning to ViewState["imgX"], and try to do another Postback and see if the ViewState["imgX"] contains the URL?
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
incorrectly checks the response c#
I have a code:
Match match = regex.Match(responseFromServer);
if (match.Success)
{
var input = responseFromServer;
var split = input.Split(':');
var final = split[3];
ProcessStartInfo mcStartInfo = new Shitocode;
Process.Start(mcStartInfo);
this.Close();
}
else if (responseFromServer == " Bad Login")
{
MessageBox.Show("Uncorrect login/password!");
}
else if (responseFromServer == " Old version")
{
MessageBox.Show("Launcher is old!");
}
Why there is no message box showing in the last two inspections?
I have tried to do things differently:
if (match.Success)
{
var input = responseFromServer;
var split = input.Split(':');
var final = split[3];
ProcessStartInfo mcStartInfo = new Shitocode;
Process.Start(mcStartInfo);
this.Close();
}
else if (responseFromServer.Equals("Bad Login"))
{
MessageBox.Show("Uncorrect login/password!");
}
else if (responseFromServer.Equals("Old Version"))
{
MessageBox.Show("Launcher is old!");
}
I enter the wrong password, but does not open the messagebox
string s = instxtbox.Text;
string[] s1 = new string[3];
s1[0] = " ";
s1[1] = " ";
s1[2] = " ";
string[] portion = s.Split(s1, StringSplitOptions.RemoveEmptyEntries);
int val = Convert.ToInt32(portion[2]);
string reg = portion[1];
if (reg == "ax")
axtxtbox.Text = portion[2];
else if (reg == "bx")
bxtxtbox.Text = portion[2];
else if (reg == "cx")
cxtxtbox.Text = portion[2];
else if (reg == "dx")
dxtxtbox.Text = portion[2];
Probably your responseFromServer does not match the values you are checking (Bad Login, and Old Version).
Try to add another else at the end of the if sequence and look what you've got.
if (match.Success)
{
//your code
}
else if (responseFromServer.Equals("Bad Login"))
{
MessageBox.Show("Uncorrect login/password!");
}
else if (responseFromServer.Equals("Old Version"))
{
MessageBox.Show("Launcher is old!");
}
else
{
MessageBox.Show("Cannot login, unknown response: " + responseFromServer)
}
EDIT after comment
If you do not the exact message, but you know that it has to contain some exact string, you could change the two responseFromServer.Equals() to responseFromServer.Contains()
Just set a breakingpoint, go through the code and check the Value of responseFromServer Copy this in the two cases and compare it in your code, i noticed you have whitespaces in the 1st code part before " Bad Login", but im not sure its the reason anyway.