简体   繁体   中英

Error: failed to convert string to int32 in debug

I have a test gridview set up with edit template for my user to be able to edit/update/Add several records. Here is what the test looks like:

在此输入图像描述

When I hit update edit, change a value, then click update the values do not update. When I place a breakpoint on the update statement it points to the datatable and reads: failed to convert string to int32

The list are defined as follows:

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;

Here is the datatable:

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
}

The Debug will not specify what int . I have also converted the @num variable value to an int and it still will not update.

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();
}

You will notice there is a place in the update that says QueryPartB that variable sets the datatable back to the select shown in the image after the update.

Edited - Here is the requested stack Trace

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)

It seems your NewID variable type doesn't match with the type in the database.Try to parse it to Integer :

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

Also you should check your other parameter types and make sure they are matching with the SqlDbType's. Corresponding type of NVarChar and NText is string .So your other parameter types ( SiteID , ServiceLineID etc.) should be string .

Try this:

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

I am not sure what HeartAttack is in ServiceLineID = HeartAttack.ToString(); ie. a type or a variable.Looks more like a type to me. If I were you I would bind the HeartAttackId to the value in dropDown list. Eg:

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

And then retreiving it would be like

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

I needed to find the row. So I changed

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

To

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

and now it works!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM