如何将 dataGridView 与我自己的对象数组绑定?

How to bind dataGridView with my own object array?

我有一个 class:

  public class MarketTrade
  {
        public int trade_seq;
        public double amount;
        public double price;
        public direction dir; //=enum
  }

我希望我的 dataGridView1 显示 table 如:

trade_seq   amount  price   dir
00001       10      100     buy
00002       5       99      buy
00003       5       100     buy
00004       15      98      sell
00005       20      100     sell

我试过了但是失败了:

  MarketTrade[] trades =  GetTrades();
  this.dataGridView1.DataSource = trades;

有简单的方法吗?

创建一个 class 属性如下:

public class MarketTrade
{
    public int TradeSeq { get; set; }
    public double Amount { get; set; }
    public double Price { get; set; }
    public Direction Dir { get; set; }

}

创建一个枚举如下:

public enum Direction
{
    Buy,
    Sell
}

创建您的数据源(我借助此方法为 10 个对象创建了一个随机数据源):

private MarketTrade[] GetTrades()
    {
        MarketTrade[] arrMarketTrades = new MarketTrade[10];

        for (int i = 0; i < 10; i++)
        {
            arrMarketTrades[i] = new MarketTrade()
            {
                Amount = (i + 1) * 4,
                Dir = i / 2 == 0 ? Direction.Buy : Direction.Sell,
                Price = (i + 1) * 2,
                TradeSeq = i
            };
        }

        return arrMarketTrades;
    }

最后,在表单加载事件中设置数据源,您可以根据需要进行更改:

    private void Form1_Load(object sender, System.EventArgs e)
    {
        dataGridView1.DataSource = this.GetTrades();
    }