Error entering data in datagridview

Asked

Viewed 276 times

0

I have the following code:

public partial class PesquisaAluno : Form
{
    List<ModelAluno> alunos;

    public PesquisaAluno(List<ModelAluno> alunos)
    {
        InitializeComponent();
        this.alunos = alunos;
    }

    private void PesquisaAluno_Load(object sender, EventArgs e)
    {
        dg.DataSource = alunos;

        foreach (var aluno in alunos)
        {
            dg.Rows.Add(aluno.Nome, aluno.Cpf, aluno.Matricula.IdCurso);
        }

    }

This code is called when the query in the previous form returns more than 1 item. These results are stored in the student list and passed to the datagrid form. However, when the form tries to load, it returns the following error:

System.Invalidoperationexception: 'It is not possible to add lines programmatically to the collection of Datagridview lines when the control is associated with data.'

How to resolve this error?

  • This is because, in the line immediately above, you define a Datasource for the Grid. By the way, why are you changing the Datasource and at the same time trying to add lines in the Grid? Just changing the Datasource is enough.

  • In this case, as I am starting in programming, this is my first project with datagridview. When I recover the data only by datasource, I see that the grid presents me columns that I do not want. Knowing that I defined 3 columns visually in datagridview, how do I populate them?

No answers

Browser other questions tagged

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