I have a scenario where I am inserting values in Gridview row. So when I insert the row for the first time. Acutally the session value is ""
But while checking like this
if (Convert.ToString(Session["RecdInfo"]) != null || Convert.ToString(Session["RecdInfo"]) != "")
{
if (strMode == "M")
{
FunFillGrid();
DtRecdInfo = (DataTable)Session["RecdInfo"];
}
DtRecdInfo = (DataTable)Session["RecdInfo"];
}
else
{
BindDataTable();
}
The condition is getting true as Instead it should get false and go inside the else part.
I tried with Session["RecdInfo"]) but still it is going inside the IF condition. any reasons why it is happening like this ?
I think your condition is not correct because if your session is "" than it is not null so condition will be true.
You can try this first check if session is not null than check if it is not empty string
if (Session["RecdInfo"] != null)
{
if (!string.IsNullOrEmpty(Session["RecdInfo"] as string))
{
}
}
Related
I am checking if the selected row's cell 7,8,9 is null or not. However it only display "enabled" even when all of the cell's value are null. Here is my code
private void btnTest_Click_1(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dgvReceivingproducts.Rows)
{
if (row.Cells[7].Value != null && row.Cells[8].Value != null && row.Cells[9].Value != null)
{
lblchecker.Text = "enabled";
}
else
{
lblchecker.Text = "disabled";
}
}
}
There could be two faults in this code:
1. The one mentioned by all answers above
2. Do you realize that lblchecker.Text will have a value corresponding to only the last row in your GridView?? (your logic seems incorrect, are you trying to set a value for each row? because now this is not what the code results in.)
Some good-practice suggestions:
1. Avoid using indexes. What if you later rearrange columns? Try using column names instead
2. A better approach would be to use DataKeys
3. And even better approach would be if this "enabled"/"disabled" value is pre-calculated i.e. prior to data binding. May be you could do this in SQL, or in your Business Layer. It depends on the logic behind this
UPDATE:
You could indicate "enabled" value per row if you set a value within each row. Using your code, a possible approach could be something like that:
private void btnTest_Click_1(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dgvReceivingproducts.Rows)
{
if (row.Cells[7].Value != null && row.Cells[8].Value != null && row.Cells[9].Value != null)
{
row.Cells[X].Value = "enabled";
}
else
{
row.Cells[X].Value = "disabled";
}
}
}
Have you tried using Convert.IsDBNull() instead of !=null
you could try this::
if ((row.Cells[7].Value != null && row.Cells[8].Value != null && row.Cells[9].Value != null)
|| (row.Cells[7].Value != DBNull.Value && row.Cells[8].Value != DBNull.Value && row.Cells[9].Value != DBNull.Value))
{
lblchecker.Text = "enabled";
}
else
{
lblchecker.Text = "disabled";
}
If do not function use the IsNullOrWhitespace function to test:
String.IsNullOrWhitespace(row.Cells[8].Value... )
I have a litte problem with this if statement:
if (selectedlabel.Text!=null|| selectedlabel.Text!=""|| selectedlabel!=null)
{
basketID = int.Parse(selectedlabel.Text); //nullpointer Value Can not be null
}
Why doesn't this work?
I have set a breakpoint and I see the selectedlabel.Text is null:
You use || instead of the correct &&
if (selectedlabel != null && selectedlabel.Text != null && selectedlabel.Text != "")
{
basketID = int.Parse(selectedlabel.Text);
}
But this is more concise and works too:
if (selectedlabel != null && !String.IsNullOrEmpty(selectedlabel.Text))
{
basketID = int.Parse(selectedlabel.Text);
}
Use int.TryParse to ensure that it's a valid integer:
int basketID;
if(selectedlabel != null && int.TryParse(selectedlabel.Text, out basketID))
{
// ...
}
With C#6 you can also use the null-conditional operator:
int basketID;
if(int.TryParse(selectedlabel?.Text, out basketID))
{
// ...
}
First of all you should check for nulls (because you're trying to access object's instance fields/properties) :
if(selectedlabel != null)
// or
if(!ReferenceEquals(selectedlabel, null))
Then what you're doing is just checking if string is null or empty ( on which c# has buil-in methods ) : string.IsNullOrEmpty(selectedlabel.Text)
Now you just have to connect these using && operator which checks if both are true, but fails if first check is false. Knowing that it will fall back when first condition is not met you can combine this into :
if (!ReferenceEquals(selectedlabel, null) && !string.IsNullOrEmpty(selectedlabel.Text))
{
// your code here
}
But another issue is basketID = int.Parse(selectedlabel.Text);. As i often says leave some margin for errors which means do not assume that user is smart ( better way! always assume that user is dumb as hell ) so instead of putting a number, user will input something like "please enter number 123 here" and it will kill your application.
To get rid of this just TryParse instead:
int.TryParse(selectedlabel.Text, out basketID);
Okay so combining ALL of the above, the result should be something like :
if (!ReferenceEquals(selectedlabel, null) && !string.IsNullOrEmpty(selectedlabel.Text))
{
if(!int.TryParse(selectedlabel.Text, out basketID))
{
// user entered text that is unconvertible to int
}
}
Change to
if (!string.IsNullOrEmpty(selectedlabel?.Text))
{
basketID = int.Parse(selectedlabel.Text);
}
your if statement should be equal to null if you want it to check for null, then it should be this
if (selectedlabel.Text==null|| selectedlabel.Text!=""|| selectedlabel!=null)
{
basketID = int.Parse(selectedlabel.Text); //nullpointer Value Can not be null
}
else it will not display the error you are trying to avoid.
hope it helps
Hi I am checking datatable row value. If the value is not null or empty then checking for the value if it is a number. Otherwise add in to the error list. If the value is null or empty then assign null.
The code is working fine but I want to check if there is any better way to do this. Any suggestions would be appreciated.
here is my code.
if (!(row.IsNull("limit") || row["limit"].ToString().Length == 0))
{
//Check if value is number
if (int.TryParse(row["limit"].ToString().Trim(), out n))
{
query.limit = Convert.ToInt32(row["limit"].ToString().Trim());
}
else
{
errorList.Add("limit: Value:" + row["limit"].ToString());
}
}
//if value is null then assign null
else
{
query.limit = null;
}
Few points I have to mention here:
By using int.TryParse to parse the row["limit"] you will get the converted value in the out parameter, then you need not convert the same again to an integer using Convert.ToInt32, use the out parameter instead.
The first if can be simplified using NullConditional operators(?.).
There may be chances for getting row as null, in such cases, you need to check for null before accessing row["limit"] otherwise NullReference will be the result
I think it will be more clear and simple if you do like this:
if (row != null && row["limit"]?.ToString() != "") // means row["limit"] definitely has some value
{
int currentLimit = 0;
if (int.TryParse(row["limit"].ToString().Trim(), out currentLimit))
{
query.limit = currentLimit ;
}
else
{
errorList.Add("limit: Value:" + row["limit"].ToString());
}
}
else
{
query.limit = null;
}
If you are not using c# 6 then row["limit"]?.ToString() will not work in this case you have to use the condition as like this:
if (row != null && row["limit"] != null && row["limit"].ToString() != "")
I have a validation method with 5 validation elements to it, 4 of which work as intended but 1 does not, question is why not?
The issue I have is with Validating "CompetitionCourse". I want the IsValid to be true only if the combobox cbCourseRound1 is not blank. At the moment this is validating regardless of this combobox being blank or populated. All other validations are working,
private bool Validate(Competition compSetup)
{
string CompetitionName = compSetup._CompetitionName;
int CompetitionFormat = compSetup._CompetitionFormatId;
string CompetitionGender = cbGenderOfCompetiton.Text;
string CompetitionMarker = cbMarker.Text;
string CompetitionCourse = cbCourseRound1.Text;
if (!CompetitionName.Equals(string.Empty) && !CompetitionGender.Equals("Mixed") && CompetitionFormat.Equals(1) && !CompetitionCourse.Equals(string.Empty) &&
((CompetitionGender.Equals("Female") && CompetitionMarker.Equals("Red")) || (!CompetitionGender.Equals("Female") && !CompetitionMarker.Equals("Red"))))
{
IsValid = true;
}
else
{
IsValid = false;
}
return IsValid;
}
depends on what's in CompetitionCourse. You'll have to check that yourself by debugging your code.
You'd be better off making explicitly sure that CompetitionCourse contains null if the ComboBox text field is blank (because I suspect it contains ""):
CompetitionCourse = (string.IsNullOrEmpty(cbCourseRound1.Text)) ? null : cbCourseRound1.Text;
At the moment this is validating regardless of this combobox being
blank or populated.
Check the Items property of the combobox, not the Text Property like.
cbCourseRound1.Items != null && cbCourseRound1.Items.Count > 0
First of all, using .Equals for strings is very Java. C# has operator overloading which looks a lot nicer:
if(CompetitionName!="" && CompetitionGender!="Mixed" ...)
As for the test itself, you'll need to set a break point and see what `CompetitionCourse has. My guess is it's not an empty string, but rather has some spaces in it. Try using
...!CompetitionCourse.Trim()!=""
Your code is diffficult to read, i'll try to simplify it:
private bool Validate(Competition compSetup)
{
bool isValid = cbGenderOfCompetiton.Text != "Female" && cbMarker.Text == "Red";
if (!isValid)
{
isValid = !string.IsNullOrEmpty(compSetup._CompetitionName);
if (isValid)
isValid = compSetup._CompetitionFormatId.Text == "Female";// this is redundant: cbGenderOfCompetiton.Text != "Mixed";
if (isValid)
isValid = CompetitionFormat == 1;
if (isValid)
isValid = cbCourseRound1.SelectedIndex != -1;
if (isValid)
isValid = cbMarker.Text == "Red";
}
return isValid;
}
Note that i've used the SelectedIndex instead of Combobox.Text because it's less error-prone.
Instead of using !Equals, use IsNullOrWhitespace, or IsNullOrEmpty. It works better.
May be you should try to trim the white space around the text box. For example, txtName.Trim();
Very simple I'm sure, but driving me up the wall! There is a component that I use in my web application that identifies itself during a web request by adding the header "XYZComponent=true" - the problem I'm having is, how do you check for this in your view?
The following wont work:
if (Request.Headers["XYZComponent"].Count() > 0)
Nor this:
if (Request.Headers.AllKeys.Where(k => k == "XYZComponent").Count() > 0)
Both throw exceptions if the header variable has not been set. Any help would be most appreciated.
if (Request.Headers["XYZComponent"].Count() > 0)
... will attempted to count the number of characters in the returned string, but if the header doesn't exist it will return NULL, hence why it's throwing an exception. Your second example effectively does the same thing, it will search through the collection of Headers and return NULL if it doesn't exist, which you then attempt to count the number of characters on:
Use this instead:
if(Request.Headers["XYZComponent"] != null)
Or if you want to treat blank or empty strings as not set then use:
if((Request.Headers["XYZComponent"] ?? "").Trim().Length > 0)
The Null Coalesce operator ?? will return a blank string if the header is null, stopping it throwing a NullReferenceException.
A variation of your second attempt will also work:
if (Request.Headers.AllKeys.Any(k => string.Equals(k, "XYZComponent")))
Edit: Sorry didn't realise you were explicitly checking for the value true:
bool isSet = Boolean.TryParse(Request.Headers["XYZComponent"], out isSet) && isSet;
Will return false if Header value is false, or if Header has not been set or if Header is any other value other than true or false. Will return true is the Header value is the string 'true'
Header exists:
if (Request.Headers["XYZComponent"] != null)
or even better:
string xyzHeader = Request.Headers["XYZComponent"];
bool isXYZ;
if (bool.TryParse(xyzHeader, out isXYZ) && isXYZ)
which will check whether it is set to true. This should be fool-proof because it does not care on leading/trailing whitespace and is case-insensitive (bool.TryParse does work on null)
Addon: You could make this more simple with this extension method which returns a nullable boolean. It should work on both invalid input and null.
public static bool? ToBoolean(this string s)
{
bool result;
if (bool.TryParse(s, out result))
return result;
else
return null;
}
Usage (because this is an extension method and not instance method this will not throw an exception on null - it may be confusing, though):
if (Request.Headers["XYZComponent"].ToBoolean() == true)
Firstly you don't do this in your view. You do it in the controller and return a view model to the view so that the view doesn't need to care about custom HTTP headers but just displaying data on the view model:
public ActionResult Index()
{
var xyzComponent = Request.Headers["xyzComponent"];
var model = new MyModel
{
IsCustomHeaderSet = (xyzComponent != null)
}
return View(model);
}
The following code should allow you to check for the existance of the header you're after in Request.Headers:
if (Request.Headers.AllKeys.Contains("XYZComponent"))
{
// Can now check if the value is true:
var value = Convert.ToBoolean(Request.Headers["XYZComponent"]);
}
if ((Request.Headers["XYZComponent"] ?? "") == "true")
{
// header is present and set to "true"
}
string strHeader = Request.Headers["XYZComponent"]
bool bHeader = Boolean.TryParse(strHeader, out bHeader ) && bHeader;
if "true" than true
if "false" or anything else ("fooBar") than false
or
string strHeader = Request.Headers["XYZComponent"]
bool b;
bool? bHeader = Boolean.TryParse(strHeader, out b) ? b : default(bool?);
if "true" than true
if "false" than false
else ("fooBar") than null
In dotnet core, Request.Headers["X-MyCustomHeader"] returns StringValues which will not be null. You can check the count though to make sure it found your header as follows:
var myHeaderValue = Request.Headers["X-MyCustomHeader"];
if(myHeaderValue.Count == 0) return Unauthorized();
string myHeader = myHeaderValue.ToString(); //For illustration purposes.