I have a small problem here. When I tried to do the following steps,
string set1="123.10,134.40";
string set2="17,134";
List<string> List1 = new List<string>(set1.Split(','));
List<string> List2 = new List<string>(set2.Split(','));
var QueryResult = from D1 in List1
from E1 in List2
select new
{
D1,
E1
};
DataTable tempDT = new DataTable();
tempDT.Columns.Add("Data1", typeof(int));
开发者_开发知识库tempDT.Columns.Add("Data2", typeof(string));
foreach (var item in QueryResult)
{
tempDT.Rows.Add(new object[] {Convert.ToInt32(item.E1.ToString()),
Convert.ToString(item.D1.ToString()) });
}
When I try to add those values to the tempDT
I am getting an exception:
Input string was not in a correct format.
How do I fix this issue?
It is because you are using Convert.ToInt32 on a string that contains a decimal character.
The code you posted worked just fine, so it means the problem is with your real data.
Most likely, you have something like this:
string set2="17,134,,20";
Meaning empty item which will crash the code.
Remove such empty items with:
List<string> List2 = new List<string>(set2.Split(new char[] {','}, StringSplitOptions.RemoveEmptyEntries));
To be totally safe from that error, use TryParse instead:
int e1;
foreach (var item in QueryResult)
{
if (Int32.TryParse(item.E1, out e1))
{
tempDT.Rows.Add(new object[] { e1, item.D1 });
}
}
This will just ignore any invalid values, not adding them to the data table.
精彩评论