I need to set a table from a database to be the DataSource of a GridGrid in WPF. In Windows Forms the property is called DataSource
but in WPF no such property exists, so how can i do it?
You can use the ItemsSource
property :
<ListView ItemsSource="{Binding YourData}">
<ListView.View>
<GridView>
<!-- The columns here -->
</GridView>
</ListView.View>
</ListView>
If you prefer to use code-behind rather than a binding, just give a name to the ListView
and set the ItemsSource
property in code:
listView1.ItemsSource = YourData;
You can also use the ItemsSource
property with other list controls (DataGrid
, ListBox
, ComboBox
, etc), since it is defined in the ItemsControl
base class.
EDIT: if the data source is a DataTable
, you can't assign it directly to ItemsSource
because it doesn't implement IEnumerable
, but you can do it through a binding:
listView1.SetBinding(ItemsControl.ItemsSourceProperty, new Binding { Source = YourData });
This is simple an example:
XAML part :
<DataGrid Name="dataGrid1" Width="866" Height="auto" HorizontalAlignment="Left" VerticalAlignment="Top" />
C# part :
... [code to read and fill your table ] ...
da.Fill(myDataTable);
dataGrid1.ItemsSource = myDataTable.DefaultView;
And now your DataGrid will be filled with your DataTable
The GridView
is a view and not a standalone control as far as i know, you would normally use it as the view of a ListView
. In WPF the property for data population is called ItemsSource
, you probably want to either use a ListView
or DataGrid
to display your data that way.
You can use below both ways to bind the datatable to datagrid in WPF.
datagrid.ItemSource = mydt.DefaultView();
datagrid.DataContext = mydt.DefaultView();
I have this code, its work load from csv
in .xaml
<DataGrid x:Name="dataGridView1"
ItemsSource="{Binding Source=ClusterList}"
AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="ClusterNumber" Binding="{Binding ClusterNumber}"/>
<DataGridTextColumn Header="ServerName" Binding="{Binding ServerName}"/>
/>
</DataGrid.Columns>
</DataGrid>
then I have c#
code of view
public DiscoveryView()
{
InitializeComponent();
ClusterList = new ObservableCollection<ClusterData>();
LoadDataFromCsv();
dataGridView1.ItemsSource = ClusterList;}
public class ClusterData
{
public string ClusterNumber { get; set; }
public string ServerName { get; set; }
}
public ObservableCollection<ClusterData> ClusterList { get; set; }
private void LoadDataFromCsv()
{
using (var reader = new StreamReader("./Configs/clusterlist.csv"))
{
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(',');
ClusterList.Add(new ClusterData
{
ClusterNumber = values[0],
ServerName = values[1]
});
}
}
}
maybe this code is for beginners, but it works for me
© 2022 - 2025 — McMap. All rights reserved.