Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fill DataGridView Programmatically

Tags:

c#

winforms

I need to fill a DataGridView programmatically. The columnus of the database are fixed and the Rows depends on the size of list. Actually i have List<MyCustomClass> and i need to fill data with that list.

Currently, I am doing this:

public Constructor()
{
    InitializeComponent();
    dataGridViewFiles.AutoGenerateColumns = false;
    dataGridViewFiles.ColumnCount = 3;
    dataGridViewFiles.Columns[0].Name = "File Name";
    dataGridViewFiles.Columns[1].Name = "Total Documents";
    dataGridViewFiles.Columns[2].Name = "Total Pages";
}

Public LoadDGV()
{
    for (int i = 0; i < nTotalInputFiles; i++)
    {//add code here for adding rows to dataGridviewFiles
        DataGridViewRow tempRow = new DataGridViewRow();

        DataGridViewCell cellFileName = new DataGridViewTextBoxCell();
        cellFileName.Value = selectedProject.InputFiles[i].FileName;
        tempRow.Cells.Add(cellFileName);

        DataGridViewCell cellDocCount = new DataGridViewTextBoxCell();
        cellDocCount.Value = selectedProject.InputFiles[i].DocCount.ToString();
        tempRow.Cells.Add(cellDocCount);

        DataGridViewCell cellPageCount = new DataGridViewTextBoxCell();
        cellPageCount.Value = selectedProject.InputFiles[i].PageCount.ToString();
        tempRow.Cells.Add(cellPageCount);

        tempRow.Tag = selectedProject.InputFiles[i].Id;
        dataGridViewFiles.Rows.Add(tempRow);
    }

But the above code some time doesn't perfect. So is there any other way? Or any suggestion to improve above one?

like image 990
Jame Avatar asked Mar 16 '26 19:03

Jame


1 Answers

I would avoid working with the DataGridView directly, and I suggest you use a "model" of some kind that you can then bind the DGV to.

For example, you could use a DataTable with the same scheme as your desired grid, and this way you only manipulate the model.

I've always found it better to use DataBinding and manipulate the model than trying to manipulate the DGV directly.

like image 167
Luc Morin Avatar answered Mar 19 '26 09:03

Luc Morin