Best approach to bind a datagridview to database entity/ies

后端 未结 2 1888
逝去的感伤
逝去的感伤 2020-12-06 22:30

Is this aproach the best that exist to databind a datagridview?

I\'ve seen many people with problems binding datagridviews and after a lot of work I found this as t

2条回答
  •  南笙
    南笙 (楼主)
    2020-12-06 23:00

    You could just bind the DataGridView to the DataSource with AutoGenerateColumns on something like

    dataGridView1.DataSource = [yourDataSource]
    

    Then loop through the columns and set their properties in the loop which would allow you to hide columns you don't want to see, name headers etc.

    This is how I do mine

    foreach (DataGridViewColumn col in dgvReconciledItems.Columns)
    {
        switch (col.Name)
        {
            case "Column1":
                col.HeaderText = "Header1";
                col.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
                col.FillWeight = 30;
                break;
            case "Column2":
                col.HeaderText = "Header2";
                col.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
                col.FillWeight = 10;
                break;
    
            default:
                col.Visible = false;
                break;
        }
    }
    

    Any questions let me know

提交回复
热议问题