Windows forms datagridview сортировка

Реализация DI в PHP

Jason-Webb 13.05.2025

Когда я начинал писать свой первый крупный PHP-проект, моя архитектура напоминала запутаный клубок спагетти. Классы создавали другие классы внутри себя, зависимости жостко прописывались в коде, а о. . .

Обработка изображений в реальном времени на C# с OpenCV

stackOverflow 13.05.2025

Объединение библиотеки компьютерного зрения OpenCV с современным языком программирования C# создаёт симбиоз, который открывает доступ к впечатляющему набору возможностей. Ключевое преимущество этого. . .

POCO, ACE, Loki и другие продвинутые C++ библиотеки

NullReferenced 13.05.2025

В C++ разработки существует такое обилие библиотек, что порой кажется, будто ты заблудился в дремучем лесу. И среди этого многообразия POCO (Portable Components) – как маяк для тех, кто ищет. . .

Паттерны проектирования GoF на C#

UnmanagedCoder 13.05.2025

Вы наверняка сталкивались с ситуациями, когда код разрастается до неприличных размеров, а его поддержка становится настоящим испытанием. Именно в такие моменты на помощь приходят паттерны Gang of. . .

Создаем CLI приложение на Python с Prompt Toolkit

py-thonny 13.05.2025

Современные командные интерфейсы давно перестали быть черно-белыми текстовыми программами, которые многие помнят по старым операционным системам. CLI сегодня – это мощные, интуитивные и даже. . .

Конвейеры ETL с Apache Airflow и Python

AI_Generated 13.05.2025

ETL-конвейеры – это набор процессов, отвечающих за извлечение данных из различных источников (Extract), их преобразование в нужный формат (Transform) и загрузку в целевое хранилище (Load). . . .

Выполнение асинхронных задач в Python с asyncio

py-thonny 12.05.2025

Современный мир программирования похож на оживлённый мегаполис – тысячи процессов одновременно требуют внимания, ресурсов и времени. В этих джунглях операций возникают ситуации, когда программа. . .

Работа с gRPC сервисами на C#

UnmanagedCoder 12.05.2025

gRPC (Google Remote Procedure Call) — открытый высокопроизводительный RPC-фреймворк, изначально разработанный компанией Google. Он отличается от традиционых REST-сервисов как минимум тем, что. . .

CQRS (Command Query Responsibility Segregation) на Java

Javaican 12.05.2025

CQRS — Command Query Responsibility Segregation, или разделение ответственности команд и запросов. Суть этого архитектурного паттерна проста: операции чтения данных (запросы) отделяются от операций. . .

Шаблоны и приёмы реализации DDD на C#

stackOverflow 12.05.2025

Когда я впервые погрузился в мир Domain-Driven Design, мне показалось, что это очередная модная методология, которая скоро канет в лету. Однако годы практики убедили меня в обратном. DDD — не просто. . .

Элемент управления DataGridView обеспечивает автоматическую сортировку, но в определенных ситуациях может потребоваться настроить операции сортировки. Например, с помощью программной сортировки можно создать альтернативный пользовательский интерфейс. Кроме того, можно обработать событие SortCompare или вызвать перегрузку Sort(IComparer) метода Sort для обеспечения большей гибкости сортировки, например для сортировки нескольких столбцов.

В приведенных ниже примерах кода демонстрируются эти три подхода к пользовательской сортировке. Дополнительные сведения см. в разделе Установка режимов сортировки для столбцов элемента управления DataGridView в Windows Forms.

Программная сортировка

В примере кода ниже демонстрируется программная сортировка с использованием свойств SortOrder и SortedColumn для определения направления сортировки и свойства SortGlyphDirection для ручной установки глифа сортировки. Перегрузка Sort(DataGridViewColumn,ListSortDirection) метода Sort используется для сортировки данных только в одном столбце.

using System;
using System.ComponentModel;
using System.Windows.Forms;

