简体   繁体   中英

Sorting Inside datagridview in c#

I am having datagridview in c#

I populated data inside datagridview.

I created Serial No inside datagridview along with other columns.

If i click serial no head,the serial no is sorted. If i do sorting in other columns,the serial no is also sorted.

How to avoid sorting serial no, if I click other column headers.

I have given the code below

         dsstock = new DataSet();
        dsstock = fetchDataSetValues(statement);
      //  grdStock.Rows.Clear();
        if (dsstock.Tables[0].Rows.Count > 0)
        {
            grdStock.Columns.Add("Sl. No.", "Sl. No.");
            grdStock.Columns[0].Width = 80;

            grdStock.Columns.Add("ItemID", "Item ID");
            grdStock.Columns[1].Width =300;
            grdStock.Columns.Add("ItemName", "Item Name");
            grdStock.Columns[2].Width = 600;
            grdStock.Columns.Add("ItemQuantity", "Item Quantity");
            grdStock.Columns[3].Width = 150;
            int row = dsstock.Tables[0].Rows.Count - 1;

            for (int r = 0; r <= row; r++)
            {
                grdStock.Rows.Add();
                grdStock.Rows[r].Cells[0].Value = r + 1;
                grdStock.Rows[r].Cells[1].Value = dsstock.Tables[0].Rows[r].ItemArray[0];
                grdStock.Rows[r].Cells[2].Value = dsstock.Tables[0].Rows[r].ItemArray[1];
                grdStock.Rows[r].Cells[3].Value = dsstock.Tables[0].Rows[r].ItemArray[2];

            }
        }

Thanks

Chandran

If I understand correctly, you want a way to keep the rows numbered the same regardless of which data is there (like Excel does). That seems odd to me if you are assigning a serial number to each item/row, but anyway there is a simple solution at Show row number in row header of a DataGridView . (You can see a screenshot at https://stackoverflow.com/a/14915110/116891 .)

private void dgGrid_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
    var grid = sender as DataGridView;
    var rowIdx = (e.RowIndex + 1).ToString();

    var centerFormat = new StringFormat() 
    { 
        // right alignment might actually make more sense for numbers
        Alignment = StringAlignment.Center, 
        LineAlignment = StringAlignment.Center
    };

    var headerBounds = new Rectangle(e.RowBounds.Left, e.RowBounds.Top, grid.RowHeadersWidth, e.RowBounds.Height);
    e.Graphics.DrawString(rowIdx, this.Font, SystemBrushes.ControlText, headerBounds, centerFormat);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM