Can't get the correct Bool result in C# - c#

I have a form where I would like to check for validation before processing the form. My form has 2 sections so I want to make sure that at least one item from each section is selected when they press submit button, and if they did then go to Dashboard.aspx. Even if I put all the required info when it checks for result1 and result2, I get false. Result1 and Result2 won't get the correct value. Even if the values are True again it passes false.
Here is my code:
protected void btnSumbit_Click(object sender, EventArgs e)
{
if (!Page.IsValid)
return;
bool result1 = false;
bool result2 = false;
CheckWireFromValidation(result1);
CheckWireToValidation(result2);
if (result1 == true && result2 == true)
{
Response.Redirect("~/DashBoard.aspx");
}
}
public bool CheckWireFromValidation (bool result1)
{
if (drpFromCoporate.SelectedIndex != 0 || drpFromCapital.SelectedIndex != 0 || drpFromProperty.SelectedIndex != 0)
{
result1 = true;
}
else
{
result1 = false;
ShowAlertMessage("You need to choose at least one filed from Wire From drop downs!!");
}
return result1;
}
public bool CheckWireToValidation(bool result2)
{
if (drpToCapital.SelectedIndex != 0 || drpToCoporate.SelectedIndex != 0 || drpToProperty.SelectedIndex != 0 || drpToTemplate.SelectedIndex != 0 || txtCorpAmt.Text != "" || txtCapAmt.Text != "" || txtPropAmt.Text != "" || txtTempelateAmt.Text != "")
{
result2 = true;
}
else
{
ShowAlertMessage("You need to choose at least one filed from Wire To drop downs!!");
}
return result2;
}

You're not using the results of CheckWireToValidation. You're using the false value you allocate initially.
Try this
bool result1 = false;
bool result2 = false;
if (CheckWireFromValidation(result1) && CheckWireToValidation(result2))
{
Response.Redirect("~/DashBoard.aspx");
}
Edit
The behavior you're expecting is that of the out parameter modifier. But please don't write code that way ...
I edited your code to get rid of .. em .. cruft. This should be more readable.
protected void btnSumbit_Click(object sender, EventArgs e)
{
if (!Page.IsValid)
return;
if (CheckWireFromValidation() && CheckWireToValidation())
{
Response.Redirect("~/DashBoard.aspx");
}
}
public bool CheckWireFromValidation ()
{
if (drpFromCoporate.SelectedIndex != 0 || drpFromCapital.SelectedIndex != 0 || drpFromProperty.SelectedIndex != 0)
{
return true;
}
else
{
ShowAlertMessage("You need to choose at least one filed from Wire From drop downs!!");
return false;
}
}
public bool CheckWireToValidation ()
{
if (drpToCapital.SelectedIndex != 0 || drpToCoporate.SelectedIndex != 0 || drpToProperty.SelectedIndex != 0 || drpToTemplate.SelectedIndex != 0 || txtCorpAmt.Text != "" || txtCapAmt.Text != "" || txtPropAmt.Text != "" || txtTempelateAmt.Text != "")
{
return true;
}
else
{
ShowAlertMessage("You need to choose at least one filed from Wire To drop downs!!");
return false;
}
}

Since you are passing Result1 and Result2 in as parameters instead assigning them. The results will never be set.
Here's one correct way of doing this
bool result1 = CheckWireFromValidation(result1);
bool result2 = CheckWireToValidation(result2);
if (result1 == true && result2 == true)
{
Response.Redirect("~/DashBoard.aspx");
}
and also a side note. I think we can safely remove the boolean parameter from the CheckWireFromValidation methods. Since the return value doesn't depends on the input variable.
Hope this helps.

Related

How to combine multiple IF statements in C#

