使用空行填充DatagridView

时间:2012-10-10 12:06:28

标签: c# winforms datagridview

我的Windows窗体中有一个datagridview。这是根据组合框中的选定值从数据库填充数据。对于某些选定项目,数据库中有记录。对某些人来说没有记录。那时我需要维护一个固定大小的datagridview,其中没有记录。有没有办法做到这一点。如果有,请帮帮我......

1 个答案:

答案 0 :(得分:0)

如果您的数据源看起来与此类似:

    public class MyDataSource : IEnumerable<SomeClass>
    {}

- 你可以这样做:

    public IEnumerator<SomeClass> GetEnumerator()
    {
        if (sourceItems == null)
        {
            yield return SomeClass.Empty;
            //as many times as you want "empty" lines in datagrid
        }
        else
        {
            foreach (var item in sourceItems)
               yield return item;
        }
    }

&#34; sourceItems&#34;是#34; SomeClass&#34;类型的项目的内部列表。 有很多方法可以做到这一点,这只是其中之一。

您今天所做的是从数据库加载数据并将结果直接写入datagridview。我建议你从数据库加载数据(就像你现在一样),而不是将数据写入datagrid,你创建一个类来保存项(数据源类)。然后将该类赋予datagrid,类似于:

MyDataSource ds = new MyDataSource();
GetDataFromDatabase().Select(p=>ds.Add(p));
BindingSource bs = new BindingSource(ds, ");
theDataGrid.DataSource = bs;

然后使用BindingSource来控制内容(只是为了展示你可能会做的一些事情):

 bs.AllowNew = false;
 bs.Position = bs.Count - 1;
 bs.ListChanged += new ListChangedEventHandler(bindingSource_ListChanged);
 bs.CurrentItemChanged += new EventHandler(bindingSource_CurrentItemChanged);
相关问题