【问题标题】:Input string was not in a correct format. C# error SQL database输入字符串的格式不正确。 C#错误SQL数据库
【发布时间】:2015-08-28 22:39:54
【问题描述】:

我有一个非常大的问题。 我想在 C# 中从我的数据库 sql 中删除一行。 这是我的代码:

int x = Convert.ToInt32(dataGridView1.SelectedCells[0].Value);
        cmd.Parameters.Clear();
        cmd.CommandText = "delete from Table2 where Name=@N";
        cmd.Parameters.AddWithValue("@N", x);
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();

最后我遇到了问题 输入字符串的格式不正确。 帮我。 我在第一行得到错误。

【问题讨论】:

  • dataGridView1.SelectedCells[0].Value 的值是多少?
  • 您在哪一行出现错误?最有可能的是,dataGridView1.SelectedCells[0] 是空的。因此,在将该空字符串转换为 Int 时,它可能会引发错误。
  • 第一行出现错误。

标签: c# sql database


【解决方案1】:

第一个问题:

dataGridView1.SelectedCells[0].Value 不是有效的整数值,因此Convert.ToInt32 失败。

你是说

string x = dataGridView1.SelectedCells[0].Value;

改为?

第二个问题:

您正在将Name 字段与整数值进行比较。我假设Name is a _string_ value in the database (otherwise it's poorly named). When SQL looks for matching values, it will try to convert every value ofNamein the database to a number. if ANY value in theName` 字段不是有效数字,查询将失败。

【讨论】:

    【解决方案2】:

    我已经读到 null 或空字符串将返回 0(待确认)

    这是我的猜测:

    根据您所在的国家/地区,应填写数字:

    1.234

    1,234

    解决方案

    很好的解决方案:你可以简单地做一个:

    Convert.ToInt32(dataGridView1.SelectedCells[0].Value.Replace(".",","));
    

    好的解决方案:或者使用 Convert.ToInt32(String, IFormatProvider) :

    Convert.ToInt32(dataGridView1.SelectedCells[0].Value,CultureInfo.CurrentCulture)
    

    编辑 -1 不加评论,我很乐意提供帮助。

    【讨论】:

    • 我不能放 Replace 或 CultureInfo,因为 Visual Basic 不给我那个,而是给我另一个东西,比如 GetHash , To Strring。
    • 你用 c# 命名你的问题,然后抱怨,因为我的回答与 Visual Basic 无关???不要指望任何其他帮助
    • 哇。我在 C# 上使用 Visual Basic 编写程序,并在编写值之后。给我一个单词列表,其中 Replace 不正确
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多