Reputation: 405
I need to change datagridview column into integer while exporting to excel. column1 has an integer values.
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();
}
Upvotes: 2
Views: 9338
Reputation: 18747
Use this:
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.
Example:
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.
Example:
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.
Example:
string str=myTable.Rows[i].Cells["column1"].Value.ToString();
if(Int32.TryParse(str, out result)
{
//code
}
Upvotes: 1
Reputation: 23937
Try to convert it via 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
}
Upvotes: 0
Reputation: 101681
You can use int.TryParse
method in order to perform a safe conversion from string
to integer
:
int value;
string input = myTable.Rows[i].Cells["column1"].Value.ToString();
if(int.TryParse(input, out value))
{
...
}
If your value is not parsable to integer then TryParse
will return false
.
Upvotes: 3