简体   繁体   English

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

[英]How to bind dataGridView with my own object array?

I have a class:我有一个 class:

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

I want my dataGridView1 show table like:我希望我的 dataGridView1 显示表如下:

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

I try this but failed:我尝试了这个但失败了:

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

Is there a simple way to do it?有没有简单的方法来做到这一点?

Create a class with properties as follows:创建一个具有如下属性的 class:

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

}

Create an enum as follows:创建一个枚举,如下所示:

public enum Direction
{
    Buy,
    Sell
}

Create your data source (I have created a random Data Source with the help of this method for 10 objects):创建您的数据源(我在此方法的帮助下为 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;
    }

Finally, setting the data source in form load event, you can change it as per your needs:最后,在表单加载事件中设置数据源,您可以根据需要更改它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM