Click here to Skip to main content
15,215,087 members
Rate this:
Please Sign up or sign in to vote.
I created a datagridview PlanningDataView that binds the value of the database, I'm using ADO.NET database model
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.
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

Rate this:
Please Sign up or sign in to vote.

Solution 1

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

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




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100