If the data has a type defined as shown in this example (Model), you can recover the items in various ways, see the example:
Note: if you do not have data type the last example is the most appropriate
Example:
Model:
public class Modelo
{
public int Id { get; set; }
public String Nome { get; set; }
}
Filling in:
GridDados.AutoGenerateColumns = true;
GridDados.ItemsSource = new List<Modelo>(){
new Modelo(){Id = 1, Nome = "Fulano 1"},
new Modelo(){Id = 2, Nome = "Fulano 2"},
};
Recovering
List<Modelo> modelos = GridDados.Items.OfType<Modelo>().ToList();
or
foreach (Modelo modelo in GridDados.Items.OfType<Modelo>().ToList())
{
int id = modelo.Id;
String nome = modelo.Nome;
}
or
If the data is an anonymous type:
GridDados.ItemsSource = new object[]{
new {Id = 1, Nome = "Fulano 1"},
new {Id = 2, Nome = "Fulano 2"},
}.ToArray();
foreach (dynamic item in GridDados.Items)
{
int id = item.Id;
String nome = item.Nome;
}
Debugging to find the item:
The dynamic
in this specific case will assume at runtime the type that each item in the list. Like this Collection
has a type of class Modelo
the variable item
assumed that guy. That is, "The Dynamic type is a static type that is defined by the Dynamic reserved word and the variable of this type can be ALL in principle, and at compile time the Dynamic type assumes any operation." (Marcorrati.Net, C# - The data type Dynamic, 2014. Available at: http://www.macoratti.net/11/02/c_din1.htm. Date Accessed: 26.Jun.2014)
or
With Datarowview:
foreach (DataRowView item in GridDados.Items.OfType<DataRowView>().ToArray())
{
string CDESC_INEP = item["CDESC_INEP"].ToString();
}
References:
Why not query the data directly? The grid is UI and should only be used by the user and not by application logic.
– Paulo Morgado
Translate at intern level (laughs) and put as a response, I’m grateful.
– Caique C.
What you’re doing is the equivalent of printing the data on paper and then doing OCR to process the data. You must process the data directly from the data source. Same as you assigned to the grid.
– Paulo Morgado
Oh yes, I get it, I also think it’s unnecessary to play on the grid, it’s just one more process, but I was asked so...
– Caique C.
And the reason I’m taking data from the grid is learning, I don’t do grids, I need to learn to manipulate a little...
– Caique C.