Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing int from DataRow cell [closed]

Tags:

c#

How could int value be parsed from DataRow cell?

Int32.Parse(item["QuestionId"].ToString());

This code works, but it looks too verbose. Also is it possible to handle DBNull values?

like image 739
Anthony Avatar asked Jul 18 '13 09:07

Anthony


2 Answers

If you know that it's an int you should just cast it accordingly, that's the safest and most efficient approach:

int questionId = item.Field<int>("QuestionId");  // similar to (int) item["QuestionId"]

The Field method also supports nullable types, so if it could be null:

int? questionId = item.Field<int?>("QuestionId");
if(questionId.HasValue) Console.Write(questionId.Value);

If it's actually a string(why?) you have to cast it to string and use int.Parse:

int questionId = int.Parse(item.Field<string>("QuestionId"));

If you really don't know what it's type is, you can use System.Convert.ToInt32:

int questionId = System.Convert.ToInt32(item["QuestionId"]);
like image 130
Tim Schmelter Avatar answered Nov 09 '22 08:11

Tim Schmelter


If what is put into that cell is actually just an int, use:

(int)item["QuestionId"]

Otherwise, check the runtime type of the value item["QuestionId"], if it is a byte for example, use (byte)item["QuestionId"]. If you're not sure, then:

Convert.ToInt32(item["QuestionId"])

will probably work, but that's less elegant.

like image 20
Jeppe Stig Nielsen Avatar answered Nov 09 '22 08:11

Jeppe Stig Nielsen