将列表绑定到DataGridView C#WinForm [英] Binding List to DataGridView C# WinForm

查看:61
本文介绍了将列表绑定到DataGridView C#WinForm的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我似乎无法弄清楚我在这里做错了什么.
当我运行代码时,我的列表未显示在我的DataGridView中.

有人可以帮我吗?

提前谢谢.

Hi,

I can''t seem to figure out exactly what I''m doing wrong here.
When I run the code my List isn''t being displayed in my DataGridView.

Can some one please help me out here?

Thanks in advance.

class Stock : INotifyPropertyChanged
{
  string sym;
  float  prc;
  int    sz;

  public event PropertyChangedEventHandler PropertyChanged;
  
  public Stock(string sym, float prc, int sz)
  {
    this.sym = sym;
    this.prc = prc;
    this.sz  = sz;
  }

  public string Symbol
  {
     get{return sym;}
  }
  
  public float Price
  {
    get{return prc;}
    set
    {
       if (prc != value)
       {
         price = value;
         OnPropertyChanged("Price");
    }
  }
  
  public int Size
  {
    get{return sz;}
    set 
    {
       if (sz != value)
       {
          sz = value;
          OnPropertyChanged("Size");
       }
    }
  }

  private void OnPropertyChanged(string propertyName)
  {
     if (PropertyChanged != null)
     {
         PropertyChanged(propertyName);
     }
  }
}

class StocksManager
{
   // Stock Market Data API Feed
   MktDataAPI  mktData;
   Thread t;
   Queue<Stock> q;
   EventWaitHandle ewh;
   object sync;
   Dictionary<string, Stock> stocksCollec;
   List<Stock> tempStocksCollec;

  public StocksManager
  {
     mktData = new MktDataAPI();
     mktData.UpdateMktData += new UpdateMktDataEventHndlr(mktData_UpdateMktData);
     q = new Queue<Stock>();
     sync = new object();
     stocksCollec = new Dictionary<string, Stock>();
     tempStocksCollec = new Dictionary<string, Stock>();
     t = new Thread(worker);

     t.IsBackGround = true;
     t.Start();
  }

  public List<Stock> StocksCollection
  {
     get{return tempStocksCollec;}
  }
  
  private void mktData_UpdateMktData(string sym, float prc, int sz)
  {
     lock(sync)
     {
        q.Enqueue(new Stock(sym, prc, sz));
     }
  }

  private void worker()
  {
     while(true)
     {
        Stock s = null;
        
        lock(sync)
        {
           if (q.Count > 0)
           { 
               s = q.Dequeue();
           }
        }
 
        if (s != null)
        {
           string sym = s.Symbol;
           float  prc = s.Price;
           int    sz  = s.Size;
   
           if(!stocksCollec.ContainsKey(sym))
           {
              stocksCollec.Add(new Stock(sym,prc,sz));
           }
           else
           {
              stocksCollec[sym].Price = prc;
              stocksCollec[sym].Size  = sz;
           }
   
           tempStocksCollec.AddRange(stocksCollec.Values);
        }
        else
        {
           signal.WaitOne();
        }
     }
  }
     
}

// GUI
StocksManager stkMngr;
public Form1()
{
   InitializeComponent();
   
   stkMngr = new StockManager();
   
   dataGridView1.DataSource = stkMngr.StocksCollection;
}

推荐答案

我真的不确定从何处获得零碎的资料,但我认为您应该将其放回原处.那甚至都不会编译.

I''m really not sure where you got that collection of bits and pieces from, but I think you should put it back there. That won''t even compile.

List<Stock> tempStocksCollec;
...
    tempStocksCollec = new Dictionary<string, Stock>();
...
  public List<Stock> StocksCollection
  {
     get{return tempStocksCollec;}
  }
...
   stkMngr = new StockManager();
   dataGridView1.DataSource = stkMngr.StocksCollection;

您不能将字典分配给列表-它们是完全不同的类型!
而且我从未尝试过将Dictionary用作数据源-我不确定会发生什么,但是我认为它的工作效果不如您认为的好.

You can''t assign a Dictionary to a List - they are completely different types!
And I have never tried to use a Dictionary as a DataSource - I''m not sure what would happen, but I don''t think it would work quite as well as your seem to think...


您的代码看起来有很多缺陷,或者您没有正确放置此处.我拿走了您的第二个代码,该代码在注释中进行了格式化,因为在Visual Studio中复制时丢失了格式化.

我注意到以下几点

1. stocksCollec = new Dictionary< string,>();缺少另一个类型参数.
替换为
stocksCollec =新字典< string,stock>();

2.不应该mktData.StockUpdateHandler + = new StockUpdateEventHandler(mktData_StockUpdateHandler);
反过来.
我的意思是StockUpdateHandler应该是代表名称,而StockUpdateEventHandler应该是事件名称.

但这只是命名约定问题.

3.队列workQueue和列表tempStocksCollec缺少类型参数
已更新为队列<股票>" workQueue;
清单<库存> tempStocksCollec;

4. stocksCollec是Dictionary,而tempStocksCollec是List.您不能将stackCollecs添加到tempStocksCollecs
除非您仅从字典中获取键或值.就像我做的一样

tempStocksCollec.AddRange(stocksCollec.Values.ToList());

5.您正在StocksManager的构造函数中初始化MktDataSim对象,并侦听激发的事件.谁在开枪
事件.我不知道您的要求,但看来您应该在Stock Manager构造函数中将MktDataSim作为参数
如果我对此有误,可以纠正我.

无论如何,我修改了代码,现在我可以看到
网格中的符号",价格"和大小"列.

这是修改后的代码.希望它能帮助您一点或至少将您指向正确的方向

Your code look very much flawed or you have not put here correctly. I took your second code which was there in comment did formatting as it lost formatting when i copied in visual Studio.

I noticed following points

1. stocksCollec = new Dictionary<string,>(); another type parameter missing.
Replaced with
stocksCollec = new Dictionary<string,stock>();

2. Shouldn''t mktData.StockUpdateHandler += new StockUpdateEventHandler (mktData_StockUpdateHandler);
be the other way round.
I mean StockUpdateHandler should be Delegate name and StockUpdateEventHandler should be Event name.

but then its just naming convention issue.

3. Queue workQueue and List tempStocksCollec has type parameter missing
Updated to Queue<Stock> workQueue;
List<Stock> tempStocksCollec;

4. stocksCollec is Dictionary and tempStocksCollec is List. you can''t add stackCollecs to tempStocksCollecs
unless you take only key or value from the dictionary. like what i did

tempStocksCollec.AddRange(stocksCollec.Values.ToList());

5. You are initializing MktDataSim object in the constructor of StocksManager and listening to event fired. Who is then firing
the event. I don''t know about your requirement but looks like you should have MktDataSim as parameter in the Stock Manager constructor
Someone can correct me if i m wrong on this.

Anyway i modified code and now I can see
Symbol,Price and Size columns in the grid.

This is the code after modification.Hope it will help you bit or atleast will point you in right direction

public partial class Form1 : Form
{
   public Form1()
   {
      InitializeComponent();
      var stkMngr = new StocksManager();
      dataGridView1.DataSource = stkMngr.StockCollection;;
   }
}
     
public class StocksManager 
{ 
   int NUM_PROCESSORS = Environment.ProcessorCount;
   MktDataSim mktData; 
   List<thread> workers;
   EventWaitHandle signal; 
   Queue<stock> workQueue;
   object sync;
   Dictionary<string,stock> stocksCollec; 
   List<stock> tempStocksCollec; 
      
