1
I have the following parameterization of my datagridview:
List<ModelAluno> alunos;
ModelAluno aluno = new ModelAluno();
public PesquisaAluno(List<ModelAluno> alunos)
{
InitializeComponent();
this.alunos = alunos;
}
private void PesquisaAluno_Load(object sender, EventArgs e)
{
ConfiguraDataGrid();
foreach (var aluno in alunos)
{
dg.Rows.Add(aluno.Nome, aluno.Cpf, aluno.Matricula.IdCurso);
}
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void ConfiguraDataGrid()
{
dg.Columns.Add("dg_Nome", "Nome");
dg.Columns.Add("dg_Cpf", "CPF");
dg.Columns.Add("dg_Curso", "Curso");
dg.ReadOnly = true;
dg.AllowUserToAddRows = false;
foreach (DataGridViewColumn column in dg.Columns)
{
if (column.DataPropertyName == "Nome")
column.Width = 300; //tamanho fixo da primeira coluna
column.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
}
In this case, I am receiving a list of students from another form and present in my datagridview only the fields I want (name, Cpf and idcurso).
In the Cellcontentclick method I need to return the selected student to my previous form, but I cannot return only these three fields, I need to return the mounted object (which is initially retrieved in a SQL Server query and is already stored in the received list in datagridview)
How do I return the entire object? Also, how do I, when pressing enter, I select the object I want and present in the textbox of the previous form?
Just don’t do:
dg.DataSource = alunos;
?– Rovann Linhalis
The datasource will fill in fields that I don’t want to present in datagridview, so I opted for manual column selection
– Lucas Bustos
define
dg.AutoGenerateColuns = false;
add the columns you want manually (as you already did) and just set theDataPropertyName
(as you have already done)– Rovann Linhalis
Right, and how can I recover the object mounted by datasource? It’s my first project with datagridview and I’m having some difficulty
– Lucas Bustos
could be something like
ModelAluno obj = alunos[dg.SelectedRows[0].Index];
but it also has other forms– Rovann Linhalis
I guess I didn’t quite understand... using the datasouce and the
dg.AutoGenerateColuns = false;
, datagridview shows the columns I parameterized, but no data inside. I could not set the value of these rows based onDataPropertyName
. How would that be?– Lucas Bustos
DataPropertyName
has to be equal to the name of the property (Name, Cpf, Matricula.Idcurso) etc... then just put the List as source– Rovann Linhalis
column.Datapropertyname = "Name"; column.Datapropertyname = "CPF"; column.Datapropertyname = "Stroke"; Would that be about right? Inside the foreach?
– Lucas Bustos