C#计算ListView中的单个列并显示在Label中
C# calculate a single column in ListView and display it in a Label
我有一个可以成功导出和导入的 ListView。我的问题是我需要计算付款列(ListView 中的最后一列)并将结果显示在标签中。但是,我收到 "input string was not in correct format" 错误。
这是我的代码:
private void DisplayWeeklyEarnings()
{
decimal total =0;
foreach (ListViewItem item in lvTimeSheet.Items)
{
total += Convert.ToDecimal(item.SubItems[4].Text);
}
lblEarnings.Text = String.Format("{0:C2}", total);
}
我也试过:
total += Decimal.Parse(item.Subitems[4].Text);
其他人建议使用:
total += Decimal.Parse(item.Subitems(4).Text);
但是,这给了我关于使用子项目作为方法的错误。很明显这是错误的。
这是我的表单:
Click here to see the Form Face
这是填充了薪酬栏的表格:
Click here to see the Populated form
如有任何帮助,我们将不胜感激。提前谢谢你。
您的最后一列包含货币符号。如果您使用 decimal.Parse
的适当重载,则可以解析
total += decimal.Parse(item.SubItems[4].Text, NumberStyles.Currency);
如果您的最后一列包含无法使用 decimal.Parse 重载解析的值(例如空白值),请考虑使用
decimal d;
if(decimal.TryParse(item.SubItems[4].Text, NumberStyles.Currency, CultureInfo.CurrentCulture, out d))
total += d;
如果您不能完全控制输入,TryParse 更安全,因为它不会在输入格式错误的情况下引发异常。
我有一个可以成功导出和导入的 ListView。我的问题是我需要计算付款列(ListView 中的最后一列)并将结果显示在标签中。但是,我收到 "input string was not in correct format" 错误。
这是我的代码:
private void DisplayWeeklyEarnings()
{
decimal total =0;
foreach (ListViewItem item in lvTimeSheet.Items)
{
total += Convert.ToDecimal(item.SubItems[4].Text);
}
lblEarnings.Text = String.Format("{0:C2}", total);
}
我也试过:
total += Decimal.Parse(item.Subitems[4].Text);
其他人建议使用:
total += Decimal.Parse(item.Subitems(4).Text);
但是,这给了我关于使用子项目作为方法的错误。很明显这是错误的。
这是我的表单: Click here to see the Form Face
这是填充了薪酬栏的表格: Click here to see the Populated form
如有任何帮助,我们将不胜感激。提前谢谢你。
您的最后一列包含货币符号。如果您使用 decimal.Parse
的适当重载,则可以解析 total += decimal.Parse(item.SubItems[4].Text, NumberStyles.Currency);
如果您的最后一列包含无法使用 decimal.Parse 重载解析的值(例如空白值),请考虑使用
decimal d;
if(decimal.TryParse(item.SubItems[4].Text, NumberStyles.Currency, CultureInfo.CurrentCulture, out d))
total += d;
如果您不能完全控制输入,TryParse 更安全,因为它不会在输入格式错误的情况下引发异常。