Add a line in a Datagridview with a QUERY as Datasource

Asked

Viewed 32 times

1

First I created a DGV and configured it the way I need, put the column names and formatted column by column the way I need, adding the default value for null, text formatting, type of input, etc.. And after that...

I am using the Entity Framework, so I created a query that returns me a table, with three columns and inserted in the DGV as follows:

 var query = context.DOWNTIME.Where(Corrida => Corrida.CORRIDA == Int32.Parse(corrida) && Corrida.DATAFIM != null)
                                                .Select(Corrida => new { Corrida.DATAINICIO, Corrida.DATAFIM, Corrida.MINUTOS });
    
p.dataGridView2.DataSource = query.ToList();

After inserting the first three columns, which are of the type Datetime and a Double, I tbm added two columns of the type Combobox and inserted another query in each Comboboxcell as follows:

foreach (DataGridViewRow row in p.dataGridView2.Rows)
{
   DataGridViewComboBoxCell theCell = (DataGridViewComboBoxCell)p.dataGridView2[row.Cells[0].ColumnIndex, row.Cells[0].RowIndex];
   var result = context.GrupoDescricao.Select(GrupoDescricao => GrupoDescricao.Grupo).Distinct().ToList();
   theCell.Items.Clear();
   theCell.Items.AddRange(result.ToArray());

   DataGridViewComboBoxCell theCell1 = (DataGridViewComboBoxCell)p.dataGridView2[row.Cells[1].ColumnIndex, row.Cells[1].RowIndex];
   var result1 = context.GrupoDescricao.Select(GrupoDescricao => GrupoDescricao.Descricao).ToList();
   theCell1.Items.Clear();
   theCell1.Items.AddRange(result1.ToArray());
 }

And finally there is a text column for Remarks, totaling 6 columns.

Everything is working as it should, but now that I need to implement a new functionality, I need to change values in this DGV, add lines, remove lines and I’m not getting. When I change a value it goes back to the old value, I can change the color of the cell but the value inside does not, I believe it is directly associated with the data source, so just changing in the source, but I don’t know how I can add a row or remove within a query and in the position I need, as the user will select the row and I should remove or add a row below.

I’ve researched a lot and in most solutions people use Datatable, Bindingsource, and I didn’t want to change my DGV that is already all standardized the way I need, including with the Comboboxcell column and the querys inserted in each cell.

I’ve already tried:

DGV.add

DGV.Insert

DGV.Row[index]. Cell[index]. Value

all these common methods of adding lines, removing or changing value.

I thank you in advance for your help! I know it’s been extended and it’s still gonna be a lot of things missing, so I’m willing to bring you the information you need.

Hug.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.