I have some flawed logic here..my goal is if all of the fields have "" value then return true, otherwise return false. How can I fix this in C# ?
public bool CheckFieldsAreEmpty()
{
Driver.WaitForElementValueNull(smtpHostInputField);
if (smtpHostInputField.GetAttribute("value") == "")
return true;
Driver.WaitForElementValueNull(smtpPortInputField);
if (smtpPortInputField.GetAttribute("value") == "")
return true;
Driver.WaitForElementValueNull(usernameInputField);
if (usernameInputField.GetAttribute("value") == "")
return true;
Driver.WaitForElementValueNull(passwordInputField);
if (passwordInputField.GetAttribute("value") == "")
return true;
Driver.WaitForElementValueNull(senderInputField);
if (senderInputField.GetAttribute("value") == "")
return true;
Driver.WaitForElementValueNull(receiverInputField);
if (receiverInputField.GetAttribute("value") == "")
return true;
else return false;
I believe something like this should work. I couldn't find what class all of those variables belong to, but replace var with the proper class and I think this should work.
logic: Add all variables to a List, use a lambda function to return if all of the list match GetAttribute("value") == ""
// Replace var with class type, or parent
List<var> allFields = new List<var> { smtpHostInputField, smtpPortInputField, sernameInputField, passwordInputField, senderInputField, receiverInputField };
foreach (var field in allFields) { Driver.WaitForElementValueNull(field); }
return allFields.All(t => t.GetAttribute("value") == "");
To illustrate #madreflection’s (correct) suggestion from the comments, consider this code:
public bool CheckFieldsAreEmpty()
{
Driver.WaitForElementValueNull(smtpHostInputField);
if (smtpHostInputField.GetAttribute("value") != "")
return false;
Driver.WaitForElementValueNull(smtpPortInputField);
if (smtpPortInputField.GetAttribute("value") != "")
return false;
Driver.WaitForElementValueNull(usernameInputField);
if (usernameInputField.GetAttribute("value") != "")
return false;
Driver.WaitForElementValueNull(passwordInputField);
if (passwordInputField.GetAttribute("value") != "")
return false;
Driver.WaitForElementValueNull(senderInputField);
if (senderInputField.GetAttribute("value") != "")
return false;
Driver.WaitForElementValueNull(receiverInputField);
if (receiverInputField.GetAttribute("value") != "")
return false;
return true;
}
Of course, as #Daniel-Lord’s answer highlights, you can centralize this repetitive logic using either a loop or a LINQ query.
Another way to solve this would be to extract WaitForElementValueNull call and empty string check to a separate method. Something like that:
private static bool WaitForElementValueNullAndEmpty(InputFieldType inputField)
{
Driver.WaitForElementValueNull(inputField);
return inputField.GetAttribute("value") == "";
}
public bool CheckFieldsAreEmpty()
{
return WaitForElementValueNullAndEmpty(smtpHostInputField) ||
WaitForElementValueNullAndEmpty(smtpPortInputField) ||
WaitForElementValueNullAndEmpty(usernameInputField) ||
WaitForElementValueNullAndEmpty(passwordInputField) ||
WaitForElementValueNullAndEmpty(senderInputField) ||
WaitForElementValueNullAndEmpty(receiverInputField);
}
The code above will match the algorithm that was provided, however if you want to check if ALL the values is empty then || should be replaced with && (As it was noticed by Jeremy Caney)

Filter data from datatable for one of columns in asp.net

I have a datatable which fetches some records. So there is one column name as UPDATED_STATUS. In that column either Pre Hoto or Post Hoto value will come.
So what I want is, Either any one of those values should be their in that column then only the it should move ahead otherwise it should prompt alert as
Either Pre Hoto or Post Hoto can be their
Below is sample image for reference
Below is the code for getting the datatable with the UPDATED_STATUS column
if (strFlag == "")
{
dtStatus = GET_STATUS_FROM_SAPID_FOR_HOTO(dtExcelRows.Rows[i]["Current SAPID"].ToString());
if (dtStatus == null && dtStatus.Rows.Count < 0)
{
ClientScript.RegisterStartupScript(Page.GetType(), "erroralert", "alert('Status cannot be blank for SAP ID entered');", true);
}
else
{
dtExcelRows.Rows[i]["UPDATED_STATUS"] = dtStatus.Rows[0][1].ToString();
dtExcelRows.AcceptChanges();
}
}
Your current check (if (dtStatus == null && dtStatus.Rows.Count < 0)) is wrong:
when dtStatus is null, you continue checking dtStatus.Rows, which throws a nullref exception (you just found out that it was null);
Rows.Count is never less than zero.
Try if (dtStatus == null || dtStatus.Rows.Count == 0) to check whether there is no status at all (it is null) or no status rows (count is zero). The || will prevent checking for dtStatus.Rows when it was found that dtStatus is null.
&& means that both sides must be true at the same time.
|| means that at least of the sides must be true (both true is also fine).
Both don't evaluate the second test when the first already decided the outcome (false && whatever is always false, true || whatever is always true)
Are you looking for like this !
foreach (DataRow row in dtStatus.Rows)
{
if (string.IsNullOrEmpty(Convert.ToString(row["UPDATED_STATUS"])) ||
(Convert.ToString(row["UPDATED_STATUS"]).ToLower() != "pre hoto" &&
Convert.ToString(row["UPDATED_STATUS"]).ToLower() != "post hoto"))
{
ClientScript.RegisterStartupScript(Page.GetType(), "erroralert", "alert('Status cannot be blank for SAP ID entered');", true);
break;
}
else { }
}
I have got a way to get this done.. Here I go
if (strFlag == "")
{
dtStatus = GET_STATUS_FROM_SAPID_FOR_HOTO(dtExcelRows.Rows[i]["Current SAPID"].ToString());
if (dtStatus == null && dtStatus.Rows.Count < 0)
{
ClientScript.RegisterStartupScript(Page.GetType(), "erroralert", "alert('Status cannot be blank for SAP ID entered');", true);
}
else
{
dtExcelRows.Rows[i]["UPDATED_STATUS"] = dtStatus.Rows[0][1].ToString();
dtExcelRows.AcceptChanges();
}
}
}
DataTable dtGetHotoPre = null;
var rows = dtExcelRows.AsEnumerable().Where(x => x.Field<string>("UPDATED_STATUS") == "PRE HOTO");
if (rows.Any())
{
dtGetHotoPre = rows.CopyToDataTable();
}
DataTable dtGetHotoPost = null;
var rowsPost = dtExcelRows.AsEnumerable().Where(x => x.Field<string>("UPDATED_STATUS") == "POST HOTO");
if (rowsPost.Any())
{
dtGetHotoPost = rowsPost.CopyToDataTable();
}
string strFlagStatus = "";
if (dtGetHotoPre != null)
{
if (dtGetHotoPost != null)
{
strFlagStatus = "No Process";
}
else
{
strFlagStatus = "Process";
grdDvHoto.DataSource = dtGetHotoPost;
}
}
else
{
if (dtGetHotoPost != null)
{
strFlagStatus = "Process";
grdDvHoto.DataSource = dtGetHotoPre;
}
else
{
strFlagStatus = "No Process";
}
}
// if(dtGetHotoPre != null && dtGetHotoPost != null)
if (strFlagStatus == "No Process")
{
ClientScript.RegisterStartupScript(Page.GetType(), "erroralert", "alert('The sites contains both Pre and Post Hoto Status, so it cannot be uploaded');", true);
}
else
{
// will move ahead.
grdDvHoto.DataBind();
}

