Im trying to see if a textbox is "0" or empty using the following code.
I hoped I could use the ! operator on IsNulorEmpty but seems it doesn't do what I want. Is there an easy way to do this on one line?
if (!String.IsNullOrEmpty(MyTextbox.Text) || MyTextbox.Text != "0")
{
//string is either null, empty or 0
}
else
{
//string has a value
}
The code is doing what you write, but you are confused about operator evaluations:
if (string.IsNullOrEmpty(MyTextbox.Text) || MyTextbox.Text == "0")
{
//string is either null, empty or 0
}
else
{
//string has a value
}
if (!(String.IsNullOrEmpty(MyTextbox.Text) || MyTextbox.Text == "0"))
{
//string has a value
}
else
{
//string is either null, empty or 0
}
Related
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();
}
I want to convert below condition to ternary
if (!string.IsNullOrEmpty(objModel.Status))
{
if (objModel.Status == "0")
{
Model.Sort = "Result1";
}
else if (objModel.Status == "8")
{
Model.Sort = "Result2";
}
else
{
Model.Sort = "Result3";
}
}
I have tried as below but it went upto if and else not else if
Model.Sort = !string.IsNullOrEmpty(Model.Status)
? (Model.Status == "0" ? Retult1 : string.Empty)
: string.Empty;
Keep a local variable for simplification
var x = objModel.Status;
if (string.IsNullOrEmpty(x))
{
Model.Sort = x=="0" ? "Result1" :
x=="8" ? "Result2" :
"Result3";
}
you can have ternary operator like this
a ? b : c ? d : e
to get this:
if (a) {
b
}
else if (c) {
{
d
}
else {
e
}
in your case
objModel.Status == "0" ? Model.Sort = "Result1" : objModel.Status == "8" ? Model.Sort = "Result2" : Model.Sort = "Result2";
I hope this helps.
You can write your code using ternary operators like this:
Model.Sort = string.IsNullOrEmpty(objModel.Status) // if (string.IsNullOrEmpty(Status))
? Model.Sort // Model.Sort = Model.Sort;
: objModel.Status == "0" // else if (Status == "0")
? "Result1" // Model.Sort = "Result1";
: objModel.Status == "8" // else if (Status == "8")
? "Result2" // Model.Sort = "Result2";
: "Result3"; // else Model.Sort = "Result3";
Where the first condition represents the if condition, and then each statement after a : operator that is a comparison represents an else if, and finally the result after the last : represents the final else assignment.
The first condition is kind of a "dummy" condition (because if it's true nothing really changes*), but is required if we want to include the IsNullOrEmpty check in the ternary operations, since the ternary operator has to return a value in both the true and false cases.
I'm not sure if the dummy assignment would get optimized away or if the setter is called in that "dummy" case. If the setter is called then potentially this could have a different effect than your original code, depending on what the setter code does.
I am creating a database based desktop application and stuck in a problem..Actually I am new to Linq...
if (OP == "Delete")
{
tb = DB.TblPurchase.FirstOrDefault(e => e.PID.Equals(ID) || e.PItemName.Equals(ItemName) || e.PCategory.Equals(Category) || e.PDate.Equals(Date)); // returns null on comparing date
DB.Delete(tb);
return "Deleted";
}
else if (OP == "Search")
{
tb = DB.TblPurchase.FirstOrDefault(e => e.PID.Equals(ID) || e.PItemName.Equals(ItemName) || e.PCategory.Equals(Category) || e.PDate == Date); // returns null on comparing date as well
return tb;
}
Starting of the function :
`public object AUDS_Purchase(string OP, int? ID = null, string ItemName = "",string Category = "", string Supplier = "", DateTime? Date = null, int ? Rate = null, int? Quantity = null, int? Total = null)
{
using(var DB = new MYDBDB())
{
TblPurchase tb = null;`
Calling the function :
`dynamic _ID = Cmb_Search_ItemID.SelectedIndex == -1 ? null : Cmb_Search_ItemID.SelectedValue;
dynamic _ItemName = Cmb_Search_ItemName.SelectedIndex == -1 ? null : Cmb_Search_ItemName.SelectedValue.ToString();
dynamic _ItemCategory = Cmb_Search_ItemCategory.SelectedIndex == -1 ? null : Cmb_Search_ItemCategory.SelectedValue.ToString();
dynamic _Date = Search_Item_Date;
dynamic res;
if (Search_Item_Date.Checked == false)
{
if (_ID != null || _ItemName != null || _ItemCategory != null)
{
res = tb.AUDS_Inventory("Search", Convert.ToInt32(_ID), _ItemName, _ItemCategory);
tb.ShowNewData(metroGrid1, res);
}
else
{
MetroMessageBox.Show(this, "No Value Given\nSelect a value", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
else
{
res = tb.AUDS_Inventory("Search", Convert.ToInt32(_ID), _ItemName, _ItemCategory, Date:_Date);
tb.ShowNewData(metroGrid1, res);
}`
Note : I am sure tb is null because I used breakpoint...
My table contains the records : Picture prove
Everything works fine with the database and the table...
This is my first post BTW..
Thanks In Advance :)
If the Date you are providing in the function contains different time then that might be the cause. As I can see from your database picture you are trying to compare date only. So you can try excluding time, it might work. You can try
e.PDate.Date == Date.Date in your function.
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;
}
I am a noob, I am stuck on this code.
I am taking input from user in a textbox and saving it in a string. Then I want to run a loop until the string ends and I put if condition for different characters....
string que;
que = textBlock1.Text;
while (!que[i].Equals('\0'))
{
int res;
if (int.TryParse(que[i].ToString(), out res) || que[i].ToString() == "x" || que[i].ToString() == "/" || que[i].ToString() == "^")
{
f[j] = f[j] + que[i].ToString();
}
if (que[i].ToString() == "+" || que[i].ToString() == "-")
j++;
i++;
}
Can someone please guide me? What should I do??
Use:
textBlock1.Text.Lenght
That way you can know the length of the string.
Have you tried foreach(char c in que){ /*your code*/ } ?
If you want to just run through the loop until the end of the string, a simple condition like this should do:
int i = 0;
while (i < que.Length )
{
// Your code
}