   public StocksManager()
   { 
      mktData = new MktDataSim();
      workers = new List<thread>(); 
      signal = new AutoResetEvent(false); 
      workQueue = new Queue<stock>(); 
      sync = new object(); 
      stocksCollec = new Dictionary<string,stock>();
      tempStocksCollec = new List<stock>();
      mktData.StockUpdateHandler += new StockUpdateEventHandler (mktData_StockUpdateHandler); 
      
      for (int i = 0; i < NUM_PROCESSORS; i++)
      { 
         workers.Add(new Thread(worker)); 
         workers[i].IsBackground = true; 
         workers[i].Start(); 
      }
   }
   
   public List<stock> StockCollection 
   {
      get { return tempStocksCollec; }
   }
   
   private void mktData_StockUpdateHandler(string symbol, double price, int size)
   { 
      getMktData(new Stock(symbol, price, size));
   } 
   
   private void getMktData(Stock stock)
   {
      lock (sync) workQueue.Enqueue(stock); 
      signal.Set(); 
   } 
   private void worker() 
   {
      while (true)
      {
         Stock stock = null; 
         lock (sync) 
         {
            if (workQueue.Count > 0)
               stock = workQueue.Dequeue(); 
                        } 
            if (stock != null)
            { 
               string sym = stock.Symbol;
               double prc = stock.Price;
               int sz = stock.Size; 
               tempStocksCollec.Clear(); 
               
               if (!stocksCollec.ContainsKey(sym)) 
                  stocksCollec.Add(sym, new Stock(sym, prc, sz));
               else
                  stocksCollec[sym].Price = prc; stocksCollec[sym].Size = sz; 

               tempStocksCollec.AddRange(stocksCollec.Values.ToList());
            }
         }
      }
   }

   public delegate void StockUpdateEventHandler(string symbol, double price, int size);
   public class MktDataSim
   {
      public event StockUpdateEventHandler StockUpdateHandler;
   }

   public class Stock : INotifyPropertyChanged
   { 
      private string symbol; 
      private double price;
      private int size;
      public event PropertyChangedEventHandler PropertyChanged; 
      
      public Stock(string symbol, double price, int size) 
      { 
         this.symbol = symbol; this.price = price; this.size = size; 
      } 
      
      public string Symbol
      { 
         get { return symbol; }
      } 
      
      public double Price 
      {
         get { return price; } 
         set 
         { 
            if (price != value) 
            { 
               price = value;
               OnPropertyChanged("Price");
            } 
         } 
      } 

      public int Size 
      {
         get { return size; } 
         set 
         {
            if (size != value)
            {
               size = value; 
               OnPropertyChanged("Size"); 
            }
         }
      }
      
      private void OnPropertyChanged(string propertyName) 
      { 
         if(PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
      } 
   }
}


这篇关于将列表绑定到DataGridView C#WinForm的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