-1

I have a problem when running my code, an error occurs

Input string was not in a correct format.

My code is:

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

I don't know why this happens. Can anyone suggest to me why this might be?

4

3 回答 3

0
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!";
于 2012-05-28T15:50:06.713 回答
0

我会说是这样的:

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
}
于 2012-05-28T08:21:31.413 回答
0

这段代码似乎引发了异常:

Convert.ToInt32(lblID.Text)

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

于 2012-05-28T08:22:12.707 回答