【问题标题】:OleDbCommand - Input string was not in a correct formatOleDbCommand - 输入字符串的格式不正确
【发布时间】:2012-05-28 08:07:22
【问题描述】:

运行我的代码时遇到问题,出现错误

输入字符串的格式不正确。

我的代码是:

protected void imgbtn_Save_Click(object sender, EventArgs e)
{

        OleDbCommand cmd = new OleDbCommand();
        cmd.CommandText = "update Companies set CompanyFName='" + txt_ComName.Text + "',CompanySName='" + txt_ShortName.Text + "',CompanyeMail='" + txt_email.Text + "',CompanyWebsite='" + txt_website.Text + "'where CompanyId='"+Convert.ToInt32(lblID.Text)+"'";
       // cmd.Parameters.AddWithValue("@CompanyId", Convert.ToInt32(lblID.Text));
        cmd.Connection = conn;
        OleDbDataAdapter da = new OleDbDataAdapter();
        da.UpdateCommand = cmd;

        cmd.ExecuteNonQuery();
        conn.Close();
        BindGridData();
        lblError.Font.Bold = true;
        lblError.Font.Size = 11;
        lblError.Text = "You have successfully modified the case!";

我不知道为什么会这样。谁能告诉我为什么会这样?

【问题讨论】:

  • 您是否在调试器中单步执行了这段代码,以找出究竟是哪一行引发了错误?
  • 查询行上的实际错误。当我在调试并且在 lblid=lable 时通过 ho raha hai。
  • 在这个update Companies set CompanyFName=' 中,您在开头缺少一个单引号,即'update Companies set CompanyFName='

标签: c# c#-4.0 ms-access-2007


【解决方案1】:

我会说是这样的:

Convert.ToInt32(lblID.Text)

失败了。

如果lblID.Text 实际上不是整数,则转换将失败。

使用TryParse 预先转换为整数会好得多,这样您就可以从无效输入中恢复:

int localId = 0;
if (Int32.TryParse(lblID.Text, out localId)
{
    // Carry on
}
else
{
    // Deal with error - this could be just accepting null input as 0
}

【讨论】:

    【解决方案2】:

    此代码似乎引发了异常:

    Convert.ToInt32(lblID.Text)
    

    运行调试器并观察lblID.Text 中的值——如果它真的可以转换为int。名字暗示这是Label,所以也许你做错了,它应该(根据以前的数据)类似于text_ID?

    【讨论】:

      【解决方案3】:
      protected void imgbtn_Save_Click(object sender, EventArgs e)
      {
      
              OleDbCommand cmd = new OleDbCommand();
              cmd.CommandText = "update Companies set CompanyFName='" + txt_ComName.Text + "',CompanySName='" + txt_ShortName.Text + "',CompanyeMail='" + txt_email.Text + "',CompanyWebsite='" + txt_website.Text + "'where CompanyId='"+lblID.Text+"'";
             // cmd.Parameters.AddWithValue("@CompanyId", Convert.ToInt32(lblID.Text));
              cmd.Connection = conn;
              OleDbDataAdapter da = new OleDbDataAdapter();
              da.UpdateCommand = cmd;
      
              cmd.ExecuteNonQuery();
              conn.Close();
              BindGridData();
              lblError.Font.Bold = true;
              lblError.Font.Size = 11;
              lblError.Text = "You have successfully modified the case!";
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-01-23
        • 2013-08-22
        相关资源
        最近更新 更多