日期:2014-05-18  浏览次数:20856 次

数据库查询结果集怎么不能转换
定义的集合
C# code
public class getinform
    {
        private string _name;
        private string _pic;
        private double _price;
        public string name
        {
            get { return _name; }
            set { _name = value; }
        }
        public string pic
        {
            get { return _pic; }
            set { _pic = value; }
        }
        public double price
        {
            get { return _price; }
            set { _price = value; }
        }
    }

数据库查询代码
C# code
public class selc
    {
    private string _name;
    private string _pic;
    private double _price;
    public string name
    {
        get { return _name; }
        set { _name = value; }
    }
    public string pic
    {
        get { return _pic; }
        set { _pic = value; }
    }
    public double price
    {
        get { return _price; }
        set { _price = value; }
    }
    }
public  List<selc> select(string ID)
    {
        List<selc> results = new List<selc>();
        SqlConnection con = new SqlConnection(_comstring);
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = con;
        cmd.CommandText = "select 产品名称,单价,小图片 from goods where 产品ID=@ID ";
        cmd.Parameters.AddWithValue("ID", ID);
        using (con)
        {
            con.Open();
            SqlDataReader reader = cmd.ExecuteReader();
            while (reader.Read())
            {
                selc get = new selc();
                get.name = (string)reader["产品名称"];
                get.pic = Convert.ToString(reader["小图片"]);
                get.price = (double)reader["单价"];
                results.Add(get);
            }
            reader.Close();
        }
        return results;
    }

但是我在前面不能赋值呢
string ID = row1["产品ID"].ToString();
object1 sel = new object1();
getinform getinform =(getinform)sel.select(ID);

------解决方案--------------------
C# code

--你结果中都没把它选出来
cmd.CommandText = "select 产品ID,产品名称,单价,小图片 from goods where 产品ID=@ID ";

------解决方案--------------------
sel.select方法返回的是List<selc>,你直接强制转成getinform? 哪位老师教的?
------解决方案--------------------
selc可以继承自getinform,前面重复的就可以不要了
object1是什么东西?应该是selc吧?
selc sel = new selc();
List<selc> getinform =sel.select(ID);
另外还有
cmd.Parameters.AddWithValue("@ID", ID);
------解决方案--------------------
C# code

List<selc> selcList  =sel.select(ID);
List<getinform > getList=new  List<getinform >();
foreach(selc item in selcList )
{
getinform get=new  getinform ();
get._name=item._name;
get._pic=item._pic;
get._price=item._price;
getList.add(get);
}