如何使用C#方法从OleDbDataReader获取结果

时间:2015-02-19 06:31:38

标签: c# methods expandoobject oledbdatareader

如何从方法中返回????

这对我很重要

这是我的方法:

public static dynamic GetFactorProperties(int factornumber)
        {
            using (var db = new OleDbConnection(cs))
            {
                db.Open();
                var cmd = new OleDbCommand("SELECT * FROM FactorList WHERE FactorNumber = @0", db);
                cmd.Parameters.AddWithValue("@0", factornumber);
                var result = cmd.ExecuteReader();
                if(result.Read())
                {
                    return result ;
                }
                else
                {
                    return ProperiesObject();
                }
            }
        }

这是我的ExpandoObject()

         public static dynamic ProperiesObject()
         {
             dynamic obj = new ExpandoObject();
            obj.FactorDate = string.Empty;
             obj.FactorNumber = string.Empty;
             obj.CustomerName = string.Empty;
             obj.FactorPrice = string.Empty;
             obj.Discount = string.Empty;
             return obj;
         }

,这是从方法来源读取的:

        var result = Program.GetFactorProperties(factornumber);
        TXTDate.Text = result.FactorDate;
        TXTFactorNumber.Text = result.FactorNumber;
        TXTCustomerName.Text = result.CustomerName;
        TXTFactorParice.Text = result.FactorPrice;
        TXTDiscount.Text = result.Discount;

1 个答案:

答案 0 :(得分:1)

方法应如下所示:

public static dynamic GetFactorProperties(int factornumber)
{
    using (var db = new OleDbConnection(cs))
    {
         db.Open();
         var cmd = new OleDbCommand("SELECT * FROM FactorList WHERE FactorNumber = @0", db);
         cmd.Parameters.AddWithValue("@0", factornumber);
         var result = cmd.ExecuteReader();
         if(result.Read())
         {
              dynamic obj = new ExpandoObject();
              obj.FactorDate = result.GetString(0);
              obj.FactorNumber = result.GetString(1);
              // ...
              return obj;
         }
         else
         {
              return ProperiesObject();
         }
    }
}

GetString接受要从中获取值的列数