class Form1 : Form
{
    private Button sortButton = new Button();
    private DataGridView dataGridView1 = new DataGridView();

    // Initializes the form.
    // You can replace this code with designer-generated code.
    public Form1()
    {
        dataGridView1.Dock = DockStyle.Fill;
        dataGridView1.AllowUserToAddRows = false;
        dataGridView1.SelectionMode =
            DataGridViewSelectionMode.ColumnHeaderSelect;
        dataGridView1.MultiSelect = false;

        sortButton.Dock = DockStyle.Bottom;
        sortButton.Text = "Sort";

        Controls.Add(dataGridView1);
        Controls.Add(sortButton);
        Text = "DataGridView programmatic sort demo";
    }

    // Establishes the main entry point for the application.
    [STAThreadAttribute()]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.Run(new Form1());
    }

    // Populates the DataGridView.
    // Replace this with your own code to populate the DataGridView.
    public void PopulateDataGridView()
    {
        // Add columns to the DataGridView.
        dataGridView1.ColumnCount = 2;
        dataGridView1.Columns[0].HeaderText = "Last Name";
        dataGridView1.Columns[1].HeaderText = "City";
        // Put the new columns into programmatic sort mode
        dataGridView1.Columns[0].SortMode = 
            DataGridViewColumnSortMode.Programmatic;
        dataGridView1.Columns[1].SortMode =
            DataGridViewColumnSortMode.Programmatic;

        // Populate the DataGridView.
        dataGridView1.Rows.Add(new string[] { "Parker", "Seattle" });
        dataGridView1.Rows.Add(new string[] { "Watson", "Seattle" });
        dataGridView1.Rows.Add(new string[] { "Osborn", "New York" });
        dataGridView1.Rows.Add(new string[] { "Jameson", "New York" });
        dataGridView1.Rows.Add(new string[] { "Brock", "New Jersey" });
    }

    protected override void OnLoad(EventArgs e)
    {
        sortButton.Click += new EventHandler(sortButton_Click);

        PopulateDataGridView();
        base.OnLoad(e);
    }

    private void sortButton_Click(object sender, System.EventArgs e)
    {
        // Check which column is selected, otherwise set NewColumn to null.
        DataGridViewColumn newColumn =
            dataGridView1.Columns.GetColumnCount(
            DataGridViewElementStates.Selected) == 1 ?
            dataGridView1.SelectedColumns[0] : null;

        DataGridViewColumn oldColumn = dataGridView1.SortedColumn;
        ListSortDirection direction;

        // If oldColumn is null, then the DataGridView is not currently sorted.
        if (oldColumn != null)
        {
            // Sort the same column again, reversing the SortOrder.
            if (oldColumn == newColumn &&
                dataGridView1.SortOrder == SortOrder.Ascending)
            {
                direction = ListSortDirection.Descending;
            }
            else
            {
                // Sort a new column and remove the old SortGlyph.
                direction = ListSortDirection.Ascending;
                oldColumn.HeaderCell.SortGlyphDirection = SortOrder.None;
            }
        }
        else
        {
            direction = ListSortDirection.Ascending;
        }

        // If no column has been selected, display an error dialog  box.
        if (newColumn == null)
        {
            MessageBox.Show("Select a single column and try again.",
                "Error: Invalid Selection", MessageBoxButtons.OK,
                MessageBoxIcon.Error);
        }
        else
        {
            dataGridView1.Sort(newColumn, direction);
            newColumn.HeaderCell.SortGlyphDirection =
                direction == ListSortDirection.Ascending ?
                SortOrder.Ascending : SortOrder.Descending;
        }
    }
}

Пользовательская сортировка с помощью события SortCompare

В примере кода ниже демонстрируется пользовательская сортировка с использованием обработчика событий SortCompare. Выбранный столбец DataGridViewColumn сортируется, а при обнаружении в нем повторяющихся значений столбец ID используется для определения конечного порядка.

#region Using directives

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;

