错误:在调试中无法将字符串转换为int32

时间:2014-02-14 16:10:52

标签: c# asp.net sql

我有一个带有编辑模板的测试gridview,我的用户可以编辑/更新/添加几条记录。这是测试的样子:

enter image description here

当我点击更新编辑时,更改一个值,然后点击更新值不更新。当我在update语句上放置一个断点时,它指向数据表并读取: failed to convert string to int32

列表定义如下:

private int InpatientMeasures = 1;
private int OutpatientMeasures = 2;

private int HeartAttack = 1;
private int HeartFailure = 2;
private int Pneumonia = 3;
private int SIPrevention = 4;
private int Surgery = 5;

这是数据表:

private DataTable GetData(SqlCommand cmd)
{
    DataTable dt = new DataTable();
    SqlConnection con = new SqlConnection(conn);
    SqlDataAdapter sda = new SqlDataAdapter();
    cmd.CommandType = CommandType.Text;
    cmd.Connection = con;
    con.Open();
    sda.SelectCommand = cmd;
    sda.Fill(dt); //This is where it breaks and gives the error in debug mode
    return dt; //The Code will actually work until the line above but will not reach here
}

Debug不会指定int。我还将@num变量值转换为int,但仍然不会更新。

protected void UpdateQualityMeasures(object sender, GridViewUpdateEventArgs e)
{
    string Mynum = ((Label)gvMainView.FooterRow.FindControl("lblNum")).Text;
    string SiteID = ((DropDownList)gvMainView.FooterRow.FindControl("ddlSite")).Text;
    switch (SiteID)
    {
        case "Inpatient Measures":
            SiteID = InpatientMeasures.ToString();
            break;
        case "Outpatient Measures":
            SiteID = OutpatientMeasures.ToString();
            break;
    }

    string ServiceLineID = ((DropDownList)gvMainView.FooterRow.FindControl("ddlServiceLine")).Text;
    switch (ServiceLineID)
    {
        case "Heart Attack":
            ServiceLineID = HeartAttack.ToString();
            break;
        case "Heart Failure":
            ServiceLineID = HeartFailure.ToString();
            break;
        case "Pneumonia":
            ServiceLineID = Pneumonia.ToString();
            break;
        case "Surgical Infection Prevention":
            ServiceLineID = SIPrevention.ToString();
            break;
        case "Surgery":
            ServiceLineID = Surgery.ToString();
            break;
    }


    string Measure = ((TextBox)gvMainView.FooterRow.FindControl("txtMeasure")).Text;
    string MyCompAvg = ((TextBox)gvMainView.FooterRow.FindControl("txtMyCompAvg")).Text;
    string NationalAvg = ((TextBox)gvMainView.FooterRow.FindControl("txtNationalAvg")).Text;
    string KYStateAvg = ((TextBox)gvMainView.FooterRow.FindControl("txtKYStateAvg")).Text;

    SqlConnection con = new SqlConnection(conn);
    SqlCommand cmd = new SqlCommand();
    cmd.CommandType = CommandType.Text;
    string QueryPartB = Measures;
    int NewID = Convert.ToInt32(Mynum);

    cmd.CommandText = "update quality_Measures set SiteID=@SiteID, ServiceLineID=@ServiceLineID, Measure=@Measure, MyCompAvg=@MyCompAvg, KYStateAvg=@KYStateAvg, NationalAvg=@NationalAvg where " +
    "num=@num;" + QueryPartB;
    cmd.Parameters.Add("@num", SqlDbType.Int).Value = NewID;
    cmd.Parameters.Add("@SiteID", SqlDbType.NVarChar).Value = SiteID;
    cmd.Parameters.Add("@ServiceLineID", SqlDbType.NVarChar).Value = ServiceLineID;
    cmd.Parameters.Add("@Measure", SqlDbType.NText).Value = Measure;
    cmd.Parameters.Add("@MyCompAvg", SqlDbType.NVarChar).Value = MyCompAvg;
    cmd.Parameters.Add("@KYStateAvg", SqlDbType.NVarChar).Value = KYStateAvg;
    cmd.Parameters.Add("@NationalAvg", SqlDbType.NVarChar).Value = NationalAvg;
    gvMainView.EditIndex = -1;
    gvMainView.DataSource = GetData(cmd);
    gvMainView.DataBind();
}

