首页 > 解决方案 > 我不断收到名为 System.FormatException 的错误

问题描述

我正在开发一个系统,它具有带有选择选项的 GridView,以通过其主键 ID 选择存储在特定行中的数据。

此代码在另一个页面上工作得很好,可以执行完全相同的功能

    protected void lnk_OnClick(object sender, EventArgs e)
    {
        int objectiveID = Convert.ToInt32((sender as LinkButton).CommandArgument);
        if (con.State == ConnectionState.Closed)
            con.Open();
        SqlDataAdapter sqlDa = new SqlDataAdapter("objectiveViewByID", con);
        sqlDa.SelectCommand.CommandType = CommandType.StoredProcedure;
        sqlDa.SelectCommand.Parameters.AddWithValue("@objectiveID", objectiveID);
        DataTable dtbl = new DataTable();
        sqlDa.Fill(dtbl);
        con.Close();
        hfobjectiveID.Value = objectiveID.ToString();
        txtAudience.Text = dtbl.Rows[0]["audience"].ToString();
        txtCondition.Text = dtbl.Rows[0]["condition"].ToString();
        txtBloom.Text = dtbl.Rows[0]["bloom_level"].ToString();
        txtVerb.Text = dtbl.Rows[0]["verb"].ToString();
        txtProduct.Text = dtbl.Rows[0]["product"].ToString();
        btnSave.Text = "Update";
        btnDelete.Enabled = true;
    }

我希望代码能够重新填充用于填充数据库的输入字段。

标签: c#asp.net

解决方案


理论上,格式异常,如果 ToInt32 方法输入是一些非数字值,它可能会在此处出错。

int objectiveID = Convert.ToInt32((sender as LinkButton).CommandArgument);

如果值(例如 dtbl.Rows[0]["audience"] 为空),则其他潜在区域为以下代码。但这将是一个不同的例外。您可以在顶部放置一个断点,然后查看哪条线崩溃。

hfobjectiveID.Value = objectiveID.ToString();
txtAudience.Text = dtbl.Rows[0]["audience"].ToString();
txtCondition.Text = dtbl.Rows[0]["condition"].ToString();
txtBloom.Text = dtbl.Rows[0]["bloom_level"].ToString();
txtVerb.Text = dtbl.Rows[0]["verb"].ToString();
txtProduct.Text = dtbl.Rows[0]["product"].ToString();

推荐阅读