一种得到数据源方法的思考

本文介绍了一种在WinForm中使用ListView控件绑定自定义数据源的方法。通过创建Product类并实现ToString方法,实现了数据的有效展示。此外,还提供了一个示例方法,展示了如何将Product类实例集合填充到ListView中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

           今天看了listview和listbox两个控件的视频教程,其中说了一种绑定数据源的方法,感觉不错,所以贴出来与大家一起分想

         比如先在工程里建一个Product类:(在此类中可以连接数据库)

        此类代码如下 :

       

using System;
using System.Collections.Generic;
using System.Text;

namespace winform1
{
    class Product//创建一个Product类
    {
        public Product(string  code, string name)
        {
            _code = code;
            _name = name;
        }

        public Product(string code, string name, int score)//重载构造函数
        {
            _code = code;
            _name = name;
            _score = score;
        }

        private string  _code;
        public string  Code
        {
            get { return _code; }
            set { _code = value; }
        }

        private string _name;
        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }

        private int _score;
        public int Score
        {
            get { return _score; }
            set { _score = value; }

        }
            
        public override string ToString()//重写tostring()方法,以便按照想要的格式输出
     
            return _code + "-" + _name;
        }

        public static IList
  
   GetAllProduct()
        {
            IList
  
   all = new List
  
  ();
            all.Add(new Product("001", "苹果"));
            all.Add(new Product("002", "橡胶"));
            all.Add(new Product("003", "花生"));
            return all;
        }


        public static IList
  
   GetAllRichProduct()//创建两个静态方法
        {
            IList
  
   all = new List
  
  ();
            all.Add(new Product("001", "苹果",100));
            all.Add(new Product("002", "橡胶",200));
            all.Add(new Product("003", "花生",300));
            return all;
        }

    }
}
然后就可以在其它文件中调用此类了:
    比如以下是一个以Product为数据源来填充listview内容的方法:
  private void button2_Click(object sender, EventArgs e)
   {
     this.listView1.Items.Clear();//首先清除原有所有记录

            IList<Product> all = Product.GetAllRichProduct();//调用方法,返回all

            foreach (Product prod in all)//遍历all中所有记录
            {
                string[] Str = new string[3];//得到此记录相应字段的值
                Str[0] = prod.Code;
                Str[1] = prod.Name;
                Str[2] = prod.Score.ToString();
                ListViewItem item = new ListViewItem(Str, 0);
                this.listView1.Items.Add(item);//填充
            }

        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值