您会注意到更新中有一个地方显示QueryPartB该变量将数据表设置回更新后图像中显示的选择。

已编辑 - 此处为请求的堆栈跟踪

at System.Data.SqlClient.SqlParameter.CoerceValue(Object value, MetaType destinationType, Boolean& coercedToDataFeed, Boolean& typeChanged, Boolean allowStreaming)
at System.Data.SqlClient.SqlParameter.GetCoercedValue()
at System.Data.SqlClient.SqlParameter.Validate(Int32 index, Boolean isCommandProc)
at System.Data.SqlClient.SqlCommand.BuildParamList(TdsParser parser, SqlParameterCollection parameters)
at System.Data.SqlClient.SqlCommand.BuildExecuteSql(CommandBehavior behavior, String commandText, SqlParameterCollection parameters, _SqlRPC& rpc)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
at System.Data.Common.DbCommand.System.Data.IDbCommand.ExecuteReader(CommandBehavior behavior)
at System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior)
at System.Data.Common.DbDataAdapter.Fill(DataTable[] dataTables, Int32 startRecord, Int32 maxRecords, IDbCommand command, CommandBehavior behavior)
at System.Data.Common.DbDataAdapter.Fill(DataTable dataTable)
at QualityOutcomeGraphGen_test.Admin.GetData(SqlCommand cmd) in c:\Users\20002143\Documents\Visual Studio 2012\Projects\QualityOutcomeGraphGen_test\QualityOutcomeGraphGen_test\Admin.aspx.cs:line 57
at QualityOutcomeGraphGen_test.Admin.UpdateQualityMeasures(Object sender, GridViewUpdateEventArgs e) in c:\Users\20002143\Documents\Visual Studio 2012\Projects\QualityOutcomeGraphGen_test\QualityOutcomeGraphGen_test\Admin.aspx.cs:line 241
at System.Web.UI.WebControls.GridView.OnRowUpdating(GridViewUpdateEventArgs e)
at System.Web.UI.WebControls.GridView.HandleUpdate(GridViewRow row, Int32 rowIndex, Boolean causesValidation)
at System.Web.UI.WebControls.GridView.HandleEvent(EventArgs e, Boolean causesValidation, String validationGroup)
at System.Web.UI.WebControls.GridView.OnBubbleEvent(Object source, EventArgs e)
at System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args)
at System.Web.UI.WebControls.GridViewRow.OnBubbleEvent(Object source, EventArgs e)
at System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args)
at System.Web.UI.WebControls.LinkButton.OnCommand(CommandEventArgs e)
at System.Web.UI.WebControls.LinkButton.RaisePostBackEvent(String eventArgument)
at System.Web.UI.WebControls.LinkButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

3 个答案:

答案 0 :(得分:1)

您的NewID变量类型似乎与数据库中的类型不匹配。请尝试将其解析为Integer

cmd.Parameters.Add("@num", SqlDbType.Int).Value = int.Parse(NewID);

此外,您应该检查其他参数类型,并确保它们与SqlDbType's.对应类型NVarCharNText string匹配。所以您的其他参数类型(SiteIDServiceLineID等)应为string

答案 1 :(得分:1)

试试这个:

cmd.Parameters.Add(new SqlParameter() { DbType = DbType.Int32, ParameterName = "@num", Value = Convert.ToInt32(NewID) });

我不确定HeartAttack在 ServiceLineID = HeartAttack.ToString(); 即是什么。一个类型或一个变量。对我来说更像一个类型。如果我是你,我会将HeartAttackId绑定到dropDown列表中的值。例如:

new ListItem() { Text = "Heart Attack", Value = "1" }; // here 1 is HeartAttackId

然后转发它就像

string ServiceLineID = ((DropDownList)gvMainView.FooterRow.FindControl("ddlServiceLine")).Value;

答案 2 :(得分:0)

我需要找到这一行。所以我改变了

string Mynum = ((Label)gvMainView.FooterRow.FindControl("lblNum")).Text;

string Mynum = ((Label)gvMainView.Rows[e.RowIndex].FindControl("lblNum")).Text;

现在它有效!