How to break if-else-if using C#

How do I break if-else-if.....Why its not working? its just checking all the conditions instead of performing the tasks. following is my code. I have checked it through breakpoints its moving to all conditions why it doesn't get stop after meeting the correct condition. even it is not going into the if activity it just read all the conditions and do nothing at the end.
private void ShowHash()
{
inpic = pb_selected.Image;
Bitmap image = new Bitmap(inpic);
byte[] imgBytes = new byte[0];
imgBytes = (byte[])converter.ConvertTo(image, imgBytes.GetType());
string hash = ComputeHashCode(imgBytes);
txt_selectedText.Text = hash;
GetHash();
}
private void GetHash()
{
if (txt_sel1.Text == null && (txt_sel2.Text == null || txt_sel3.Text == null || txt_sel4.Text == null || txt_sel5.Text == null ))
{
txt_sel1.Text = txt_selectedText.Text;
return;
}
else if (txt_sel1.Text != null && (txt_sel2.Text == null || txt_sel3.Text == null || txt_sel4.Text == null || txt_sel5.Text == null))
{
txt_sel2.Text = txt_selectedText.Text;
return;
}
else if (txt_sel2.Text != null && (txt_sel3.Text == null || txt_sel4.Text == null || txt_sel5.Text == null))
{
txt_sel3.Text = txt_selectedText.Text;
return;
}
else if (txt_sel3.Text != null && (txt_sel4.Text == null || txt_sel5.Text == null))
{
txt_sel4.Text = txt_selectedText.Text;
return;
}
else if (txt_sel4.Text != null && (txt_sel5.Text == null))
{
txt_sel5.Text = txt_selectedText.Text;
return;
}
}
I strongly suspect the problem is that the Text property is never null for any of txt_sel*. Assuming these are text boxes in a UI, it's much more likely that if there's no text in the text box, the Text property will return "" instead of null. That's the way most UI frameworks handle empty controls.
I would also suggest extracting the conditions into local variables first:
bool hasSel1 = txt_sel1.Text != "";
bool hasSel2 = txt_sel2.Text != "";
bool hasSel3 = txt_sel3.Text != "";
bool hasSel4 = txt_sel4.Text != "";
bool hasSel5 = txt_sel5.Text != "";
if (!hasSel1 && (!hasSel2 || !hasSel3 || !hasSel4 || !hasSel5)
{
...
}
And ideally, give your controls more meaningful names - a collection of variables with the same prefix but then a numeric suffix is very rarely a good idea, in terms of readability.
Reason:
If there is nothing in those textboxes, textbox.Text will return an empty string ("") not null.
Solution:
Check against "" not null:
private void GetHash()
{
if (txt_sel1.Text == "" && (txt_sel2.Text == "" || txt_sel3.Text == "" || txt_sel4.Text == "" || txt_sel5.Text == ""))
{
txt_sel1.Text = txt_selectedText.Text;
return;
}
else if (txt_sel1.Text != "" && (txt_sel2.Text == "" || txt_sel3.Text == "" || txt_sel4.Text == "" || txt_sel5.Text == ""))
{
txt_sel2.Text = txt_selectedText.Text;
return;
}
....
....
EDIT: You don't have to do ==true for boolean variables. If statement checks it against true by default. Use ! to check against false:
if (hasValue1 && (hasValue2 || hasValue3 || hasValue4 || hasValue5))
{
txt_sel1.Text = txt_selectedText.Text;
return;
}
else if (hasValue2 && (!hasValue1 ||hasValue3 || hasValue4 || hasValue5))
{
txt_sel2.Text = txt_selectedText.Text;
return;
}
else if (hasValue3 && (!hasValue1 || hasValue2 || hasValue4 || hasValue5))
{
txt_sel3.Text = txt_selectedText.Text;
return;
}
....
....
I think for string better to use inbuild null and whitespace check function:
bool hasValue1 = string.IsNullOrWhiteSpace(txt_sel1.Text);
bool hasValue2= string.IsNullOrWhiteSpace(txt_sel2.Text);
bool hasValue3= string.IsNullOrWhiteSpace(txt_sel3.Text);
bool hasValue4= string.IsNullOrWhiteSpace((txt_sel4.Text);
bool hasValue5 = string.IsNullOrWhiteSpace(txt_sel5.Text);
And then define if condition on these bool. This case can handle unexpected null or white space values.
That is bacause it probably doesn't find any of those conditions true.
If it would find a true condition it would execute that if block and won't event check the others.
To add to what others have said, you should really have a final else statement in there to catch issues such as this:
else
{
throw new InvalidOperationException("My If Statement is Broken");
}
Thanks to you all! My problem is solved by changing the conditions and your suggested alteration, following is the code may be helped some beginner like me.
private void GetHash()
{
bool hasValue1 = string.IsNullOrWhiteSpace(txt_sel1.Text);
bool hasValue2 = string.IsNullOrWhiteSpace(txt_sel2.Text);
bool hasValue3 = string.IsNullOrWhiteSpace(txt_sel3.Text);
bool hasValue4 = string.IsNullOrWhiteSpace(txt_sel4.Text);
bool hasValue5 = string.IsNullOrWhiteSpace(txt_sel5.Text);
if (hasValue1 && (hasValue2 || hasValue3 || hasValue4 || hasValue5))
{
txt_sel1.Text = txt_selectedText.Text;
return;
}
else if (hasValue2 && (!hasValue1 ||hasValue3 || hasValue4 || hasValue5 ))
{
txt_sel2.Text = txt_selectedText.Text;
return;
}
else if (hasValue3 && (!hasValue1 || !hasValue2 || hasValue4 || hasValue5 ))
{
txt_sel3.Text = txt_selectedText.Text;
return;
}
else if (hasValue4 && (!hasValue1 || !hasValue2 || !hasValue3 || hasValue5 ))
{
txt_sel4.Text = txt_selectedText.Text;
return;
}
else if (hasValue5 && (!hasValue1 || !hasValue2 || !hasValue3 || !hasValue4 ))
{
txt_sel5.Text = txt_selectedText.Text;
return;
}
else
{
CompareHash();
}
}

evaluation of conditions in an if statement

Suppose I have this if statement:
foreach (MyModel m in SomeList)
{
if (m.pID != SomeValue && (m.xID != 0 && SomeFunction(m.xID) == false)
{
return false;
}
}
I only want SomeFunction(m.xID) == false to evaluate if m.xID != 0 so if m.xID == 0 then don't evaluate SomeFunction
For the moment, I have this if statement broken down into 2 statements and I'm looking to see how I can combine these into just one while preserving the logic. This is the original:
foreach (MyModel m in SomeList)
{
if (m.xID != 0 && SomeFunction(m.xID) == false)
{
return false;
}
if (m.pID != SomeValue)
{
return false;
}
}
If that is all your loop is doing then I would be inclined to remove the loop entirely.
Also, instead of comparing something to false, just use the ! operator.
if (SomeList.Any(MyModel m=>m.xID != 0 && !SomeFunction(m.xID) || m.pID != SomeValue))
return false;
you are looking for this || Operator (C# Reference)
if ((m.xID != 0 && SomeFunction(m.xID) == false) || (m.pID != SomeValue))
{
return false;
}

Due to LINQ Retrieving of Record data's i have this error: NullReferenceException was unhandled by user code

private void getUserLoginDepartment(string AccessID, string UserPROFid)
{
try
{
DBWPAccountRecordsDataContext DBACCOUNT = new DBWPAccountRecordsDataContext();
var query = (from i in DBACCOUNT.WP_UserAccessPorts
join
z in DBACCOUNT.WP_Departments on i.AccessPortID equals z.Dept_ID
where i.AccessPortID == AccessID && i.ProfileUser_ID == UserPROFid
select new
{
PORT1 = i.AccessPoint1,
PORT2 = i.AccessPoint2,
PORT3 = i.AccessPoint3,
PORT4 = i.AccessPoint4,
DEPT = z.Dept_DESC,
DEPTPORT = z.Dept_PortNo
}).FirstOrDefault();
if (query.PORT1.ToString() != null || query.PORT1.ToString() != string.Empty)
{ Session["Port1"] = query.PORT1; }
else { Session["Port1"] = ""; }
if (query.PORT2.ToString() != null || query.PORT2.ToString() != string.Empty)
{ Session["Port2"] = query.PORT2; }
else { Session["Port2"] = ""; }
if (query.PORT3.ToString() != null || query.PORT3.ToString() != string.Empty)
{ Session["Port3"] = query.PORT3; }
else { Session["Port3"] = ""; }
if (query.PORT4.ToString() != null || query.PORT4.ToString() != string.Empty)
{ Session["Port4"] = query.PORT4; }
else { Session["Port4"] = ""; }
}
finally
{
}
}
The Error occures when i reach break point 1st IF Statement the record on my database shows that its not empty which its value is "WebAdmin" but then suppost to be it should pick it up and store it to the Session["PORT1"] that i have made is there something i missed or i'm doing it wrong on my linq Query. NOTE:*This is an ASP.NET C# Application
EDIT 10/2/2013 0420PM:
It's still an Error After using that method sir.
1) you should check query for null when you use FirstOrDefault
2) you need to check each PORTX for null
3) use string.IsNullOrEmpty( ) to check if the string of PORTX is null
var query = ( ... ).FirstOrDefault( );
if( query != null )
{
if( query.PORT1 != null && !string.IsNullOrEmpty( query.PORT1.ToString( ) ) )
{
}
else { ... }
}
You have to check query.PORT1 for null before calling ToString on it, you can use String.IsNullOrEmpty to check both conditions. Before checking query.PORT1 you need to check if query is null or not. You also need to use && instead of or operator as || will cause the right side of or operator to be evaluated if left is false and on right side calling ToString on null will again through exception.
if (query != null && query.PORT1 != null && query.PORT1.ToString() != string.Empty)
{ Session["Port1"] = query.PORT1; }
Using IsNullOrEmpty
if(query != null && !String.IsNullOrEmpty(query.PORT1))
{
Session["Port1"] = query.PORT1;
}

Categories