none
How to sort in DataGridView

    Question

  • Dear all,

     

    I have a DataGridViewComboBoxColumn in DataGridView which ValueMember is ID and DisplayMember is Name. When I click on Header of DataGridView contains DataGridViewComboBoxColumn, this column only sort by ID not sort by Name.

     

    My code:

     

    DataGridViewComboBoxColumn comboBoxColumn = new DataGridViewComboBoxColumn();

    comboBoxColumn.HeaderText = “ID”;

    comboBoxColumn.Name = “ID”;

    comboBoxColumn.DataPropertyName = “ID”;

    comboBoxColumn.DisplayMember = “NAME”;

    comboBoxColumn.ValueMember = ID;

    comboBoxColumn.MaxDropDownItems = 5;

    comboBoxColumn.DropDownWidth = 100;

    comboBoxColumn.Width = 100;

    comboBoxColumn.DataSource = dataTable;

    comboBoxColumn.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing;

    comboBoxColumn.SortMode = DataGridViewColumnSortMode.Automatic;

     

    dataGridViewCustom.Columns.Add (comboBoxColumn)

     

    However, this code help me sort by ID. Please tell me way sort by Name.

    Thanks so much.

    Thursday, September 08, 2005 12:15 PM

Answers

  • In this case you will have to manually sort your datasource. This is because the Sort functionality when databound is performed by the datasource, for example a DataTable, so when the DataTable sorts it is just using the ID value.

    -mark
    DataGridView Program Manager
    Microsoft
    This post is provided "as-is"

    Thursday, September 22, 2005 10:35 PM

All replies

  • Hello,
    You should try to use the SortCompare event of the DataGridView control.

    Something like this:

    private void dataGridViewCustom_SortCompare(...)
    {
        // extract name corresponding to e.CellValue1
        // extract name corresponding to e.CellValue2
        // set e.SortResult according to comparison of the two extracted names
        e.Handled = true;
    }

    This should work just fine.
    Hope this helps.
    Thanks,
    -regis
    DataGridView Developer
    Microsoft
    This post is provided "as-is"
    Thursday, September 08, 2005 11:09 PM
  • Hi,

    I try to use the SortCompare event of the DataGridView control, however when i click on header columns this event not active.

    Tell me way how to active this event

    Thanks.
    Friday, September 09, 2005 1:27 AM
  • My DataGridView have set DataSource property, so SortCompare event not be active.

    Please tell me way to solve my problem.
    Thanks a lot.
    Friday, September 09, 2005 2:42 AM
  • In this case you will have to manually sort your datasource. This is because the Sort functionality when databound is performed by the datasource, for example a DataTable, so when the DataTable sorts it is just using the ID value.

    -mark
    DataGridView Program Manager
    Microsoft
    This post is provided "as-is"

    Thursday, September 22, 2005 10:35 PM