Building DataGrid with C # WPF at runtime

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 the 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 AddColumn button, it 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 the DataTable and in the DataGrid, is it correct to do this?

Because if I put only the DataTable is not seen in the DataGrid

Let's say that the user added two columns, Size and Color so my DataTable would have to receive

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

The information stays in the DataTable but is not displayed in the DataGrid.

Is there any way to put the information in the DataGrid without using the DataTable or some method that causes the information to appear, taking into account that columns and rows are added at runtime

    
asked by anonymous 09.02.2017 / 17:20

1 answer

2

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

  

Is there any way to put the information in the DataGrid without using the DataTable?

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

AutoGenerateColumns

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

CanUserAddRows

With this true property, if you defined the data source as an object of type List<Pessoa> , the lines entered in DataGrid will be reflected in the collection (object). Note that in this approach, if you add an item in the collection via the application (code), that 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 think this is the best collection type for working 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 DataGrid . If the user adds a line in DataGrid , it will reflect on object pessoas

link

    
09.02.2017 / 20:28