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?
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"]);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With