简体   繁体   English

如何将此列值转换为整数?

[英]How can I convert this column value to an integer?

My C# code looks like this: 我的C#代码如下所示:

myNum = dt.Columns[0];

myNum is an integer and dt is a datatable. myNum是一个整数,dt是一个数据表。 The value in column 0 of dt is a string ("12"), but I'd like to convert it to an integer. dt第0列中的值是一个字符串(“12”),但我想将其转换为整数。 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. 你的解析没有工作,因为parse方法接受一个字符串,数据作为一个简单的对象返回。

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. 如果Parse抛出异常,这意味着dt.Columns [0]不是有效输入。 If you want to avoid exception, you can use int.TryParse which returns a boolean telling if the conversion was done or not successfully 如果要避免异常,可以使用int.TryParse返回一个布尔值,告诉转换是否成功完成

EDIT : BTW, Darin must be right: your value is not stored in a column but in a cell 编辑 :BTW,Darin必须是正确的:您的值不会存储在列中但存储在单元格中

Use TryParse method to parse the Value : 使用TryParse方法解析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])

如果你正在处理各种类型,例如双打(1.0),上面会更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM