btsm btsm - 2 years ago 91
ASP.NET (C#) Question

Can't assign data table value into string

Hey guys a have a really simple data table, which is imported via excel by this:

cmdExcel.CommandText = "SELECT * From [" + SheetName + "A:B]";
oda.SelectCommand = cmdExcel;

I don't use any header, so the names of columns are default - F1 and F2. The thing is, that I couldn't assign any value from the second column to the variable. But the values from the first one could be assigned properly.

string firstColumn = dt.Rows[1]["F1"] as string;
string secondColumn = dt.Rows[1]["F2"] as string;

I attached a screen, where you can see, what is in data table. In firstColumn is stored "ABC" which is alright, but the secondColumn value is null. It should be easy, but something is wrong here and I have no idea what. Can you help me?

Attached image

Answer Source

Explicitly cast it to Int32 instead of string like below:

int secondColumn = Convert.ToInt32(dt.Rows[1]["F2"]);

Your screen shot shows it as integer value. So if you cast it to integer, it should work.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download