首页 > 解决方案 > 在文本框中发布数据时,输入字符串在 C# 中的格式不正确

问题描述

我收到一条错误消息,提示输入字符串的格式不正确。我还将我的变量转换为 int。这是我的代码。请让我知道我哪里出错了。

private void CashTextBox_TextChanged(object sender, EventArgs e)
{
  try
  {
    int total = dataGridView1.Rows.Cast<DataGridViewRow>()
      .Sum(t => Convert.ToInt32(t.Cells[1].Value));

    int cashtotal = Convert.ToInt32(CashTextBox.Text);

    // TotalTextBox.Text = total + cashtotal;

    int i = total + cashtotal;
    TotalTextBox.Text = i.ToString();
  }
  catch (System.Exception ex)
  {
     System.Windows.Forms.MessageBox.Show(ex.Message);
  }
}

标签: c#

解决方案


您必须在转换数据之前检查 dataType。

 int.TryParse(CashTextBox.Text, out var cashtotal); //C# 7.0

或者

 int cashtotal;
 int.TryParse(CashTextBox.Text, out cashtotal);  //older C# version

也在这里:

.Sum(t => Convert.ToInt32(t.Cells[1].Value));

推荐阅读