#endregion
class Form1 : Form
{
    private DataGridView dataGridView1 = new DataGridView();

    // Establish the main entry point for the application.
    [STAThreadAttribute()]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.Run(new Form1());
    }

    public Form1()
    {
        // Initialize the form.
        // This code can be replaced with designer generated code.
        dataGridView1.AllowUserToAddRows = false;
        dataGridView1.Dock = DockStyle.Fill;
        dataGridView1.SortCompare += new DataGridViewSortCompareEventHandler(
            this.dataGridView1_SortCompare);
        Controls.Add(this.dataGridView1);
        this.Text = "DataGridView.SortCompare demo";

        PopulateDataGridView();
    }

    // Replace this with your own population code.
    public void PopulateDataGridView()
    {
        // Add columns to the DataGridView.
        dataGridView1.ColumnCount = 3;

        // Set the properties of the DataGridView columns.
        dataGridView1.Columns[0].Name = "ID";
        dataGridView1.Columns[1].Name = "Name";
        dataGridView1.Columns[2].Name = "City";
        dataGridView1.Columns["ID"].HeaderText = "ID";
        dataGridView1.Columns["Name"].HeaderText = "Name";
        dataGridView1.Columns["City"].HeaderText = "City";

        // Add rows of data to the DataGridView.
        dataGridView1.Rows.Add(new string[] { "1", "Parker", "Seattle" });
        dataGridView1.Rows.Add(new string[] { "2", "Parker", "New York" });
        dataGridView1.Rows.Add(new string[] { "3", "Watson", "Seattle" });
        dataGridView1.Rows.Add(new string[] { "4", "Jameson", "New Jersey" });
        dataGridView1.Rows.Add(new string[] { "5", "Brock", "New York" });
        dataGridView1.Rows.Add(new string[] { "6", "Conner", "Portland" });

        // Autosize the columns.
        dataGridView1.AutoResizeColumns();
    }

    private void dataGridView1_SortCompare(object sender,
        DataGridViewSortCompareEventArgs e)
    {
        // Try to sort based on the cells in the current column.
        e.SortResult = System.String.Compare(
            e.CellValue1.ToString(), e.CellValue2.ToString());

        // If the cells are equal, sort based on the ID column.
        if (e.SortResult == 0 && e.Column.Name != "ID")
        {
            e.SortResult = System.String.Compare(
                dataGridView1.Rows[e.RowIndex1].Cells["ID"].Value.ToString(),
                dataGridView1.Rows[e.RowIndex2].Cells["ID"].Value.ToString());
        }
        e.Handled = true;
    }
}

Пользовательская сортировка с помощью интерфейса IComparer

В примере кода ниже демонстрируется пользовательская сортировка с помощью перегрузки Sort(IComparer) метода Sort, которая принимает реализацию интерфейса IComparer для выполнения сортировки по нескольким столбцам.

#region Using directives

using System;
using System.Drawing;
using System.Windows.Forms;

#endregion

class Form1 : Form
{
    private DataGridView DataGridView1 = new DataGridView();
    private FlowLayoutPanel FlowLayoutPanel1 = new FlowLayoutPanel();
    private Button Button1 = new Button();
    private RadioButton RadioButton1 = new RadioButton();
    private RadioButton RadioButton2 = new RadioButton();

    // Establish the main entry point for the application.
    [STAThreadAttribute()]
    public static void Main()
    {
        Application.Run(new Form1());
    }

    public Form1()
    {
        // Initialize the form.
        // This code can be replaced with designer generated code.
        AutoSize = true;
        Text = "DataGridView IComparer sort demo";

        FlowLayoutPanel1.FlowDirection = FlowDirection.TopDown;
        FlowLayoutPanel1.Location = new System.Drawing.Point( 304, 0 );
        FlowLayoutPanel1.AutoSize = true;

        FlowLayoutPanel1.Controls.Add( RadioButton1 );
        FlowLayoutPanel1.Controls.Add( RadioButton2 );
        FlowLayoutPanel1.Controls.Add( Button1 );

        Button1.Text = "Sort";
        RadioButton1.Text = "Ascending";
        RadioButton2.Text = "Descending";
        RadioButton1.Checked = true;

        Controls.Add( FlowLayoutPanel1 );
        Controls.Add( DataGridView1 );
    }

