2013-06-26 123 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 
}