我需要在导出到excel时将datagridview列更改为整数。 column1具有整数值。
myTable.Rows[i].Cells["column1"].Value.ToString();
string[,] ID = new string[myTable.RowCount, 1];
for (int i = 0; i < myTable.RowCount; i++)
{
ID[i, 0] = myTable.Rows[i].Cells["column1"].Value.ToString();
}
答案 0 :(得分:3)
您可以使用int.TryParse
方法执行从string
到integer
的安全转换:
int value;
string input = myTable.Rows[i].Cells["column1"].Value.ToString();
if(int.TryParse(input, out value))
{
...
}
如果您的值无法解析为整数,则TryParse
将返回false
。
答案 1 :(得分:1)
使用此:
Convert.ToInt32(string s)
Converts the specified string representation of
32-bit signed integer equivalent. This calls in turn Int32.Parse () method.
When s is a null reference, it will return 0 rather than throw ArgumentNullException.
示例:
int num=Convert.ToInt32(myTable.Rows[i].Cells["column1"].Value.ToString());
Int32.Parse(string s)
Converts the string representation of a number to its 32-bit signed integer equivalent.
When s is a null reference, it will throw ArgumentNullException.
示例:
int num=int.Parse(myTable.Rows[i].Cells["column1"].Value.ToString());
Int32.Parse(string,out int)
Converts the specified string representation of 32-bit signed integer equivalent
to out variable, and returns true if it is parsed successfully, false otherwise.
示例:
string str=myTable.Rows[i].Cells["column1"].Value.ToString();
if(Int32.TryParse(str, out result)
{
//code
}
答案 2 :(得分:0)
尝试通过Int32.TryParse
(Details in MSDN)
//method
public static bool TryParse(
string s,
out int result
)
//How to use:
int number;
bool res = Int32.TryParse(myTable.Rows[i].Cells["column1"].Value.ToString(), out number);
//if parse was successfull
if(res)
{
//export to Excel
}
else
{
//throw exception, value was not an int
}