2013-06-26 121 views
0

我在C#中調用存儲過程並使用值填充DataTable。我有一個問題,我的存儲過程的返回值是一個字符串,而我用來保存在我的C#中的值的屬性來自類是一個枚舉的類。我試着投,但我不斷收到此錯誤:Cast string to enum

Specified cast is not valid.

這是我的方法調用存儲過程:

this.OrderType = (eOrderType)ds.Tables[0].Rows[0]["OrderType"]; 

這就是:在這條線出現

public void GetOrder() 
{ 
    ConnectionStringSettings connectionString = ConfigurationManager.ConnectionStrings["T_DB"]; 
    string conString = connectionString.ConnectionString; 

    DataSet ds = new DataSet(); 

    using (SqlConnection con = new SqlConnection(conString)) 
    { 
     SqlCommand cmd = new SqlCommand("LH_Get_order", con); 
     cmd.Parameters.AddWithValue("@onum", 45642); 
     cmd.CommandType = CommandType.StoredProcedure; 

     SqlDataAdapter ad = new SqlDataAdapter(cmd); 
     ad.Fill(ds); 

     if (ds.Tables[0].Rows.Count > 0) 
     { 
      this.BatchId = ds.Tables[0].Rows[0]["gbo_batch_id"].ToString(); 
      this.ExternalRefId = ds.Tables[0].Rows[0]["o_num"].ToString(); 
      this.LoanId = ds.Tables[0].Rows[0]["o_loan"].ToString(); 
      this.OrderType = (eOrderType)ds.Tables[0].Rows[0]["OrderType"]; //problem 
     } 
    } 
} 

問題我的OrderType財產:

public eOrderType OrderType 
{ 
    get { return _OrderType; } 
    set { _OrderType = value; } 
} 

這是eOrderType枚舉:

public enum eOrderType : int { 

    [System.Runtime.Serialization.EnumMemberAttribute(Value="CVA BPO")] 
    CVABPO = 1, 

    [System.Runtime.Serialization.EnumMemberAttribute()] 
    ExteriorBPO = 2, 

    [System.Runtime.Serialization.EnumMemberAttribute()] 
    Inspection = 3, 

    [System.Runtime.Serialization.EnumMemberAttribute()] 
    RepairEstimate = 4, 
} 
+7

, 對?你可能只想要Enum.Parse ... –

回答

0
(eOrderType) Enum.Parse(typeof(eOrderType),ds.Tables[0].Rows[0]["OrderType"]); 
+0

非常感謝。 – Alma

0

您需要將字符串解析到一個枚舉值,而不是鑄造:那麼想必將數據存儲在數據庫中的字符串

eOrderType orderType; 
if(Enum.TryParse(ds.Tables[0].Rows[0]["OrderType"], out orderType)) 
{ 
    this.OrderType = orderType; 
} 
else 
{ 
    //parse failed 
}