    protected override void OnLoad( EventArgs e )
    {
        PopulateDataGridView();
        Button1.Click += new EventHandler(Button1_Click);

        base.OnLoad( e );
    }

    // Replace this with your own code to populate the DataGridView.
    private void PopulateDataGridView()
    {

        DataGridView1.Size = new Size(300, 300);

        // Add columns to the DataGridView.
        DataGridView1.ColumnCount = 2;

        // Set the properties of the DataGridView columns.
        DataGridView1.Columns[0].Name = "First";
        DataGridView1.Columns[1].Name = "Last";
        DataGridView1.Columns["First"].HeaderText = "First Name";
        DataGridView1.Columns["Last"].HeaderText = "Last Name";
        DataGridView1.Columns["First"].SortMode = 
            DataGridViewColumnSortMode.Programmatic;
        DataGridView1.Columns["Last"].SortMode = 
            DataGridViewColumnSortMode.Programmatic;

        // Add rows of data to the DataGridView.
        DataGridView1.Rows.Add(new string[] { "Peter", "Parker" });
        DataGridView1.Rows.Add(new string[] { "James", "Jameson" });
        DataGridView1.Rows.Add(new string[] { "May", "Parker" });
        DataGridView1.Rows.Add(new string[] { "Mary", "Watson" });
        DataGridView1.Rows.Add(new string[] { "Eddie", "Brock" });
    }

    private void Button1_Click( object sender, EventArgs e )
    {
        if ( RadioButton1.Checked == true )
        {
            DataGridView1.Sort( new RowComparer( SortOrder.Ascending ) );
        }
        else if ( RadioButton2.Checked == true )
        {
            DataGridView1.Sort( new RowComparer( SortOrder.Descending ) );
        }
    }

    private class RowComparer : System.Collections.IComparer
    {
        private static int sortOrderModifier = 1;

        public RowComparer(SortOrder sortOrder)
        {
            if (sortOrder == SortOrder.Descending)
            {
                sortOrderModifier = -1;
            }
            else if (sortOrder == SortOrder.Ascending)
            {
                sortOrderModifier = 1;
            }
        }

        public int Compare(object x, object y)
        {
            DataGridViewRow DataGridViewRow1 = (DataGridViewRow)x;
            DataGridViewRow DataGridViewRow2 = (DataGridViewRow)y;

            // Try to sort based on the Last Name column.
            int CompareResult = System.String.Compare(
                DataGridViewRow1.Cells[1].Value.ToString(),
                DataGridViewRow2.Cells[1].Value.ToString());

            // If the Last Names are equal, sort based on the First Name.
            if ( CompareResult == 0 )
            {
                CompareResult = System.String.Compare(
                    DataGridViewRow1.Cells[0].Value.ToString(),
                    DataGridViewRow2.Cells[0].Value.ToString());
            }
            return CompareResult * sortOrderModifier;
        }
    }
}

Компиляция кода

Для этих примеров требуются:

  • ссылки на сборки System, System.Drawing и System.Windows.Forms.

Сведения о сборке этих примеров из командной строки для Visual Basic или Visual C#, см. в разделе построение из командной строки или командной строки создания с помощью csc.exe. Можно также сборке этого примера в Visual Studio путем вставки кода в новый проект.

См. также

  • DataGridView
  • Сортировка данных в элементе управления DataGridView в Windows Forms
  • Установка режимов сортировки для столбцов элемента управления DataGridView в Windows Forms
  • Практическое руководство. Определение режимов сортировки для столбцов элемента управления DataGridView в Windows Forms

