Building Datagrid with C# WPF at runtime

Asked

Viewed 751 times

0

I have a Datatable where I will store some data that the user informs and through it I want to pass the information to Datagrid.

gvDados.ItemsSource = dt.DefaultView; //Essa é a ligação entre o DataTable e a Grid

In case the user informs the column name and clicks the button Addircoluna, which has the following code:

private void btnAddColuna_Click(object sender, RoutedEventArgs e)
{  
    bool valida = true;
    int nroColunas = dt.Columns.Count;

    for (int i = 0; i < nroColunas; i++) 
    {
        if (dt.Columns[i].ToString().ToUpperInvariant().Equals(ttbColuna.Text.ToUpperInvariant()))
            valida = false;
    }

    if (valida)
    {
        // gvDados.Columns.Clear();
        DataGridTextColumn c = new DataGridTextColumn();
        c.Header = ttbColuna.Text;

        gvDados.Columns.Add(c);

        cbbColunas.Items.Add(ttbColuna.Text);

        dt.Columns.Add(ttbColuna.Text, typeof(string));
        ttbColuna.Text = "";
    }
    else
        MessageBox.Show("Já existe uma coluna com esse nome","Sistema Comercial |B ",MessageBoxButton.OK,MessageBoxImage.Error);    
}

With this method it generates the columns, which I want and adds the column in Datatable and Datagrid, it is correct to do this?

Because if I just put it on Datatable it is not visualized on Datagrid

Until then everything is ok, but when I add a line in Datatable so that it can appear in Datagrid does not work, a line appears but blank without the data ...

Let’s say the user added two columns, Size and Color so my Datatable would have to receive

dt.Rows.Add(ttbTamanho.Text, ttbCor.Text);

The information is in the Datatable, but is not shown in the Datagrid.

Is there any way to put the information in the Datagrid without using the Datatable or any method that makes the information appear, taking into account that columns and rows are added at runtime

1 answer

2


What you are asking for may be a bit complex. I will give you some guides and tips that can make your life easier.

Is there any way to put the information in Datagrid without using Datatable?

Yes, any object that implements IEnumerable can be the data source. For example: List<Produto> or ICollection<Categoria>, including a List<dynamic> are valid sources.

Autogeneratecolumns

The estate AutoGenerateColumns defined as true will generate columns automatically after you have the data source set. If your data source is a List<Pessoa>, and the Pessoa has the attributes Nome, Telefone and Cidade, three columns will be generated automatically.

Canuseraddrows

With that property true, if you defined the data source as an object of type List<Pessoa>, the lines inserted in DataGrid will be reflected in the collection (object). Note that in this approach, if you add an item to the collection via application(code), this line will not be reflected in DataGrid.

 <DataGrid x:Name="DataGrid1" AutoGenerateColumns="True" CanUserAddRows="True" />

Code-Behind

private List<Pessoa> pessoas;
public MainWindow()
{
    InitializeComponent();
    pessoas = new List<Pessoa>();
    DataGrid1.ItemsSource = pessoas;
 }

or

    var listaDinamica = new List<dynamic>
    {
        new { Nome = "José", CPF = "000.000.00-00"},
        new { Nome = "Pedro", CPF = "111.111.11-11"}
    };

    DataGrid1.ItemsSource = listaDinamica;

Observablecollection

I believe this is the best kind of collection to work with Datagrid in WPF. It works like this:

    private ObservableCollection<Pessoa> pessoas;
    public MainWindow()
    {
        InitializeComponent();
        pessoas = new ObservableCollection<Pessoa>();
        DataGrid1.ItemsSource = pessoas;
     }

Using ObservableCollection, if you add a person to the list via code, it will reflect on the DataGrid. If the user adds a line to DataGrid, will reflect on the object pessoas

https://msdn.microsoft.com/pt-br/library/ms668604(v=vs.110). aspx

  • Thank you your reply was very helpful and managed to help me! if I could also help with that thank you: http://answall.com/questions/183435/defini%C3%A7%C3%A3o-de-row-header-de-um-datagrid-atrav%C3%A9s-das-linhas-de-uma-coluna-de-um-da

Browser other questions tagged

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