0

我收到了这条消息

输入字符串的格式不正确

将值插入数据库时​​。当我检查我有 DDL 但我没有从中选择值时,因此出现了此消息,尽管我在数据库中将此列设置为允许 NULL 值。

protected void BT_submit_Click(object sender, ImageClickEventArgs e)
{
    string File = "~/CvFiles/" + FU_CV.FileName;
    if (FU_CV.FileBytes.Length > 4194304)
    {
        modalpopup.Show();
    }
    else
    {
        app.AddApplicant(txt_Mname.Text, Convert.ToInt32(DDL_Dept.SelectedValue));
    }
}

private void loadDepts()
{
    DDL_Dept.DataSource = d.GetAll();
    DDL_Dept.Items.Clear();
    DDL_Dept.AppendDataBoundItems = true;
    DDL_Dept.Items.Insert(0, new ListItem("-All-", "NULL"));
    DDL_Dept.DataValueField = "id";
    DDL_Dept.DataTextField = "name";
    DDL_Dept.DataBind();
}
 public bool AddApplicant(string MiddleName, int Dept_ID)
{

    SqlCommand cmd = new SqlCommand("SP_Insert_IntoApplicantforuser");
    cmd.CommandType = CommandType.StoredProcedure;

    cmd.Parameters.AddWithValue("@MiddleName", MiddleName);


    cmd.Parameters.AddWithValue("@Dept_ID", Dept_ID);


    System.Data.SqlClient.SqlParameter paramter1 = cmd.Parameters.Add("@AppID", SqlDbType.Int);
    paramter1.Direction = ParameterDirection.Output;

    bool rowaffected;
    rowaffected = DBHelper.Instance().Insert(cmd);
    if (rowaffected == false)
    {
        AppID = (int)paramter1.Value;

    }
    return rowaffected;


}
4

1 回答 1

1

您应该检查 DDL_Dept.SelectedValue 是否是int. 使用int.TryParse方法:

if (FU_CV.FileBytes.Length > 4194304)
{
    modalpopup.Show();
}
else
{
    int dept;
    if  (int.TryParse(DDL_Dept.SelectedValue, out dept))
        app.AddApplicant(txt_Mname.Text, dept);
    else 
        app.AddApplicant(txt_Mname.Text, -1); //or whatever there should be for you
}
于 2012-12-28T08:17:47.173 回答