简体   繁体   中英

Insert gives “Failed to convert parameter value from a String to a Byte” error

I'm trying to make leave management system. When I try to insert data in leave_request table I get an error:

Failed to convert parameter value from a String to a Byte

My code:

protected void Button1_Click(object sender, EventArgs e)
{
    // Guid obj = new Guid();
    con.Open();

    SqlCommand cmd = new SqlCommand("request", con);
    cmd.CommandType = CommandType.StoredProcedure;

    cmd.Parameters.Add("@empID", SqlDbType.UniqueIdentifier);
    cmd.Parameters["@empID"].Value = new Guid();

    cmd.Parameters.Add("@leave_type", SqlDbType.TinyInt );
    cmd.Parameters["@leave_type"].Value = DropDownList1.SelectedValue.ToString();

    cmd.Parameters.Add("@DayPart", SqlDbType.TinyInt);
    cmd.Parameters["@DayPart"].Value = RadioButton1.ToString();

    cmd.Parameters.Add("@Category", SqlDbType.VarChar);
    cmd.Parameters["@Category"].Value = categorylist.SelectedValue.ToString();

    cmd.Parameters.Add("@CategoryID", SqlDbType.Int);
    cmd.Parameters["@CategoryID"].Value = DropDownList3.SelectedValue.ToString();

    cmd.Parameters.Add("@Reason", SqlDbType.VarChar);
    cmd.Parameters["@Reason"].Value = txtreason.Text.ToString();

    cmd.Parameters.Add("@fromdate", SqlDbType.Date);
    cmd.Parameters["@fromdate"].Value = Calendar1.SelectedDate.ToShortDateString();

    cmd.Parameters.Add("@todate", SqlDbType.Date);
    cmd.Parameters["@todate"].Value = Calendar2.SelectedDate.ToShortDateString();

    cmd.ExecuteNonQuery();

    con.Close();
}

Table structure:

empID uniqueidentifier,
leave_type int,
DayPart int,
CategoryID int,
Category varchar(50),
Reason varchar(500),
fromdate date,
todate date

Please check in your database following things

  1. In table leave_request, check for all parameters that you are passing and see its datatype in database, using alt+f1. The parameters leave_type and daypart, one or both of them are string in your database however you are passing them as tinyint hence the problem.

Although you are converting them as string while passing, however when the driver is trying it to map for database it is expecting them to be byte not string.

  1. In stored procedure "request", check that your parameter datatypes should match with the passing parameter datatypes,

Always use Microsoft recommended conversion when mapping .NET framework to SQL Server datatypes as suggested in below link.

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