简体   繁体   中英

Fill DataGridview with empty rows in c#

I want to fill my point of sales application datagridview fill with empty rows when load. how can I do that using c# .net or can do it with database rows. can anyone help me.

I tried this code:

if (dataGridView1.Rows.Count < 20){
    int r = 20 - dataGridView1.Rows.Count;
    for (int i = 0; i < r; i++){
        AddARow(dt);
    }
}
dataGridView1.DefaultCellStyle.BackColor = Color.SkyBlue;
dataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.White;

I use Mysql database for my application. I saw many point of sales systems using this empty rows in this interface.

this is the gridview i want

I think you just have to add empty elements as ItemSource:

    public class DataItem
    {
        public string Column1 { get; set; }
        public string Column2 { get; set; }

    }


    private void populategrid()
    {
        ObservableCollection<DataItem> list = new ObservableCollection<DataItem>();
        list.Add(new DataItem { Column1 = "", Column2 = "" });
        list.Add(new DataItem { Column1 = "", Column2 = "" });
        list.Add(new DataItem { Column1 = "", Column2 = "" });
        list.Add(new DataItem { Column1 = "", Column2 = "" });

        myDataGrid.ItemsSource = list;
    }

In this case a used a list of DataItem that has strings as properties, but you can use any type.

The easiest way to add a row to your DataGridView is the "dataGridView1.Rows.Add()" method. Use it like this:

for(int i = 0; i < 20; i++)
{
    dataGridView1.Rows.Add();
}

Or like this:

dataGridView1.Rows.Add(20);

Note that you have to add columns first for this to work, otherwise you will get an InvalidOperationException

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