I am trying to check if there is at least one Textbox is not null as shown below but that condition will be true if all Textboxare not null not only one at least
foreach (TextBox cont in GB_Search.Controls.OfType<TextBox>())
{
if (string.IsNullOrEmpty(cont.Text))
{
// at least one control
}
}
You can use Linq for this.
The following will check that at least one should not be null and will return true if at least one text box contains value in it:
var oneHasValue = GB_Search.Controls.OfType<TextBox>()
.Any(x=>!string.IsNullOrEmpty(x.Text));
and the following would return true if all are not null or empty:
var allContainValue = GB_Search.Controls.OfType<TextBox>()
.All(x=>!string.IsNullOrEmpty(x.Text));
System.Windows.Controls TextBox
The default value of the TextBox.Text property is an empty string, so unless you've explicitly set it as null I don't see why you'd want to check for nullity.
You're most likely looking to see if any of the TextBox.Text is empty like this:
var result = GB_Search.Controls.OfType<TextBox>()
.Any(textBox => textBox.Text.Length == 0);
or if there is any non-empty:
var result = GB_Search.Controls.OfType<TextBox>()
.Any(textBox => !(textBox.Text.Length == 0));
Note - I've specifically used the Length property of the TextBox to check if it's empty as opposed to String.IsNullOrEmpty, this is simply because as mentioned above TextBox.Text is by default an empty string and as you've mentioned in the comments section under your post you're not explicitly setting it to null, thus there's no need to use String.IsNullOrEmpty as it performs a redundant check that you don't need.
System.Windows.Forms TextBox
Looking to see if any of the TextBox.Text is null or empty:
var result = GB_Search.Controls.OfType<TextBox>()
.Any(textBox => string.IsNullOrEmpty(textBox.Text));
or if there is any non null and non empty:
var result = GB_Search.Controls.OfType<TextBox>()
.Any(textBox => !string.IsNullOrEmpty(textBox.Text));
Related
Searching through a column in a spreadsheet I notice that the second line will exception ("Nullable object must have a value.") when it comes across a blank field, however the first line will succeed. I have to add the Bool cast to the second line because otherwise I get "Cannot convert Nullable<bool> to bool". I assume this is the issue, but is there a way around that to allow blank fields to be checked?
keyFoundCell = _ws.Cells["a:a"].FirstOrDefault(cell => cell.Value?.ToString() == field.Key);
keyFoundCell = _ws.Cells["a:a"].FirstOrDefault(cell => (bool)cell.Value?.ToString().Equals(field.Key, StringComparison.OrdinalIgnoreCase));
In both EPPlus and Excel Interop you can read a cell's contents using the Text property instead of the Value property if you want to operate on the cell's visible contents and avoid nulls. Value returns an object which might be null, but Text returns the visible text as a string which can be empty but won't be null.
If we're using Value.ToString() or Value?.ToString() then chances are we'd be better off with Text because that's a giveaway that we want the text we see, not the value.
What's happening here is that the ?. operator will return null right away if the left hand side of the operator is null.
So, when cell.Value is null, the first line works because you're doing a direct comparison using the == operator, which will return a bool. In other words, null == field.Key returns false (unless field.Key is null, of course).
The second line does not work without a cast because if the value is null, then the ?. operator returns null and the rest of the line is ignored (.ToString() is never called). So the exception you're getting is due to the fact that the if condition must return a bool, yet it's returning a Nullable<bool> instead.
One way to fix this is to simply check for null first. This will not compare any objects where cell.Value == null:
keyFoundCell = _ws.Cells["a:a"].FirstOrDefault(cell =>
cell.Value != null &&
cell.Value.ToString().Equals(field.Key, StringComparison.OrdinalIgnoreCase));
Another way you can do this is to use the static Equals method of the string class, which will allow one or more null arguments. This will include results where cell.Value == null (and will return true for those cases where field.Key is also null):
keyFoundCell = _ws.Cells["a:a"].FirstOrDefault(cell =>
string.Equals(cell.Value?.ToString(), field.Key, StringComparison.OrdinalIgnoreCase));
maybe try:
keyFoundCell = _ws.Cells["a:a"].FirstOrDefault(cell => (bool?)cell.Value?.ToString().Equals(field.Key, StringComparison.OrdinalIgnoreCase)) ?? false;
I am instantiating an Associate object and assigning properties to it from txtboxes inside of my main form. What is the best practice for null checking? Is it to check each and every property with an if statement before I assign it or is there something a bit better? Here is my code:
Associate updateAssociate = new Associate();
updateAssociate.AssocID = txtAssocId.Text;
updateAssociate.FirstName = txtFname.Text;
updateAssociate.LastName = txtLname.Text;
updateAssociate.HireDate = Convert.ToDateTime(txtHireDate.Text);
updateAssociate.ContractEndDate = Convert.ToDateTime(txtContractEnd.Text);
updateAssociate.TerminationDate = Convert.ToDateTime(txtTerminationDate.Text);
updateAssociate.FullPartTimeID = cboFullPart.SelectedText;
updateAssociate.PrimaryRole = cboPRole.SelectedText;
Based on your comment to the question:
If it is a text box then it would be the .Text property I would want to check for null or blank values before I assign them to the object
You can use the null coalescing operator to check for null values when assigning like that:
updateAssociate.AssocID = txtAssocId.Text ?? string.Empty;
or:
updateAssociate.AssocID = txtAssocId.Text ?? someDefaultValue;
That way if txtAssocId.Text is null then you would assign your defined default to the object property instead of null.
Though I'm not entirely sure a TextBox's .Text property would ever be null instead of an empty string. Maybe you want to check for both?:
updateAssociate.AssocID = string.IsNullOrEmpty(txtAssocId.Text) ? someDefaultValue : txtAssocId.Text;
In C# 6 it would be null-conditional operator.
updateAssociate.AssocID = txtAssocId?.Text;
In prior versions of c# you can write a method to eliminate code duplication. Something like this:
public static T CheckNull<T>(Func<T> canBeNull) where T : class
{
try
{
return canBeNull();
}
catch (NullReferenceException)
{
return default(T);
}
}
And use it like this
updateAssociate.AssocID = CheckNull(() => txtAssocId.Text);
Then you can wrap any code that can throw a null reference into lambda, pass it to this method and no longer bother with it.
I have this below script in my Class.
aggrgt.Add(new PlainBrgDataSummaryChartAggrgt
{
label = m.label,
goal = m.goal,
groupCode = m.groupCode,
groupValue1 = m.groupValue1,
graphSwitch = m.graphSwitch,
orderByAsc = m.orderByAsc,
metricID = m.metricID,
scoreWk1 = metricscoreWk1.metricScore1,
});
The condition I want is when metricscoreWk1 is null, scoreWk1 = metricscoreWk1.metricScore1 is eliminated.
This may help you:
scoreWk1 = metricscoreWk1.metricScore1 ==null ? 0 : metricscoreWk1.metricScore1
That is, if the value of metricscoreWk1.metricScore1 is null 0(or else any default value) will be assigned else the original value will be assigned to scoreWk1
You can't put "" for Double, the closest analogue, INHO, is Double.NaN (Not A Number):
// Let's have Double.NaN for unknown/undefined etc. value
scoreWk1 = metricscoreWk1.metricScore1 ?? Double.NaN;
You could either:
Create the PlainBrgDataSummaryChartAggrgt object without setting the scoreWk1 field. If metricscoreWk1 is not null, you then set the field and you then add the object to the list.
If you have a setter for metricScore1, you could add a check wherein you ensure that metricscoreWk1 is not null. If it is, the value is not updated.
The second option would allow you to keep your current initialization structure, but the first is more explicit. Should you opt for the second approach, I'd recommend you document it.
I have a custom class Diary, which has a nullable property DeadlineType
On one of my Forms I have a ComboBox in DropDownList mode, which is populated with all the possible values that DeadlineType can take. When a Diary is selected, the form is populated with all the properties, but I have an issue with the DeadlineType property in that, when it is null, it requires more code than I believe it should i.e.
if (amendDiary.DeadlineType != null)
{
cboDeadlineType.Text = amendDiary.DeadlineType.ToString();
}
else
{
cboDeadlineType.Text = null;
}
I am sure there must be a more concise way to achieve this, or certainly hope so, because this scenario is repeated a lot throughout my application i.e. posting nulls to ComboBoxes.
I did try
cboDeadlineType.Text = amendDiary.DeadlineType.ToString() ?? null
But that gives an 'Object not set to an instance' error.
Try this:
cboDeadlineType.Text = (amendDiary.DeadlineType ?? "").ToString();
Note that setting the ComboBox.Text to null means the same as setting it to "" (The combo Text is empty in both cases).
Another solution is use the Convert.ToString method:
cboDeadlineType.Text = Convert.ToString(amendDiary.DeadlineType);
With that solution, if the input is null, the cboDeadlineType.Text is assigned exactly to null.
try
cboDeadlineType.Text = amendDiary.DeadlineType!=null ?amendDiary.ToString() :"";
Hopefully this is an easy one. Is there a way to test for an "empty" field using DataRow? The following work fine for testing against a field with null values, unfortunately, the column I'm dealing with are either populated with data or are just "empty". Is there an approach in C# I'm missing? Thanks
if (Particle.Tables.Count == 0 || pDr.ItemArray[1].ToString() == "")
tblParticle.Append("No Data");
you can use stirng.isNullorEmpty to check for empty fields. String.isNullorEmpty
if (Particle.Tables.Count == 0 || string.isNullorEmpty(pDr.ItemArray[1].ToString()))
{
tblParticle.Append("No Data");
}
.
if (string.IsNullOrEmpty(pDr.ItemArray[1].ToString()))
{
tblParticle.Append("No Data");
}
else
{
//else do something else
}
checking for NULL will not hurt keep in mind that Null and Empty are two different things
See DataRow.IsNull method - it accepts a column name or index
and returns whether it is NULL
The following assumes we are talking about a string (VARCHAR/CHAR) column:
If you don't care if it is null or an empty string, and always want an empty string back, you can use DataRow["name"].ToString()
If you want your string object to become null or empty just like the field value, you can use DataRow["name"] as string
If you want to get an exception in case of NULL, you can use (string) DataRow["name"]