Code Q & A
  • index
  • Java
  • python
  • javascript
No Result
View All Result
Code Q & A
  • index
  • Java
  • python
  • javascript
No Result
View All Result
Code Q & A
No Result
View All Result

Winforms Datagridview Sort by Combobox Displaymember

06/23/2022
in combobox, datagridview, winforms
Reading Time: 2 mins read

I have an issue where I am trying to sort a Datagridview by the Combobox DisplayMember instead of the ValueMember.

The Datagridview is Databound to a Datatable which is populated from a SQL query and the Combobox is populated by the results of a LinqQuery.

Code-behind for Form populating Datagridview and Sorting

Dictionary<string, string> search = new Dictionary<string, string>();
            search.Add("ID", "ID");
            search.Add("ClientID", "ClientID");
            search.Add("ClientCode", "ClientCode");
            search.Add("BatchRef", "BatchRef");
            search.Add("CaseRef", "CaseRef");
            search.Add("AccountNo", "AccountNo");
             search.Add("MeterName", "MeterName");
            search.Add("MeterAddress", "MeterAdd");
            search.Add("MeterPostcode", "MeterPostcode");
            search.Add("AgentID", "AgentID");
            search.Add("CompletedDate", "CompletedDate");
            search.Add("SubmittedDate", "SubmittedDate");

            Systems.PopulateDataGrid(search, dgvSearch, SQLHelper.FillDataTable(sql, CommandType.Text, searchParameters));

private void dgvSearch_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            ListSortDirection direction;

            if (dgvSearch.Columns[e.ColumnIndex].HeaderText == "Agent")
            {
                if (dgvSearch.SortOrder == System.Windows.Forms.SortOrder.Ascending)
                    direction = ListSortDirection.Descending;
                else
                    direction = ListSortDirection.Ascending;

                dgvSearch.Sort(dgvSearch.Columns[e.ColumnIndex], direction);
            }
        }

Systems.PopulateDatagrid

 internal static void PopulateDataGrid(Dictionary<string, string> dataGrid, DataGridView dgv, DataTable dt)
        {
            dgv.AutoGenerateColumns = false;
            foreach (KeyValuePair<string, string> row in dataGrid)
            {
                dgv.Columns[row.Key].DataPropertyName = row.Value;
            }
            dgv.DataSource = dt;
        }

SQLHelper.FillDatatable

internal static DataTable FillDataTable(string strSQL, CommandType CT, List<SqlParameter> parameters)
        {
            var ds = new DataSet("UMDS");
            DataTable dt = ds.Tables.Add("UMDT");
            ds.EnforceConstraints = false;

            using (var cn = new SqlConnection(SQLHelper.ConnectionString))
            {
                using (var cmd = new SqlCommand(strSQL, cn))
                {
                    cmd.CommandType = CT;

                    if (parameters != null)
                    {
                        DateTime dateTime;

                        foreach (SqlParameter p in parameters)
                        {
                            if (p.Value == null || string.IsNullOrEmpty(p.Value.ToString()) || p.Value.ToString() == Systems.MASKEDDATE || p.Value.ToString() == Systems.MASKEDTIME)
                            {
                                p.Value = DBNull.Value;
                            }
                            else if (DateTime.TryParse(p.Value.ToString(), out dateTime))
                            {
                                p.Value = dateTime;
                            }
                            cmd.Parameters.Add(p);
                        }
                    }

                    try
                    {
                        cn.Open();
                        using (SqlDataReader dr = cmd.ExecuteReader())
                        {
                            dt.Load(dr);
                        }

                    }
                    catch (SqlException ex)
                    {
                        Systems.Msg("Database Error", "Error Loading Data from Database. Please try again.\n\n" + ex.Message, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            return dt;
        }

When clicking on the Header for "AgentID" it is sorting by the ValueMember instead of the DisplayMember.

Answering my own question:

Managed to find the answer on another SO question after some more googling.

Tags: comboboxdatagridviewwinforms
ShareTweetPin

Related Posts

c#

Getting Serializable Error Even After Inserting [Serializable] Before Class

I created a class public class clsCategories { public static List<infoCategories> listCategories = new List<infoCategories>(); public void serialize() { BinaryFormatter...

c#

Serialization Exception

i am trying to save a state of a chessGameplay. private void saveToolStripMenuItem_Click(object sender, EventArgs e)// menu strip control {...

c#

How do I have an enum bound combobox with custom string formatting for enum values?

In the post Enum HowNice { ReallyNice, SortOfNice, NotNice } And then, you call a function GetDescription, using syntax like:...

combobox

Linq-to-sql Null value not displayed in combobox bound to FK

I've a combobox that is binded to a FK entity (the object, not the ID-field). The combobox is filled with...

Next Post

How to make C# Combobox Datasource and Databinding Different

Hot tags

.htaccess .net Algorithm amazon-web-services android Apache c# css c语言 django django-models docker google-app-engine google-cloud-platform hadoop Hive html ios java javascript kubernetes linux macos maven mysql node.js php postgresql python python-2-7 Python 3.X R ruby ruby-on-rails spring SQL SQL SERVER svn TensorFlow ubuntu windows xcode 爬虫 算法 编程语言

    © 2022 Websitedic.com.

    No Result
    View All Result
    • index
    • Java
    • python
    • javascript