Click here to Skip to main content
15,904,288 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have listed values in datagridview ..and i want to sort that via code and like to know the respective row number as well... how to sort and find the row number as well??
Posted

Here's an example on how to sort a dataGridView. SortColumn is the Column number you want to sort on (From left to right, starting at zero).

C#
int sortColumn = 0;

if(dataGridView.ColumnCount > sortColumn)
{
  dataGrid.Sort(dataGrid.Columns[sortColumn], System.ComponentModel.ListSortDirection.Ascending);
}


As for getting row numbers you can use the Index number from a dataGridView row

C#
MessageBox.Show(dataGridView.Rows[0].Index.ToString());
 
Share this answer
 
I dont want to show the sorted list in the datagridview ... I only want to get the maximum and minimum value of the grid's content along with its row number in the code in any temporary values lets say...
maxVal, maxVamRowNo, minVal, MinValRowNo...
 
Share this answer
 
Another way here.
 
Share this answer
 
In that case:

C#
int sortColumn = 0;

if(dataGrid.ColumnCount > sortColumn)
{
  dataGrid.Sort(dataGrid.Columns[sortColumn], System.ComponentModel.ListSortDirection.Ascending);

  int minValue = -1;
  int minValueRow = -1;
  int maxValue = -1;
  int maxValueRow = -1;

  int.TryParse(dataGrid.Rows[0].Cells[sortColumn].Value.ToString(), out minValue);
  minValueRow = dataGrid.Rows[0].Index;

  int.TryParse(dataGrid.Rows[(dataGrid.Rows.Count - 1)].Cells[sortColumn].Value.ToString(), out maxValue);
  maxValueRow = dataGrid.Rows[(dataGrid.Rows.Count - 1)].Index;
}


Sort Column should be the columnNumber you want to sort and now the min and max values from.

A better way without sorting at all is:

C#
int cell = 0;

if (dataGrid.Rows.Count > 0)
{
    int minValue = Convert.ToInt32(dataGrid.Rows[0].Cells[cell].Value);
    int minValueRow = 0;
    int maxValue = Convert.ToInt32(dataGrid.Rows[0].Cells[cell].Value);
    int maxValueRow = 0;


    for (int i = 0; i < dataGrid.Rows.Count; i++)
    {
        int num = Convert.ToInt32(dataGrid.Rows[i].Cells[cell].Value);

        if (minValue > num)
        {
            minValue = num;
            minValueRow = i;
        }

        if (maxValue < num)
        {
            maxValue = num;
            maxValueRow = i;
        }
    }
}
 
Share this answer
 
v6

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900