C# If Statement with value from field in Table - c#

How do I write this statement to get a value back from the database or table and validate that if the Value = Yes it will return the "Result =10" part. The field is called "ApprovedStatus" the value will either be "No" or "Yes".
Visual Studio Tells me this: "The name 'Yes' does not exist in the current context"
If (ApprovedStatus.Equals = Yes)
{
result = 10;
}
else
{
result = 1;
}

Try if (ApprovedStatus == "Yes") if it's a string, or if (ApprovedStatus) if it's a bool.

If ApprovedStatus is of type bool, do:
if (ApprovedStatus)
Should it be string, do NOT do this
if(ApprovedStatus == "Yes")
because this will equal false if ApprovedStatus = "yes"
Instead use
if(StringComparer.OrdinalIgnoreCase.Equals(ApprovedStatus,"Yes"))
result = 10;
else
result = 1;
Note that if you do
if (ApprovedStatus.ToString().ToUpper().Equals("YES"))
or
if( ApprovedStatus.Equals("whatever",StringComparison.OrdinalIgnoreCase))
it will throw a null reference exception if ApprovedStatus is null.
...which is possible to likely if the value comes from a database.

Best guess given the limited info available... (Assuming ApprovedStatus is a String)
if(ApprovedStatus == "Yes")
{
result = 10;
}
else
{
result = 1;
}
or
if(ApprovedStatus.Equals("Yes"))
{
result = 10;
}
else
{
result = 1;
}

Use String.Compare -- it's more efficient.
if(String.Compare(ApprovedStatus, "Yes", true)==0){
result = 10;
} else {
result = 1;
}

Boolean values in C# are true and false. You should consult a basic C# tutorial, but your check has probably to look like this:
if (ApprovedStatus)
{
result = 10;
}
else
{
result = 1;
}
It can be written shorter as:
result = ApprovedStatus ? 10 : 1;

if (ApprovedStatus.Equals("Yes")) <-- Case Sensitive
{
}
or
if (ApprovedStatus.ToString().ToUpper() == "YES")
{
}

Related

String was not recognized as a valid boolean in C# RadioButton

I want to send values from one form to another form, which means when i click on a button then i want to send student values to another form through id column. However, I have got an error regarding string was not recognized when i want to send RadioButton values.
Please note, I do not save RadioButton values as string i.e. Male or Female into the database.
Here is the code itself.
if (this.isupdate)
{
DataTable dtStudentInfo = GetAllStudentInfoById(this.StudentId);
DataRow row = dtStudentInfo.Rows[0];
tbID.Text = row["std_id"].ToString();
tbName.Text = row["std_name"].ToString();
tbFatherName.Text = row["std_f_name"].ToString();
tbAddress.Text = row["std_address"].ToString();
tbBatchNo.Text = row["std_batch"].ToString();
tbBatchYear.Text = row["std_batch_year"].ToString();
tbCNIC.Text = row["std_cnic"].ToString();
tbMobNumber.Text = row["std_mob"].ToString();
rbMale.Checked = (row["std_gender"] is DBNull) ? false : Convert.ToBoolean(row["std_gender"] = 1) ? true : false);
}
A small typo makes a who lot of a difference.
Convert.ToBoolean(row["std_gender"] = 1)
Was meant to be (the convert is unnecessary here):
Convert.ToBoolean(row["std_gender"] == 1)
The typo caused the row["std_gender"] to be set to 1, which makes the convert fail.
Try
Convert.ToBoolean(row["std_gender"].ToString() == "1")
Solved..!!!
Code was right... Just a lil error with the returning type....
private object GetGender()
{
if (rbMale.Checked)
{
return (int)Gender.Male;
}
else if (rbFemale.Checked)
{
return (int)Gender.Female;
}
else
{
return (int)Gender.NoSelection;
}
}
Just changed the return type from object to int and also change the data type of gender from varchar to int...Here is the code
private int GetGender()
{
if (rbMale.Checked)
{
return (int)Gender.Male;
}
else if (rbFemale.Checked)
{
return (int)Gender.Female;
}
else
{
return (int)Gender.NoSelection;
}
}

