简体   繁体   中英

How to fill datagrid from list?

Yo guyz,

I'm trying to fill my two datagrids columns by tree other list. Is somebody know how can I do this? My solution read the data from table and show it in message boxes by for loop. I don't know how to bind columns to showing this information in datagrid.

public void WybierzDoRaportu()
    {
        List<string> NameTab = new List<string>();
        List<string> NumerTab = new List<string>();
        List<string> IloscTab = new List<string>();

        DataTable dt = new DataTable();
        DataSet ds = new DataSet();
        MySqlCommand cmd = new MySqlCommand(" SELECT c.nazwa, c.symbol, z.id_czesci_symbol, z.ilosc, z.z_numer_naprawy FROM `sylpo_test`.`zamowienie` AS z LEFT JOIN `test`.`czesc` AS c ON c.symbol=z.id_czesci_symbol WHERE z.z_numer_naprawy='" + numberBox.Content.ToString() + "' ORDER BY ilosc;", connection);
        MySqlDataAdapter adp = new MySqlDataAdapter(cmd);
        try
        {            
            connection.Open();

            using (MySqlDataReader dr = cmd.ExecuteReader())   //do a query
            {
                dt.Load(dr);
            }
            adp.Fill(ds, "LoadDataBinding");
        }
        catch (MySqlException ex)
        {
            MessageBox.Show(ex.ToString());
        }
        finally
        {
            connection.Close();
        }

        foreach (DataRow dRow in dt.Rows)
        {
            NameTab.Add(dRow[0].ToString());
            NumerTab.Add(dRow[2].ToString());
            IloscTab.Add(dRow[3].ToString());          
        }

        for (int i = 0; i <= dt.Rows.Count - 6; i++)
        {
            czesciTable.ItemsSource = NameTab; // not working :/
            MessageBox.Show(NameTab.ElementAt(i) + " " + NumerTab.ElementAt(i) + " " + IloscTab.ElementAt(i));
        }


        for (int i = 5; i <= dt.Rows.Count - 1; i++)
        {
            MessageBox.Show(NameTab.ElementAt(i) + " " + NumerTab.ElementAt(i) + " " + IloscTab.ElementAt(i)+" druga tura");
        }
    }

And XAML

<DataGrid x:Name="czesciTable" ItemsSource="{Binding}" AutoGenerateColumns="False" CanUserAddRows="False" HorizontalAlignment="Right" Margin="0,207,175,0" VerticalAlignment="Top" Width="183" Height="66" FontSize="5" FontWeight="Bold" BorderBrush="Black" Background="White" HeadersVisibility="Column" CanUserReorderColumns="False" CanUserSortColumns="False" ScrollViewer.CanContentScroll="False" VerticalScrollBarVisibility="Disabled">
            <DataGrid.Columns>
                <DataGridTextColumn Binding="{Binding Path=NazwaTab}" Header="NAZWA" Width="70"
                            IsReadOnly="True" CanUserResize="False" />
                <DataGridTextColumn Binding="{Binding Path=NumerTab}" Header="KOD" Width="60"
                            IsReadOnly="True" CanUserResize="False" />
                <DataGridTextColumn Binding="{Binding Path=IloscTab}" Header="ILOŚĆ (w szt.)" Width="51"
                            IsReadOnly="True" CanUserResize="False" />
            </DataGrid.Columns>
        </DataGrid>

Thanks for your help.

First of all, this is not a public property, it's defined inside that method or constructor you have there :

List<string> NameTab = new List<string>();

Make it public and change it to an ObservableCollection<string> .

     public ObservableCollection<string> NameTab
    {
        get { return (ObservableCollection<string>)GetValue(NameTabProperty); }
        set { SetValue(NameTabProperty, value); }
    }

    // Using a DependencyProperty as the backing store for NameTab.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty NameTabProperty =
        DependencyProperty.Register("NameTab", typeof(ObservableCollection<string>), typeof(MainWindow), new PropertyMetadata(null));

set your DataContext in the constructor or somewhere and set NameTab as the binding source for your DataGrid .

You should do the same thing for the others two : NumerTab and IloscTab .

If you don't want to use that DependencyProperty, try to implement INPC interface:

public class ItemContainer : INotifyPropertyChanged
{
    private ObservableCollection<string> _NameTab;

    public ObservableCollection<string> NameTab
    {
        get { return _NameTab; }
        set
        {
            _NameTab = value;
            PropertyChanged(this, new PropertyChangedEventArgs("NameTab"));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged = delegate { };
}

Update 1:

An example of how the DataGrid should work:

<Window x:Class="DataGridExample.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <DataGrid x:Name="czesciTable" ItemsSource="{Binding NameTab}" 
              AutoGenerateColumns="False"
              CanUserAddRows="False" 
              VerticalAlignment="Top"  
              FontSize="12" 
              FontWeight="Bold" 
              BorderBrush="Black" 
              Background="White" 
              HeadersVisibility="Column" 
              CanUserReorderColumns="False"
              CanUserSortColumns="False"
              ScrollViewer.CanContentScroll="False" 
              VerticalScrollBarVisibility="Disabled">
        <DataGrid.Columns>
            <DataGridTextColumn Binding="{Binding Path=id_czesci_symbol}" Header="ID" Width="51"
                        IsReadOnly="True" CanUserResize="False" />
            <DataGridTextColumn Binding="{Binding Path=Nazwa}" Header="NAZWA" Width="70"
                        IsReadOnly="True" CanUserResize="False" />
            <DataGridTextColumn Binding="{Binding Path=Symbol}" Header="Symbol" Width="60"
                        IsReadOnly="True" CanUserResize="False" />
        </DataGrid.Columns>
    </DataGrid>
</Grid>

Codebehind:

public partial class MainWindow : Window
{
    public ObservableCollection<Model> NameTab { get; set; }

    public MainWindow()
    {
        InitializeComponent();
        NameTab = new ObservableCollection<Model>();
        NameTab.Add(new Model() { id_czesci_symbol = 1, Nazwa = "Nazwa1", Symbol = "Symbol1" });
        NameTab.Add(new Model() { id_czesci_symbol = 2, Nazwa = "Nazwa2", Symbol = "Symbol2" });
        NameTab.Add(new Model() { id_czesci_symbol = 3, Nazwa = "Nazwa3", Symbol = "Symbol3" });
        this.DataContext = this;

    }
}

And the model:

public class Model : INotifyPropertyChanged
{

    private string _Nazwa;

    public string Nazwa
    {
        get { return _Nazwa; }
        set
        {
            _Nazwa = value;
            PropertyChanged(this, new PropertyChangedEventArgs("Nazwa"));
        }
    }

    private string _Symbol;

    public string Symbol
    {
        get { return _Symbol; }
        set
        {
            _Symbol = value;
            PropertyChanged(this, new PropertyChangedEventArgs("Symbol"));
        }
    }

    private int _id_czesci_symbol;

    public int id_czesci_symbol
    {
        get { return _id_czesci_symbol; }
        set
        {
            _id_czesci_symbol = value;
            PropertyChanged(this, new PropertyChangedEventArgs("id_czesci_symbol"));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged = delegate { };
}

Result:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM