Search code examples
c#wpfdatagrid

How to create DataGrid with fixed number of columns?


I have DataGrid control with fixed count of columns (5 columns), which is created via following code:

    m_dictionary_data = new DataGrid();
    {
        //  Dictionary data initialization
        {
            //  Columns generation
            m_dictionary_data.Columns.Add(new DataGridTextColumn() { Header = "Color name", Width = 100 });
            m_dictionary_data.Columns.Add(new DataGridTextColumn() { Header = "Color", Width = 100 });
            m_dictionary_data.Columns.Add(new DataGridTextColumn() { Header = "R", Width = 100 });
            m_dictionary_data.Columns.Add(new DataGridTextColumn() { Header = "G", Width = 100 });
            m_dictionary_data.Columns.Add(new DataGridTextColumn() { Header = "B", Width = 100 });
        }
    }

I have such picture:

enter image description here

This data grid has extra right 6th column

How can I create data grid with fixed count of columns? (I want to remove extra empty column)

EDIT: I made mistake. Actually my data grid has 5 columns. Rest part of control is just extra space


Solution

  • As "Александр Лысенко" already mentioned, fixing the width of the datagrid columns is a way but it is not the best approach. I came around the same problem and after searching a lot came up with a solution from internet that is by far I know is the best known solution.

    You can define the widths of the columns as percentages. For that we can use DataGridLength Object.

    Try something like this.

    m_dictionary_data.Columns.Add(new DataGridTextColumn() { Header = "Color name", Width = new DataGridLength(0.2, DataGridLengthUnitType.Star)});
    m_dictionary_data.Columns.Add(new DataGridTextColumn() { Header = "Color",      Width = new DataGridLength(0.2, DataGridLengthUnitType.Star)});
    m_dictionary_data.Columns.Add(new DataGridTextColumn() { Header = "R",          Width = new DataGridLength(0.2, DataGridLengthUnitType.Star)});
    m_dictionary_data.Columns.Add(new DataGridTextColumn() { Header = "G",          Width = new DataGridLength(0.2, DataGridLengthUnitType.Star)});
    m_dictionary_data.Columns.Add(new DataGridTextColumn() { Header = "B",          Width = new DataGridLength(0.2, DataGridLengthUnitType.Star)});
    

    The above code will divide the datagrid width with equal 5 parts of 20% width each. You can tweak this percentage to give any column more width than the other but the overall percentage should count to '1' to divide the width as required out of 100%. Hope this solves your problem.

    To know more about the DataGridLength and DataGridLengthUnitType

    here are MSDN links

    DataGridLength

    DataGridLengthUnitType