How i can extract year from datetime.now?

I want user to input the year of vehicle made but not more than this year. for example today is 2015, i don't want them to input 2020. but 2016 is ok.
here is my code.
property = validationContext.ObjectType.GetProperty("VehicleYear");
string vehicleYear = Convert.ToString(property.GetValue(validationContext.ObjectInstance, null));
if (!string.IsNullOrWhiteSpace(vehicleYear) && vehicleYear.Length == 4 && Convert.ToInt16(vehicleYear) >= 1980)
{
isVehicleOlderThan1981 = true;
}
else
{
isVehicleOlderThan1981 = false;
else if (value != null && Convert.ToDateTime(value) < DateTime.Now)
{
return new ValidationResult(this.ErrorMessage);
}
i only want to get a year from the DatetTime.now
Sorry i am new to the programming.
To get the year component of any date (including DateTime.Now), use this:
DateTime.Now.Year
I tried to clean your code for a bit and make it more logical (Also attached the answer you are looking for):
property = validationContext.ObjectType.GetProperty("VehicleYear");
var value = property.GetValue(validationContext.ObjectInstance, null);
int inputNumber;
//First check if input is number
if (!int.TryParse(value, out inputNumber))
{
this.ErrorMessage = "Input is not an integer!"
//you could also throw an exception here (depends on your error handling)
return new ValidationResult(this.ErrorMessage);
}
//retrieves the number of digits
int countDigits = Math.Floor(Math.Log10(year) + 1);
if (countDigits != 4)
{
this.ErrorMessage = String.Format("Input has {0} digits!",countDigits);
return new ValidationResult(this.ErrorMessage);
}
if (inputNumber > (DateTime.Now.Year + 1))
{
this.ErrorMessage = "Year is in the future!";
return new ValidationResult(this.ErrorMessage);
}
//inputNumber is now a valid year!
if(inputNumber > 1980)
{
isVehicleOlderThan1981 = true;
} else {
isVehicleOlderThan1981 = false;
}
Try this:
DateTime.Now.Year
You may also want to look at TryParse methods, it will simplify your code.
ie
int i;
if(int.TryParse("VehicleYear", out i)
{
//successful conversion, use int i for your comparisons etc.
}
else
{
//wasn't a valid year (can't be converted)
}
You need to use Year Year property from DateTime. Your else if may look like:
else if (value != null && Convert.ToDateTime(value).Year < DateTime.Now.Year)
NOTE: Convert.ToDateTime(value).Year will scream at you if value does not have correct date.
else if (value != null && Convert.ToDateTime(value) > DateTime.Now.AddYears(10))
{
//validation error
}

Convert Null value retrieving from database into decimal data type

Please check the Table below:
Scope is: I have to check in the database the top profileid and have to increase it by 1. If no data is there then it will fetch 0 and will increase it by 1.
I am getting the top value when there is data but in case the table is completely empty, I am getting exception. Code is as below.
public Decimal GetTopProfileID()
{
Decimal topID = 0;
var profileID = _dbContext.tblProfile.Max(n => n.profileid);
try
{
if (profileID == null)
{
topID = 1;
}
else
{
topID = Convert.ToDecimal(profileID);
topID++;
}
}
catch (Exception)
{
throw;
}
return topID;
}
Please help me find the solution. Ready for any question.
Thanks in advance !!
When there's no record in the table and you try to get .Max() value,
then it will throw an error, so its better to verify if any record
exist or not.
Update your code as follows.
if (_dbContext.tblProfile.Any()) {
//Verify records in tblProfile table, if there's any record exist or not
return Convert.ToDecimal(_dbContext.tblProfile.Max(n = > n.profileid)) + 1;
try {
if (profileID == null) {
topID = 1;
} else {
topID = Convert.ToDecimal(profileID);
topID++;
}
} catch (Exception) {
throw;
}
return topID;
} else { //If there's no value in table then assuming it should return 1.
return 1;
}
Update
Or you can make it more simpler:
if (_dbContext.tblProfile.Any()) {
//Verify records in tblProfile table, if there's any record exist or not
return Convert.ToDecimal(_dbContext.tblProfile.Max(n = > n.profileid)) + 1;
} else { //If there's no value in table then assuming it should return 1.
return 1;
}
You can use this code:
if (_dbContext.tblProfile.Any())
{
//Verify records in tblProfile table, if there's any record exist or not
var profileID = _dbContext.tblProfile.Max(n = > n.profileid) ?? 0;
return profileID + 1;
}
else
return 1;
Also if ProfileID is not nullable then don't need care about null value.
Then you can use below code:
return _dbContext.tblProfile.Any() ? _dbContext.tblProfile.Max(n = > n.profileid) + 1 : 1;
var profileID = _dbContext.tblProfile.OrderByDescending(n => n.profileid).FirstOrDefault();
Decimal topID = 1;
if (profileID != null)
{
decimal.TryParse(profileID.ProfileId, out topID);
topID++;
}
return topID;
}
Above answer by Moksh Shah is correct, but in that case we are hitting Data Base twice,
I think this should produce the desired result.
Use LastOrDefault() like this:
decimal variableName = Convert.ToDecimal(_dbContext.tblProfile.Select(x=> x.ProfileId).LastOrDefault() + 1);
Should work.
This is better than other solution as there is only one database call.

How to add condition to loop

I wanna check a value in array and if it exist return the value else return the message and read another value from array. add
else
{
MessageBox.Show("This Item ID Does Not Exist");
}
but the problem is when the the value is not in array, it want to show the message for 1258038 times.
how can I check the value (input) and if it exists, i can continue and if it does not exist in array , it returns back and read another value (input can be several values that must read one by one)
for (int cun = 0; cun < ItemIdNumber.Length; cun++)
{
int Item_Id = Convert.ToInt32(ItemIdNumber[cun]);
for (int yyu = 0; yyu <= 1258038; yyu++)
{
int weer = c[yyu];
if (weer == Item_Id)
{
itemseq = yyu;
}
else
{
MessageBox.Show("This Item ID Does Not Exist");
}
}
float[] i_ff = b[itemseq];
for (int ii = 0; ii < i_ff.Length; ii++)
{
.......
Use break to leave the loop early. You'll also need to change your logic a bit so you're not displaying a message in every iteration. This is just one possibility:
int? itemseq = null;
for (...) // outer loop
{
...
for (...) // inner loop
{
if (weer == Item_Id)
{
itemseq = yyu;
break;
}
}
if (!itemseq.HasValue)
MessageBox.Show("This Item ID Does Not Exist");
...
}
I think with a little bit of thought, you could make this more readable.
You've got two collections to search - ItemIdNumber and c.
You're looking for the first value in ItemIdNumber that matches an item in the first 1258038 values of c.
Something like this LINQ statement maybe, although I'm not exactly sure what type your collections are. And I'm writing this free-hand, so it might not compile as-is. Should give you something to work with though.
var id = (from id in ItemIdNumber
join cid in c.Take(1258038) on Convert.ToInt32(id) equals cid
select cid).FirstOrDefault();
if (!id.HasValue)
MessageBox.Show("This Item ID Does Not Exist");
for (int cun = 0; cun < ItemIdNumber.Length; cun++) {
...
boolean found = false;
for (int yyu = 0; yyu <= 1258038; yyu++) {
int weer = c[yyu];
if (weer == Item_Id)
{
itemseq = yyu;
found = true;
break;
}
}
if(!found) {
MessageBox.Show("This Item ID Does Not Exist");
}
...
}

Check asp.net textbox value against multiple if conditions

I have my website built in ASP.NET 2.0 and C#. I have textbox called tbCode where a user enters a code. I am trying to check that entered value against multiple values in the code behind on a button click.
This is my mark up so far.
protected void btUpdate_Click(object sender, EventArgs e)
{
if ((this.tbcode.Text.Trim().ToUpper() != "AB12") ||(this.tbcode.Text.Trim().ToUpper() != "DE14") || (this.tbcode.Text.Trim().ToUpper() != "XW16"))
{
lbmessage.Text = "Invalid Promo code. Please enter again";
}
else if ((this.tbcode.Text.Trim().ToUpper() == "AB12") || (this.tbcode.Text.Trim().ToUpper() == "DE14") || (this.tbcode.Text.Trim().ToUpper() == "XW16"))
{
Order.Shipping.Cost = 0;
this.lShipping.Text = Order.Shipping.Cost.ToString("c");
this.lSubtotal.Text = Order.Subtotal.ToString("c");
this.lTotal.Text = Order.TotalCost.ToString("c");
Order.PomoCode = this.tbcode.Text.Trim().ToUpper();
lbmessage.Text = "Promo Code Applied.";
}
else
{
this.lShipping.Text = Order.Shipping.Cost.ToString("c");
this.lSubtotal.Text = Order.Subtotal.ToString("c");
this.lTotal.Text = Order.TotalCost.ToString("c");
}
}
when i hit the button its always saying invalid code. not sure where am i making the mistake. It works perfectly if I am checking against just one value rather than the 3.
Thanks and appreciate it
Here is likely what you wanted to do:
protected void btUpdate_Click(object sender, EventArgs e)
{
string tbcodeValue = this.tbcode.Text.Trim().ToUpper();
string[] validCodes = new string[] { "AB12", "DE14", "XW16" };
if (!validCodes.Contains(tbcodeValue))
{
lbmessage.Text = "Invalid Promo code. Please enter again";
}
else
{
Order.Shipping.Cost = 0;
this.lShipping.Text = Order.Shipping.Cost.ToString("c");
this.lSubtotal.Text = Order.Subtotal.ToString("c");
this.lTotal.Text = Order.TotalCost.ToString("c");
Order.PomoCode = tbcodeValue;
lbmessage.Text = "Promo Code Applied.";
}
}
First off, you were calling this.tbcode.Text.Trim().ToUpper() all over the place. That really clutters up your code and makes it hard to read. Assigning that to a variable not only makes the code cleaner, but avoids performing all of those string manipulation functions over and over.
Next, it appears that your intent is to say, "if the textbox value isn't any of these values, run some code saying it's invalid. The easiest way to do that is to put all of the valid values into a container of some sort and see if it contains the value you're interested in. Your next block of code is basically for, "if it is one of the valid values". So if it does contain the string then it is valid. As for your else, I couldn't figure out what the intent of it was. Either the string is invalid, or it's valid. I don't see any third case there, so I just removed it.
You need to change your ||'s to &&'s in the first if statement. You are always going to fall into that block otherwise.
Try this:
if ((this.tbcode.Text.Trim().ToUpper() != "AB12") && (this.tbcode.Text.Trim().ToUpper() != "DE14") && (this.tbcode.Text.Trim().ToUpper() != "XW16"))
{
lbmessage.Text = "Invalid Promo code. Please enter again";
}
else if ((this.tbcode.Text.Trim().ToUpper() == "AB12") || (this.tbcode.Text.Trim().ToUpper() == "DE14") || (this.tbcode.Text.Trim().ToUpper() == "XW16"))
{
Order.Shipping.Cost = 0;
this.lShipping.Text = Order.Shipping.Cost.ToString("c");
this.lSubtotal.Text = Order.Subtotal.ToString("c");
this.lTotal.Text = Order.TotalCost.ToString("c");
Order.PomoCode = this.tbcode.Text.Trim().ToUpper();
lbmessage.Text = "Promo Code Applied.";
}
else
{
this.lShipping.Text = Order.Shipping.Cost.ToString("c");
this.lSubtotal.Text = Order.Subtotal.ToString("c");
this.lTotal.Text = Order.TotalCost.ToString("c");
}
You could also employ a switch;case; block.
String testtext = this.tbcode.Text.Trim().ToUpper();
switch(testtext)
{
case "AB12":
// Do stuff for this case
break;
case "Text2":
// Do stuff for this case
break;
default:
// anything that fails all above tests goes here
break;
}
Just be sure to either break, return, or continue after each case or you will get a compile error. Also default needs to be last in line.

Categories