如何从列表中填充datagrid?

时间:2015-06-25 04:04:30

标签: c# mysql wpf xaml datagrid

Yo guyz,

我试图按树其他列表填充我的两个datagrids列。有人知道我该怎么做?我的解决方案从表中读取数据并通过for循环在消息框中显示。我不知道如何绑定列以在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");
        }
    }

和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>

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

首先,这不是一个公共属性,它是在那里的那个方法或构造函数中定义的:

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

将其公开并将其更改为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));

在构造函数或某处设置DataContext,并将NameTab设置为DataGrid的绑定源。

你应该为其他两个做同样的事情:NumerTab和IloscTab。

如果您不想使用该DependencyProperty,请尝试实现INPC接口:

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 { };
}

更新1:

DataGrid应如何工作的示例:

<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>

代码隐藏:

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;

    }
}

模特:

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 { };
}

结果:

enter image description here