by Igor Katenov, Lead Developer of 10Tec Products

Microsoft’s DataGridView control, supplied as a part of the .NET Framework starting with the version 2.0, is a versatile grid control for displaying and manipulating tabular data. It also provides many basic features any serious grid control must have, including sorting. For instance, you can sort a DataGridView column when you click the column’s header:

Sort DataGridView column in C#

However, there are many subtleties and nuances related to DataGridView sorting. The aim of this article is to highlight main possible troubles you can face when you sort DataGridView in C#.

Sorting a DataGridView column

The MSDN documentation for the DataGridViewColumn.SortMode Property states that DataGridView sorts a column if the column’s SortMode property is set to DataGridViewColumnSortMode.Automatic, which is the default setting for any DataGridViewTextBoxColumn. You might suppose then that a user can simply sort by any column by clicking on the column’s heading, but surprisingly, this is not the case!

The explanation lies in the fact that DataGridView does not internally sort its rows itself. Instead, it exploits the sorting functionality of the attached data source, and if the data source does not provide sorting functionality, DataGridView column sorting is not available also. To be more precise, the data source must implement the IBindingList interface with sorting support (namely the SupportsSorting member and all related members like IsSorted, ApplySort, and so on). That should answer all your potential future questions like why DataGridView does not sort columns of a LINQ query result, items of an EntityCollection from the Entity Framework, or even a list object – because all those data sources do not support built-in sorting. It seems, the only native .NET class that has built-in sorting is DataView, which is used implicitly when you assign a DataTable or a similar ADO.NET data source to the DataSource property of a DataGridView control.

One of the possible solutions to this problem is to wrap your data into an IBindingList object that implements sorting. The Internet can supply numerous examples of creating a so called SortableBindingList class for that. Below is a link to a StackOverflow question that demonstrates how to implement a SortableBindingList for a custom class:

C# — troubles with sorting datagridview

Disable DataGridView sorting

Now we know how to enable sorting in a DataGridView, but we may need to implement the opposite task – disable DataGridView sorting. If you want to disable column sorting when the user clicks a DataGridView’s column headers, simply set the aforementioned SortMode property for your DataGridView columns to DataGridViewColumnSortMode.NotSortable.

If you need to disable column sorting for all columns, you can write a universal code and avoid duplicating this setting for every individual column. Below is a typical example how to disable DataGridView sorting for all columns in C#:

private void dataGridView1_ColumnAdded(object sender, DataGridViewColumnEventArgs e)
{
   dataGridView1.Columns[e.Column.Index].SortMode = DataGridViewColumnSortMode.NotSortable;
}

It implies that you attach this event handler to the DataGridView’s ColumnAdded event before you define columns or the DataGridView generates them automatically when you bind the DataGridView to a data source. Other solutions can be found in this thread on StackOverflow.

How to sort DataGridView programmatically

So far, we have been discussing interactive sorting in DataGridView i.e. the sorting performed when the user clicks a DataGridView column header. In a real-world app you may need to sort DataGridView programmatically from C# code. There may be several reasons for that. For instance, your users may want to see a DataGridView sorted by a column in descending order by default when they launch your app.

DataGridView provides you with the Sort method you should use for that. We need one of its overloaded versions that accepts the DataGridView column to sort by and the desired sort order. Below is a C# example that demonstrates how to sort a DataGridView programmatically by the «Date Added» column in descending order:

dataGridView1.Sort(dataGridView1.Columns["DateAdded"],
   System.ComponentModel.ListSortDirection.Descending);

One important note though, when you retrieve a DataGridView column object using the Columns collection, don’t forget that you must use the name of the column but not its column header text – they may differ from each other in the general case.

Custom sorting in DataGridView

Continuing the topic of programmatic sorting in DataGridView, let’s note the SortCompare event used to implement custom sorting in DataGridView. This event is raised when you call the overloaded version of the Sort method mentioned above (by the way, it also works when we click a column’s header of a DataGridView in the interface to sort it by that column). If you want to order rows using a custom rule, you code your comparison logic in a handler of the SortCompare event and set its e.Handled argument to True to tell the DataGridView that it should not do its standard comparison work.

