Click here to Skip to main content
15,887,376 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I created a datagridview PlanningDataView that binds the value of the database, I'm using ADO.NET database model
C#
private void MainDashboard_Load(object sender, EventArgs e)
     {
         int numberRow = 0;
         var planningList = _db.Plannings.Select((q) => new {ID = numberRow, Address = q.Address,
           Phone = q.Phone, Date = q.Date
         }).ToList();
         PlanningDataView.DataSource = planningList;
     }

However, I want to make the ID column in the first grid to generate increment value, just like serial numbers.
C#
private void PlanningDataView_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
    int sno = 1;
    foreach (DataGridViewRow row in PlanningDataView.Rows)
    {
        row.Cells[0].Value = sno++;
    }

    //PlanningDataView.AutoResizeColumns();
}

The output is, the ID iterate, but only 0 number, what I want is 1,2, 3, etc

What I have tried:

I remove lambda ID query and decide to add new column after
 var planningList = _db.Plannings.Select((q) => new {Address = q.Address,
  Phone = q.Phone, Date = q.Date
}).ToList();
PlanningDataView.DataSource = planningList;


This, break the table style but work
private void PlanningDataView_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
    int sno = 1;
    string ID = "ID";
    string headerID = "ID";

    if (PlanningDataView.Columns.Contains(ID))
        PlanningDataView.Columns.Remove(ID);
    {
       PlanningDataView.Columns.Add(ID, headerID);
    }


    PlanningDataView.Columns[ID].DisplayIndex = 0;

    foreach (DataGridViewRow row in PlanningDataView.Rows)
    {
        row.Cells[0].Value = sno++;
    }

    //PlanningDataView.AutoResizeColumns();

    //foreach (DataGridViewRow row in PlanningDataView.Rows)
    //{
    //    PlanningDataView.Rows[0].HeaderCell.Value = string.Format("{0}  ", row.Index + 1).ToString();
    //    row.Height = 25;
    //}
}
Posted
Updated 30-May-20 22:45pm

1 solution

As you are using planningList as the binding source, you should increment the planningList.ID
 
Share this answer
 

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