开发者

How can I convert this column value to an integer?

开发者 https://www.devze.com 2022-12-25 18:15 出处:网络
My C# code looks like this: myNum = dt.Columns[0]; myNum is an integer and dt is a datatable.The value in column 0 of dt is a string (\"12\"),开发者_开发知识库 but I\'d like to convert it to an int

My C# code looks like this:

myNum = dt.Columns[0];

myNum is an integer and dt is a datatable. The value in column 0 of dt is a string ("12"),开发者_开发知识库 but I'd like to convert it to an integer. How can I do this? I've tried:

myNum = int.Parse(dt.Columns[0]);

...but that doesn't work. Any ideas?


The values are stored in rows and not columns. Try this instead:

myNum = int.Parse(dt.Rows[0][0].ToString());


Your parse wasn't working because the parse method takes a string, and the data comes back as a simple object.

Also, the data is in the rows, so you have two options really, (I prefer the first):

// This converts the object directly to an integer
myNum = Convert.ToInt32(dt.Rows[0][0]); 

// This converts the object to a string, and then parses it into an integer
myNum = int.Parse(dt.Rows[0][0].ToString()); 


if Parse throws an exception, this means dt.Columns[0] is not a valid input. If you want to avoid exception, you can use int.TryParse which returns a boolean telling if the conversion was done or not successfully

EDIT: BTW, Darin must be right: your value is not stored in a column but in a cell


Use TryParse method to parse the Value :

int myNum = 0;
int.TryParse(dt.rows[0][0].ToString() , out myNum);

with above code , If an error occurs , The value of variable will be zero


Convert.ToInt32(dt.Rows[0][0])

The above would be better, if you are dealing with a variety of types, eg doubles (1.0).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号