简体   繁体   中英

Fill the DatagridView with empty rows

I have one datagridview in my windows form. That is filling data from database based on selected value in the combo-box. For some selected item there is record in the database. for some there is no records. At that time i need to maintain a fixed size datagridview with no records filled in it. Is there any way to do this. If yes please help me...

If your datasource looks similar to this:

    public class MyDataSource : IEnumerable<SomeClass>
    {}

-you may simply do this:

    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;
        }
    }

"sourceItems" is the internal list of items of the type "SomeClass". There are many ways to do this and this is just one of them.

What you are doing today is to load data from database and write the result directly to datagridview. What I suggest is that you load data from database (as you do now) and instead of writing data to datagrid, you create a class to hold the items (a datasource class). That class is then given to the datagrid similar to this:

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

Then use the BindingSource to controll the contents (just to show some of the things you may do):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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