Code optimization for null or empty check - c#

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() != "")

Related

Retrieving single value from datatable how to check NULL

I am trying to compare the value of a row esmcost with psmcost of table wsmtbl but esmcost cost value is null due to which I am getting the following error:
Operator '<>' is not defined for type 'DBNull' and type 'DBNull'
Is there any way to change the null value to zero?
This is the C# code
ds.Tables["wsmtbl"].Rows[0]["esmcost"] <> ds.Tables["wsmtbl"].Rows[0]["psmcost"]
Try the following.
Decimal esmcost;
if (ds.Tables["wsmtbl"].Rows[0]["esmcost"] == DBNull.Value)
esmcost = 0.00;
else
esmcost = Convert.ToDecimal(ds.Tables["wsmtbl"].Rows[0]["esmcost"]);
Decimal psmcost;
if (ds.Tables["wsmtbl"].Rows[0]["psmcost"] == DBNull.Value)
psmcost = 0.00;
else
psmcost = Convert.ToDecimal(ds.Tables["wsmtbl"].Rows[0]["psmcost"]);
if (esmcost != psmcost)
{
...
}
One could use the ternary operator syntax but I chose the above for readability reasons. For example:
Decimal esmcost = ds.Tables["wsmtbl"].Rows[0]["esmcost"]
== DBNull.Value ? 0.00 : Convert.ToDecimal(ds.Tables["wsmtbl"].Rows[0]["esmcost"]);
Try this,
if(ds.Tables["wsmtbl"].Rows[0]["esmcost"] == DBNull.Value)
{
ds.Tables["wsmtbl"].Rows[0]["esmcost"] = 0;
}
ds.Tables["wsmtbl"].Rows[0]["esmcost"] != ds.Tables["wsmtbl"].Rows[0]["psmcost"];

How to check if specific column of selected row in Datagridview is null?

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... )

Session conditions are not working properly

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))
{
}
}

C# Check if a UILabel is not null not work

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

Property value is not valid typed data set

I am using typed data set in my application and I have a data table with two columns which are of System.Int32.AllowDBNULL = true and NULLVALUE = throw exception and default value = 1. I am using this property of datatable in my code like this:
if (rr.ForenameStatus != -1 && rr.ForenameStatus == 0)
{
}
but I am getting this error:
The value for column 'ForenameStatus' in table 'Registrant' is DBNull.
I tried to change NULLVALUE of column to NULL or empty in dataset properties but I get error:
property value is not valid
I tried using this:
if (rr.ForenameStatus != System.DBNull.Value && rr.ForenameStatus == 0)
{
}
but It says Operator != can not be applied to operands of int and dbnull
Please suggest me solution to this.
Set AllowDBNULL = true and call IsForenameStatusNull method to check on NULL value.
Try this:
if (rr.ForenameStatus.ToString()!="" && rr.ForenameStatus == 0)
{
}
This is as an alternative. You may try converting the int value to string and compare against empty string to identify the nulls.

Categories