0

I have a simple foreach of datatable as:

foreach(DataRow designKey in designFolioList.Rows)
{

}

So I have 2 items into each row like:

enter image description here

So I want to get value of the first one I try:

foreach(DataRow designKey in designFolioList.Rows)
{
    var currentDesignKey = designKey[0] as string;
}

But currentDesignKey is always null? What am I doing wrong? How is the correct way to get item 0 from table?

2
  • Since it’s not a string you’ll always get a null when using as. You probably want .ToString() if you want it as a string Commented Oct 23, 2018 at 19:17
  • The correct way of getting item 0 is designKey[0]. Why are you trying to convert it to a sting? It isn't a string. Commented Oct 23, 2018 at 19:19

1 Answer 1

4

Judging by that screenshot, designKey[0] is not a string, it's an int. Because it is not directly castable to a string, using as string on it will result in a null. Think of as as a form of cast that doesn't crash if it doesn't work out. This doesn't work out:

object o = 123;
string s = (string)o;

It crashes like this:

Run-time exception (line xx): Unable to cast object of type 'System.Int32' to type 'System.String'.

as doesn't crash, it just returns null for casts that don't work;

If you really want it as a string, call .ToString() on it. Otherwise, cast it to an int(or long/whatever it is)

foreach(DataRow designKey in designFolioList.Rows)
{
    var currentDesignKey = (int)designKey[0];
    var currentDesignKeyStr = designKey[0].ToString();
}

.ToString() works because object has .ToString(), and so does int (by way of override). ToString()ing an int, turns it into a string representation of itself: 123 -> "123"

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

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.