The Microsoft Docs portal contains a wonderful C# example of Custom Sorting Using the SortCompare Event. It demonstrates how to sort the selected column and use the values of the ID column to determine the final row order if the column contains duplicate values.

Unfortunately, there is one serious limitation on the use of custom sorting in DataGridView: the SortCompare event can be used only when DataGridView works in unbound mode.

Sort DataGridView by multiple columns programmatically (unbound mode)

One of the overloaded versions of DataGridView’s Sort method allows you to sort DataGridView by multiple columns programmatically in unbound mode. You need to use the other overloaded version of the method that accepts an object implementing the System.Collections.IComparer interface. A classic example of this interface usage demonstrates how to sort unbound DataGridView by two columns:

The C# source code of the custom comparer used for this DataGridView is as follows:

public class DGVComparer : System.Collections.IComparer
{
  public int Compare(object x, object y)
  {
    DataGridViewRow row1 = (DataGridViewRow)x;
    DataGridViewRow row2 = (DataGridViewRow)y;

    int compareResult = string.Compare(
        (string)row1.Cells[0].Value,
        (string)row2.Cells[0].Value);

    if (compareResult == 0)
    {
      compareResult = ((int)row1.Cells[1].Value).CompareTo((int)row2.Cells[1].Value);
    }

    return compareResult;
  }
}

Below is the corresponding code snippet that demonstrates how to use this custom comparer:

dataGridView1.Sort(new DGVComparer());
dataGridView1.Columns[0].HeaderCell.SortGlyphDirection = SortOrder.Ascending;
dataGridView1.Columns[1].HeaderCell.SortGlyphDirection = SortOrder.Ascending;

Note that we set the sort glyphs manually as our unbound DataGridView knows nothing about the current sort order of its columns.

This approach can be used to sort DataGridView when the user clicks its column headers. Generally this logic is put in an event handler of the ColumnHeaderMouseClick event. But it’s very hard to implement this technique if you want to provide your users with the ability to sort more than two columns in an unbound DataGridView, especially if the columns store values of different data types. Return to the source code of the custom comparer used above and see that we hard-coded the comparison logic for the two columns of the predefined data types.

Alternative DataGridView sorting solution – iGrid.NET

10Tec iGrid.NET is a WinForms grid control similar to DataGridView, and it can be considered as a superior DataGridView alternative in many aspects. You can find out more about all features of this control in the product section on this website, but let us highlight its sorting functionality and how this compares to DataGridView in this article dedicated to sorting in DataGridView.

First of all, multi-column sorting is built-in. The user can simply click iGrid’s column headers holding down the Shift or Ctrl key to sort this unbound DataGridView replacement by multiple columns:

Multiple column sort in unbound DataGridView replacement

Notice that the column headers of the sorted columns display numbers after the sort glyphs. These numbers indicate the order of the columns in the current sort criteria.

Compared to DataGridView, you can sort multiple columns in iGrid regardless of the data source used to populate it. And if required, custom sorting is also at your disposal at any time.

Next time you are fighting with sorting DataGridView in C#, may we suggest you try iGrid.NET instead?

Read more about the 10Tec DataGridView alternative »

Добрый день!
В наличии:
— C# WinForm приложение
— таблица (datagridview) с 9 столбцами, один из которых содержит дату и время в формате:
«10.02.2015 12:25:36» в текстовом формате (в дату переделать нет возможности — требование заказчика)
Необходимо:
— Выполнить сортировку по этому столбцу (по возрастанию) при нажатии на заголовок столбца

Примечания
С сортировкой в datagridview никогда не сталкивался.


  • Вопрос задан

  • 6940 просмотров

Пригласить эксперта

Гуглится за 17 секунд:
https://msdn.microsoft.com/en-us/library/bb383929%…

