1
 if((string)row["ProductID"].ToString() == txtBarcode.Text)

I want to search a row if the value of the txtbox is the same as my datatable but i have an error.. it says that Possible unintended reference comparison; to get a value comparison, cast the left hand side to string. i just use .ToString() and Convert.ToString() but still have that error.

1
  • 4
    remove explicit cast (string) if you are using ToString Commented Mar 16, 2014 at 13:16

3 Answers 3

2

Your .ToString() is converting the row value to a string, so you don't also need to cast it on the left with (string)

Ie. if(row["ProductID"].ToString() == txtBarcode.Text)

Personally, I'd stare clear of using == operator with anything but ints, chars and whether this instance is that instance.

A better way of comparing strings is to use string.Equals(string) string.contains(string) or string.indexOf(string)

Sign up to request clarification or add additional context in comments.

3 Comments

In his case, String.Equals would be a better choice.
String.Contains(String) and String.IndexOf(String) are clearly wrong advices, as they return positive results in case of "Foo Bar".IndexOf("Foo");. Better use String.Equals as @Scott suggested.
@Oybek, I do mention as general options for comparing strings. Have added string.Equals though.
1

Note : if you are comparing with TextBox value then it is better to trim the values before comparing to remove the whitespaces using Trim() method.

Solution 1: if you want to find the excat match then you need to use Equals() method.

if(row["ProductID"].ToString().Equals(txtBarcode.Text.Trim())
{

/* do something*/

}

Solution 2: if you want to find the part of the string then you can use String.Contains() method as below:

if(row["ProductID"].ToString().Contains(txtBarcode.Text.Trim())
{

/* do something*/

}

Comments

0

You need to do one of the above. Either do a cast (string)row["ProductId"] or Convert.ToString(row["ProductId"]) for converting the value to string. But casting using (string)row["ProductId"] is likely to throw InvalidCastException. So may be ToString() would be better.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.