RBrattas
RBrattas

Reputation: 121

DataGridViewCell.Value.get return null

How do I handle Object reference not set to an instance of an object; DataGridViewCell.Value.get return null? Null is okay, but I do not want an exception:

DataGridViewRow im_DataGridViewRow = vmpi_DataGridView.Rows .Cast<DataGridViewRow>() .Where(r => r.Cells[0].Value.ToString().Equals("HELP")) .First();

Upvotes: 0

Views: 347

Answers (4)

RBrattas
RBrattas

Reputation: 121

This work, thank you! You get im_DataGridViewRow == null and no exception: DataGridViewRow im_DataGridViewRow = vmpi_DataGridView.Rows .Cast<DataGridViewRow>() .FirstOrDefault(r => (bool)(r.Cells[vmp_COLUMN_Index_Int32]?.Value?.ToString().Equals(vmp_COLUMN_Value_string) ?? false));

Upvotes: 0

Patrick Beynio
Patrick Beynio

Reputation: 858

You can simply use null-conditionals ?. and null-coalescing ??, to get rid of null exceptions from the predicate, like:

r.Cells[0]?.Value?.ToString().Equals("HELP") ?? false

FirstOrDefault
If you don't want an exception, if no item matches the criteria you could use FirstOrDefault.
Also, like izzy mentioned you could simplify you code, by omitting Where and passing the predicate to First or FirstOrDefault instead:

.Cast<DataGridViewRow>()
.FirstOrDefault(r => r.Cells[0]?.Value?.ToString().Equals("HELP") ?? false)

FirstOrDefault will return the default if nothing is found, so null for class types and the default value for struct types

First
or if you actually want to throw an Exception if the item is not found, you can keep using First:

.Cast<DataGridViewRow>()
.First(r => r.Cells[0]?.Value?.ToString().Equals("HELP") ?? false)

Upvotes: 1

Mahmoud Ramadan
Mahmoud Ramadan

Reputation: 662

try FirstOrDefault() can return a Default value of something other than null

DataGridViewRow im_DataGridViewRow = vmpi_DataGridView.Rows .Cast() .Where(r => r.Cells[0].Value.ToString().Equals("HELP")) .FirstOrDefault();

Upvotes: 0

RBrattas
RBrattas

Reputation: 121

for (Int32 vm_ROW_Counter_Int32 = 0; vm_ROW_Counter_Int32 < vmpi_DataGridView.Rows.Count - 1; vm_ROW_Counter_Int32++)
            {
                for (Int32 vm_COLUMN_Counter_In32 = 0; vm_COLUMN_Counter_In32 < vmpi_DataGridView.Rows[vm_ROW_Counter_Int32].Cells.Count; vm_COLUMN_Counter_In32++)
                {
                    if (vm_COLUMN_Counter_In32 == vmp_COLUMN_Index_Int32)
                    {
                        vm_COLUMN_Value_string = vmpi_DataGridView.Rows[vm_ROW_Counter_Int32].Cells[vm_COLUMN_Counter_In32].Value.ToString();
                        
                        if (vm_COLUMN_Value_string.Contains(vmp_COLUMN_Value_string))
                        {
                            vmpi_DataGridView.Rows[vm_ROW_Counter_Int32].Selected = true;
                            vmo_FOUND_boolReturn = true;
                        }
                    }
                }

            }

Upvotes: 0

Related Questions