c# - 在文本框中发布数据时,输入字符串在 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);
}
}
解决方案
您必须在转换数据之前检查 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));
推荐阅读
- javascript - 在 javscript 中动态删除行
- javascript - JSON 到 Typescript 模型唯一键
- iframe - 关于 iframe 和 cookie 的问题我如何将 samesite none 部分添加到我的 cookie 中?
- ios - 创建可扩展的表格视图?
- javascript - MutationObserver 回调未在 Firefox 中调用,但在 Chrome 中调用
- python - [python]:将字典项的 pandas 列转换为 DataFrame 中的单个行
- android - Jetpack Compose LazyVerticalGrid 重组
- kubernetes - 带有 azure/k8s-bake@v1 的 github action 自托管运行器
- python - 如何通过 python 访问托管在网络上的文件?
- mongodb - $group 和 $map 在 mongodb 中无法正常工作