Цитирую:
The DataGridView control provides automatic sorting, so that user can manually sort any column in the control. You can control whether a column can be sorted by setting the SortMode property of the DataGridViewColumn. You can also programmatically sort a column.

Вам нужно, чтобы пользователь мог вручную, значит надо проставить SortMode в Automatic

Вот тут посмотрите: DataGridView.Sort

Там указан пример реализации IComparer`а, который нужно дать методу сорт. Вам нужно изменить у класса RowComparer метод Compare. В вашей реализации сравнения двух DataGridViewRow вам нужно выделить содержимое ячейки с текстом даты, распарсить с помощью DateTime.Parse и выдать результат сравнения дат.


  • Показать ещё
    Загружается…

Минуточку внимания

What is Datagridview Sorting?

  • In general, the DataGridView control provides automatic sorting, so that user can manually sort any column in the control.
  • Here we can control whether a column can be sorted by setting the SortMode property of the DataGridViewColumn.
  • We can also programmatically sort a column.

DataGridview Sorting

How to sort Datagridview

  • In C#, the DataGridView control provides an automatic sorting, so that we can automatically sort any column in the datagridview control.
  • We can sort the data in ascending or descending order based on the contents of the specified column.
  • Also we can see the DataGridView sorting, when a user clicks on the column header.

Syntax

dataGridView1.Sort(dataGridView1.Columns[1], ListSortDirection.Ascending);

 c-sharp sorting

  1. Here Fetch Data button will display the data values from the SQL and displays it by clicking it.
  2. Go to tool box and click on the DataGridview option the form will be open.
  3. Go to tool box and click on the button option and put the name as Sort in the button.
  4. Here thetext field is specifying to enter the text in text field.

C# Sample Code — C# Examples

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WikiTechy_Csharp_Windows_Application
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
         
        private void button1_Click(object sender, EventArgs e)
        {
            string connectionString =
                @"Data Source=VENKAT\KAASHIV;Initial Catalog=wikitechy;user id = venkat;password=venkat";

            string sql = "SELECT * FROM login_table";

SqlConnection connection = new SqlConnection(connectionString);
SqlDataAdapter dataadapter = new SqlDataAdapter(sql, connection);

            DataSet ds = new DataSet();

            connection.Open();
                        dataadapter.Fill(ds);
            connection.Close();

            dataGridView1.DataSource = ds.Tables[0];  

        }

        private void button2_Click(object sender, EventArgs e)
        {
            dataGridView1.Sort(dataGridView1.Columns[1], ListSortDirection.Ascending);
        }
    }
}

Code Explanation:

 c-sharp sorting code

  1. Here private void button2_Click(object sender, EventArgs e) click event handler for button2 specifies, which is a normal Button control in Windows Forms. The two parameters, «object sender» and «EventArgs e» parameters of function of event of a button such as private void button2_Click(object sender, EventArgs e). Here dataGridView1.Sort(dataGridView1.Columns[1], ListSortDirection.Ascending); specifies to Sorts the contents of the DataGridView control in ascending order based on the contents of the specified column.

Sample Output

 c-sharp sorting code output

  1. Here in this output the Fetch Data button will display the data values from the SQL and displays it by clicking it.
  2. Here in this output table displays the Id «1,2,3» and name «venkat, jln, arun».

 c-sharp sorting code output1

  1. Here in this output the Fetch Data button will display the data values from the SQL and displays it by clicking it.
  2. Here in this output table displays the Id «3,2,1» and name «arun, jln, venkat».
  3. Here in this output we display Sort, which specifies click on Sort button then the table id’s and names are converted into ascending order (A to Z).

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Как сдвинуть кнопку пуск в windows 11
  • The sims 3 windows 7 32 bit
  • Windows mouse registry settings
  • Состояние 0xc0000225 сбой меню загрузки windows 7 что делать
  • Рабочий стол как на mac для windows 10