gpt4 book ai didi

c# - WPF - 在数据网格上填充数据

转载 作者:行者123 更新时间:2023-12-02 12:38:14 33 4
gpt4 key购买 nike

我有以下代码,但我没有找到任何方法如何添加用户的数据到表。我想动态地做到这一点。

我已经创建了 WPF 应用程序并添加了数据网格和按钮,当我单击时在按钮上查看数据网格上的数据,我应该如何进行?

private void Button_Click(object sender, RoutedEventArgs e)
{
//get user data...
DataTable dt = new DataTable("Users Info");
DataGrid.ItemsSource = dt.DefaultView;

foreach (var user in users)
{
string firstName = user.Firstname;
string lastName = user.Lastname;
}

 

Xaml 是:

<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WPFTest01" x:Class="WPFTest01.MainWindow"
Title="WPF_DEMO_Main" Height="350" Width="525">

<Grid x:Name="Grid" Background="#FF1BA1E2">
<DataGrid x:Name="DataGrid" HorizontalAlignment="Left" Margin="65,60,0,0" VerticalAlignment="Top" Height="185" Width="385" SelectionChanged="DataGrid_SelectionChanged_1"/>
<Button Content="Button" HorizontalAlignment="Left" Margin="390,280,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click_1"/>

</Grid>
</Window>

我尝试了一些代码但没有成功:(

//dt.Columns.Add("First Name", typeof(string));
//dt.Columns.Add("Last Name", typeof(string));

//DataSet ds = new DataSet();

//ds.Tables.Add(dt);

最佳答案

用户(集合)指定为DataGrid的ItemsSource,以在datagrid上显示数据。

XAML

<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="500">
<StackPanel>
<Grid x:Name="Grid" Background="#FF1BA1E2">
<DataGrid x:Name="DataGrid" HorizontalAlignment="Left" Margin="65,10,0,0" VerticalAlignment="Top" Height="180" Width="385" SelectionChanged="DataGrid_SelectionChanged_1"/>
<Button Content="Button" HorizontalAlignment="Left" Margin="95,235,0,0" VerticalAlignment="Top" Width="75" Height="30" Click="Button_Click_1"/>
</Grid>
</StackPanel>
</Window>

隐藏代码

//Fill data here
private void Button_Click_1(object sender, RoutedEventArgs e)
{

ObservableCollection<User> users = new ObservableCollection<User>();
users.Add(new User{FirstName = "firstname-1",LastName = "lastname-1"});
users.Add(new User{FirstName = "firstname-2",LastName = "lastname-2"});
users.Add(new User{FirstName = "firstname-3",LastName = "lastname-3"});
users.Add(new User{FirstName = "firstname-4",LastName = "lastname-4"});
DataGrid.ItemsSource = users;
}

就是这样。

或者,您可以定义一个集合属性并将其绑定(bind)到 DataGrid,而不是从代码隐藏中设置 datagrid ItemsSource 属性。

关于c# - WPF - 在数据网格上填充数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20350886/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com