OleDbCommand - 输入字符串格式不正确

本文关键字:格式 不正确 字符串 输入 OleDbCommand | 更新日期: 2023-09-27 18:35:27

我在运行代码时遇到问题,发生错误

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

我的代码是:

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!";

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

OleDbCommand - 输入字符串格式不正确

我会说是这样的:

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
}

看起来这段代码引发了异常:

Convert.ToInt32(lblID.Text)

运行调试器并观察lblID.Text中的值 - 如果它真的可以转换为 int .名称表明这是Label,所以也许你犯了一个错误,它应该是(根据以前的数据)类似于text_ID?

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!";