Check whether an Object is empty or null - c#

I have a DataGridView and added a column called SellQty and a Checkbox at index 0. User has to enter int value when he selects a checkbox. If not I am showing a message to enter the value. Now the problem is I am getting the value from the SellQty cell and storing it in an object and checking whether it is null.
object SellQty = gvProductBatch.Rows[i].Cells["txtSellQty"].Value;
if(SellQty!=null)
// do something
else
// ..Show message.
This works fine. But the problem is when the user enters a value and deletes it, the value stored in it is {} i.e. empty. I would like to know how to check an object is empty. I have googled for the same but didn't find answer to handle empty object. All results were for if object is null.

You can get the actual edited Value by using the .EditedFormattedValue
if (string.IsNullOrWhiteSpace(gvProductBatch.Rows[i].Cells["txtSellQty"].EditedFormattedValue.ToString())
{
//Do something
}

Related

Pass Text from form to formula field

I create a formula for conditional sum. Here is sample code.
` if {Customer.Region} = 'VA'
then 1
else 0
To sum records in the state of Virginia:
if {Customer.Region} = 'VA'
then {Orders.Amount}
else 0`
I want to input the value 'VA' from textbox of a form dynamically. When i input 'VA' in my form and click a button that value go to the formula if {Customer.Region} = 'textbox Value'. How can i do that?
Create a Parameter Field. This will allow you to be prompted by the report to input a value. So if you created a Parameter Field and name it "MyString", then you could do your comparison to your report field as:
If {Customer.Region} = {?MyString}
//Do something if true
Else
//Do something if false
Please note, this will only prompt you to input a value for the Parameter Field when the report is executed. If you want to compare using a second input value, you will need to run the report again for each additional value.

not able to pull datetime type from datagridview using C#

I have this Datagridview, where I'm inserting a new row, but the value for the column
expected_date, it is getting a null value in the program, when in fact I have typed in 01/01/2099,
I've tried inserting manually in my code and it works, but when I'm doing something like :
dataGridView2[fieldIndex, rowIndex].Value
in order to grab 01/01/2099 from the Datagridview and use it in my code, it just returns null or "" (Empty String).
I'm also just not sure why it's only for the column that uses a date that causes the trouble.

Null Reference Exception when int parsing DataGridView row values

The purpose of the code below is to sum up all the index 3 of a datagridview that would continue on adding endlessly in an order system and display it in a label named Price.
private void Add_Click(object sender, EventArgs e)
{
dgvSelected.Rows.Add(dgvItem.SelectedCells[0].Value.ToString(),
dgvItem.SelectedCells[1].Value.ToString(),
dgvItem.SelectedCells[2].Value.ToString(),
dgvItem.SelectedCells[3].Value.ToString());
for (int i = 0; i < dgvSelected.Rows.Count; i++)
{
price = price + int.Parse(dgvSelected.Rows[i].Cells[3].Value.ToString());
Price.Text = price.ToString();
}
}
The problem is that it keeps saying:
"Object reference not set to an instance of an object."
...as an error for the following line:
price = price + int.Parse(dgvSelected.Rows[i].Cells[3].Value.ToString());
There is supposed to be no null in the table but the error keeps on insisting that there is a null. There are multiple rows in the table but the only row it can read is the 1st row. When it comes to the 2nd row which has values, it then will say the error concerned.
Of course the programming languge isnt wrong. Its reporting to you that you are tring to use an object reference which is in fact null.
In the section dgvSelected.Rows[i].Cells[3].Value.ToString() one of the following is null
dgvSelected
dgvSelected.Rows
dgvSelected.Rows[i]
dgvSelected.Rows[i].Cells
dgvSelected.Rows[i].Cells[3]
dgvSelected.Rows[i].Cells[3].Value
As you can see, you should be doing alot of checking to make sure none of these objets is null
Edit: Strikeout some of those, as rightfully pointed out in comments the loop would not be entered if those were null.
It's you, on this line something is null.
price = price + int.Parse(dgvSelected.Rows[i].Cells[3].Value.ToString())
It is almost certainly that there is not a dgvSelected.Rows[i].Cells[3] for the particular value of i that throws the exception. Put a breakpoint on that line and check dgvSelected.Rows[i].Cells.Length.
You are adding only one row to dgvSelected. I assume, there are other rows in there, added somewhere else with less columns. Check all places where you access dgvSelected and make sure no rows with less than 4 columns are added.
You can simply use a debugger to check what exactly the problem is.
Since, others have already given a 'broad' answer. I would suggest a slimmer 'possible' answer.
Append the below lines of code as the first line inside your loop, and the console output would give you the correst solution.
if(dgvSelected.Rows[i].Cells[3].Value==null){
Console.Writeline(String.Format("Row Index:{0}, Column Index:3 has an unexpected null value. Ignoring this row.", i)
continue;
}
Because, looking at your code, it seems less likely that Row/column object would be null.
All the best.

GridView OnRowDataBound, Cell's Text.Length

My datadsource is querying the table for a varchar column, that either comes out empty or comes out something like "1,2,3,4,5".
On the RowDataBound event I want to test if the string is not empty so I can substitute that string with an image or whatever.
But
e.Row.Cells[0].Text.Length
returns 9 for the populated Cells (and this is correct), and returns 6 for the empty ones.
Can someone explain this to me? It's not just in this one column.
Instead, always use String.IsNullOrEmpty method to check for empty strings.
So, in your current problem it would be:
if String.IsNullOrEmpty(e.Row.Cells[0].Text.Trim())
{
// code in here would execute when the Text property is empty/null
}

What's the best way to write "nulls" to SQL database when presenting options in combobox?

I'm writing a front end to a database, presenting options as comboboxes. And I need to be able to return nulls to the database.
I have a solution at the moment which involves 'fudging' a record into the query to populate the Datatable, then detecting the selection and hard coding null into my update statement if this item has been selected.
--GetDataByAvailableTechs query
SELECT tblLEMSCredentialsId, TechNumber
FROM tblLEMSCredentials AS aLEMSCreds
UNION ALL
SELECT '99999' AS Expr1, '<NONE>' AS Expr2
.
//populate combo box
BV_LEMSHIPDataSet.tblLEMSCredentialsDataTable dtAvailableTechs = taLEMSCreds.GetDataByAvailableTechs(selectedSerial);
cboTechNumber.DataSource = dtAvailableTechs;
.
//Save back to DB
if (lemsCredsID == 99999)
{
taDevice.UpdateQuery_Restage(null, selectedSerial);
}
else
{
taDevice.UpdateQuery_Restage(lemsCredsID, selectedSerial);
}
Can anyone suggest a better way of doing this please? I need to make the application cope with another 5 similar fields and don't want to create a multitude of if else versions of my update.
G
In the past I've used a similar approach but used minus numbers for the NULL values - that way you can you treat anything less than zero as NULL in one if statement.
This assumes that your ID's in the table are always positive though :)
Null object pattern. Make it return an empty string for the UI and provide a method call to extract the value when updating the database. In normal cases this will return your true value but the null object will override this behaviour to give you your null.
No magic numbers required and all you need to do is add this value to the start of the "bindable values" when you bind your control to the datasource.
You may put an string value as the combobox 'null value', for example: "thenullvalue" then parse combobox value to nullable int type (int?). For proper selection you will get the desired value, for 'null selection' you will get null (parsing "thenullvalue" to int will give you null) :)
Then save the value to database just as:
int? lemsCredsID = parseInt(combobox.Value);
//Save back to DB
taDevice.UpdateQuery_Restage(lemsCredsID, selectedSerial);
Depending of your db provider you might also need to convert nullable type null value to DBNull, like this:
taDevice.UpdateQuery_Restage((lemsCredsID==null ? DBNull : (int)lemsCredsID), selectedSerial);
Hope this helps.
If the value is intended to be null, pass null to the database would be a good solution, this reduces the extra logic handling for special values for nulls and it can be quite risky and ambiguous.
The view or application layer should be able to handle null either returned from database or passing into it.
e.g. you can convert null to string.Empty before binding the control as well as you can convert string.Empty to null before passing into the database.

Categories