Jame
Jame

Reputation: 22180

How to fill DataGridView Programmatically

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?

Upvotes: 3

Views: 26960

Answers (2)

Luc Morin
Luc Morin

Reputation: 5380

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.

Upvotes: 3

DooDoo
DooDoo

Reputation: 13437

What is Perfect for you?You can create a DataTable and bind it to your grid that automatically creates your columns

Upvotes: 0

Related Questions