Create new user and comparison for two textbox - c#

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

Related

C#: Add a new check without affecting existing checks

I hope I can explain my scenario the best I can.
I have code that when the "Load" button is clicked, all file names (if any) located in a predefined network directory path, are loaded to a text-area.
Currently there can be .txt, .xml files.
Contents could look like:
first_file_found.xml
second_file_found.xml
third_file_found.txt
Also, in the code there is another function "isCoValid" that performs an additional validation of the contents of these files, based on return value (true/false) of this function, the "Process" button is enabled:
if (IsFlatFile(fileName) || IsXMLFile(fileName))
{
if (isCoValid(fileName))
{
btnProcess.Enabled = true;
}
else
{
btnProcess.Enabled = false;
break;
}
}
Now I have to add a .csv file type, but this file does not required to perform the isCoValid function.
The text-area contents now look like:
first_file_found.xml
second_file_found.xml
third_file_found.txt
fourht_file_found.csv
My request for help is to ask how can the check to find out if there is a CSV file can be done, and also controlling the enabling of the "Process" button, but still respect the existing check for .txt, and .xml and the validation of contents?
I might have xml and text files, that aren't valid, but I still need to be able to process the .csv. file.
I did change it like this:
if (IsFlatFile(fileName) || IsXMLFile(fileName))
{
if (isCoValid(fileName))
{
btnProcess.Enabled = true;
}
else
{
btnProcess.Enabled = false;
break;
}
}
if (IsCSVFile(fileName))
{
btnProcess.Enabled = true;
}
But I am sure this is not correct and I would like to ask for some help if possible.
I hope I explained my problem with some clarity and straightforwardness, if not, please let me know and I can try to provide more information.
Thank you,
Erasmo
Additional Code Requested
public bool IsFlatFile(string FileName)
bool ReturnValue = false;
if (FileName.ToUpper().Right(4) == ".TXT")
{
if ((FileName.Substring(0, 2).ToUpper() == "MN") ||
(FileName.Substring(0, 2).ToUpper() == "CH"))
{
ReturnValue = true;
}
}
return ReturnValue;
}
public bool IsXMLFile(string FileName)
bool ReturnValue = false;
if (FileName.ToUpper().Right(4) == ".XML")
{
if ((FileName.Substring(0, 2).ToUpper() == "TR") ||
(FileName.Substring(0, 2).ToUpper() == "SK"))
{
ReturnValue = true;
}
}
return ReturnValue;
}
protected bool isCoValid(string fName)
{
bool retCode = false;
Parameters parms;
var reader = new AppSettingsReader();
Application app = new Application();
Package package = null;
try
{
package = app.LoadPackage(packagePath + "ValidateContents.dtsx", null);
parms = package.Parameters;
parms["ID"].Value = "";
parms["ImportFileName"].Value = fName;
parms["UserID"].Value = userName;
DTSExecResult results = package.Execute();
if (results == Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure)
{
foreach (Microsoft.SqlServer.Dts.Runtime.DtsError local_DtsError in package.Errors)
{
retCode = false;
resultText = resultText + "DTSX Package Execution results: " + local_DtsError.Description.ToString() + Environment.NewLine;
}
}
else
{
resultText = resultText + "Successful Process Completion." + Environment.NewLine + Environment.NewLine;
string sqlStr = "SELECT TOP 1 * FROM Validation WHERE Type = 'VALCO' AND CAST(CreatedDate AS DATE) = CAST(GETDATE() AS DATE)";
DataTable dt = new DataTable();
dt = GetDataSet(sqlStr);
if (dt.Rows.Count > 0)
{
foreach (DataRow row in dt.Rows)
{
if (row["Status"].ToString() == "Valid")
{
retCode = true;
resultText = "Output: Valid" + Environment.NewLine + "Press the 'Process' button to proceed.";
}
else
{
retCode = false;
resultText = "Output: " + row["Status"].ToString() + Environment.NewLine + "Validation Fail: " + row["Error"].ToString();
}
}
}
else
{
resultText = "Unable to read Validation Table for this file.";
retCode = false;
}
}
}
catch (Exception)
{
throw;
}
return retCode;
}
Your code will look like so:
if (IsFlatFile(fileName) || IsXMLFile(fileName) || IsCSVFile(fileName))
{
btnProcess.Enabled = isCoValid(fileName);
if (!btnProcess.Enabled) break;
}
public static bool IsCSVFile(string FileName) =>
Path.GetExtension(FileName).Equals(".csv", StringComparison.OrdinalIgnoreCase);
when you write your own IsCSVFile() method and update isCoValid() method to fit your needs.
Sorry, but I can't guess what happens inside classes that are used in isCoValid() method.

Gridvew Looping for multiple times even when selected least records in asp.net

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);
}
}
}

C# combining variables

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");
}
}

If not called. c# [duplicate]

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.

This.close() closing main form aswell

been trying to figure this out for about an hour!
I made an app that has 1 main form which is launched in Program.cs like this
frmFleetMain frmW = new frmFleetMain();
frmW.iNIPathAndFile = GlobalInfo.iNIPathAndFile;
frmW.SetUser(GlobalInfo.Username);
Application.Run(frmW);
and 1 sub form that is launched in the main form like this
if (recordid != "")
{
frmFleetSave frmsave = new frmFleetSave();
frmsave.Rowid = int.Parse(recordid);
frmsave.ShowDialog();
dgvMain.Rows[rowindx].Cells[0].Style.BackColor = Color.Red;
oFuel.Filter = FLEET_FUEL.ColumnNames.FUEL_SEQUENCE + " = "+recordid;
oFuel.FLEET_NO = int.Parse(GlobalInfo.FLEETNO);
oFuel.Filter = "";
GlobalInfo.FLEETNO = "";
}
In the btnclose event of frmsave i have this code
if (GlobalInfo.FLEETNO == "")
{
DialogResult result = MessageBox.Show("Record will not be updated!Click OK to try again or CANCEL to close.", "Warning", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation);
if (result == DialogResult.Cancel)
{
this.Close();//this closes both forms -this is not what i want
}
}
else
{
this.Close();//this closes frmsave only-this is what i want:)
}
I cant figure out why this is happening!Help :)
SOLVED :
if (recordid != "")
{
frmFleetSave frmsave = new frmFleetSave();
frmsave.Rowid = int.Parse(recordid);
frmsave.ShowDialog();
if (frmsave.ssave)//get a bool variable indicating we can save! :-P
{
oFuel.Filter = FLEET_FUEL.ColumnNames.FUEL_SEQUENCE + " = " + recordid;
oFuel.FLEET_NO = int.Parse(GlobalInfo.FLEETNO);
oFuel.Filter = "";
GlobalInfo.FLEETNO = "";
}
}
try to change frmsave.ShowDialog(); to frmsave.ShowDialog(this);
and change other code to:
DialogResult result = MessageBox.Show(this, "Record will not be updated!Click OK to try again or CANCEL to close.", "Warning", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation);
if (result == DialogResult.Cancel)
{
Close();
}
this works fine on my pc...
SOLVED :
if (recordid != "")
{
frmFleetSave frmsave = new frmFleetSave();
frmsave.Rowid = int.Parse(recordid);
frmsave.ShowDialog();
if (frmsave.ssave)//get a bool variable indicating we can save! :-P
{
oFuel.Filter = FLEET_FUEL.ColumnNames.FUEL_SEQUENCE + " = " + recordid;
oFuel.FLEET_NO = int.Parse(GlobalInfo.FLEETNO);
oFuel.Filter = "";
GlobalInfo.FLEETNO = "";
}
}

Categories

Resources