简体   繁体   中英

Do to add columns and rows to datagrid?

I am creating a datagrid for my window and trying to add columns to it and then add rows containing data to it. Do you know what I am doing wrong. I know it is something small and simple that I do not understand. Can someone help me? Thanks! I get a stackoverflow exception now.

 public partial class Window5 : Window
{
    item items = new item();




    public Window5()
    {

        InitializeComponent();


    }



    private void Window_Loaded(object sender, RoutedEventArgs e)
    {


        DataGridTextColumn FirstName = new DataGridTextColumn();
        FirstName.Header = "First Name";
        FirstName.Binding = new Binding("FirstName");
        Datagrid.Columns.Add(FirstName);

        DataGridTextColumn LastName = new DataGridTextColumn();
        LastName.Header = "Last Name";
        LastName.Binding = new Binding("LastName");
        Datagrid.Columns.Add(LastName);

        DataGridTextColumn Department = new DataGridTextColumn();
        Department.Header = "Department";
        Department.Binding = new Binding("Department");
        Datagrid.Columns.Add(Department);

        DataGridTextColumn Time = new DataGridTextColumn();
        Time.Header = "Time";
        Time.Binding = new Binding("Time");
        Datagrid.Columns.Add(Time);

        Datagrid.Items.Add(new item() { FirstName = "Joey", LastName = "Chang", Department = "Education" });



    } 

    private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
    {

    } 
}
public partial class item 
{
    public string FirstName {get; set;}
    public string LastName { get; set; }
    public string Department { get; set; }


}

}

Windows5.xaml :

<Window x:Class="WpfApp2.Window5"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp2"
        mc:Ignorable="d"
        Title="Window5" Height="450" Width="800" Loaded="Window_Loaded" Closing="Window_Closing">
    <DataGrid x:Name="Datagrid" HorizontalAlignment="Left" Height="422" Margin="0,0,0,-3" VerticalAlignment="Top" Width="790"/>
</Window>

Take GenerateItems method out of item class and put it in window5 class. Then call the method

Your item class might be referencing a different DataGrid.

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