2012-12-28 56 views
0

選擇數據我有這個消息錯誤時,不會從DDL

值插入數據庫時​​

輸入字符串的不正確的格式

。當我檢查我有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; 


} 

回答

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 
} 
+0

AddApplicant必須有根據DDL值,所以當我用NULL時出現的錯誤 – Egydeveloper

+0

不能轉換INT爲NULL – Egydeveloper

+0

@Egydeveloper你的意思是「int轉換成NULL」做int變量?你可以顯示你的方法AddApplicant? – JleruOHeP