ITMANAGER ITMANAGER - 5 months ago 30
C# Question

How to compare value of cell with string variable?

I have the following code:

string findID = pacients.findByUniqueCode(code);

foreach (DataGridViewRow row in dataGridView1.Rows)
{
if ((string)row.Cells["idDataGridViewTextBoxColumn"].Value == findID)
{

}
}


I get an error in line:

if ((string)row.Cells["idDataGridViewTextBoxColumn"].Value == findID)


It can not convert
row.Cells
to string. How to fix it?

Answer Source

to compare strings, both of your values has to be a strings which obliviously in your case is not a case!

So what you must do here to fix this is to convert your row.Cells["idDataGridViewTextBoxColumn"].Value to a string, and how to do that, depends of you, there are few ways but I will mention here two common ones,

you might do this by using build in .ToString() method, or you might use also build in Convert.ToString() method, it is up to you which you are going to choose, so you code might look like this:

if (Convert.ToString(row.Cells["idDataGridViewTextBoxColumn"].Value) == findID) 
{
   ....
}

or

if ((row.Cells["idDataGridViewTextBoxColumn"].Value).ToString() == findID)
{
   .....
}

Applying any of cases above should fix your issue.

Thanks