To avoid the exception first check your objects are not null before trying to call methods on them. Check for...
dataTABLE != null
Cells[0].Value != null
Cells[1].Value != null
That being said, you asked about the best possible way to achieve the task so here's some other things to think about.
You could just iterate through the data table using something like dataTable.AsEnumerable().Any( dr => ...);
to see if any rows matching your criteria already exist.
Whenever you need to compare strings to other strings or objects that could be null, you need to think carefully about your requirements and what a null reference means for you.
If cell[0].value == null
do you still want to go ahead and compare MyServerChecked
? If cell[0].value == null
and MyServerChecked == null
then should they be considered equal?
Similarly, how do you want to handle empty strings? Should an empty string be considered equal to null?
Here is a simple solution to get started. If the cells are null, it won't try to compare them. This may not be the behavior you want, but like I said, have a think about what null values and empty strings means for your particular scenario and code for it accordingly.
string MyServerChecked = "Something";
string ServiceName = service.ServiceName.ToString();
if (dataTable != null)
{
foreach (DataGridViewRow row in dataTable.Rows)
{
if (row.Cells[0].Value != null
&& row.Cells[1].Value != null
&& string.Equals(row.Cells[0].Value.ToString(), MyServerChecked, StringComparison.OrdinalIgnoreCase)
&& string.Equals(row.Cells[1].Value.ToString(), ServiceName, StringComparison.OrdinalIgnoreCase))
{
// Row already exists...
}
}
}
Using the overloaded string.Equals
method with a StringComparison
enum type means you don't have to convert to upper yourself. It also gives you some extra options for culture settings. Have a look at StringComparison Enumeration on MSDN for more info.