I would like to load some data from external various source such as text file, csv file, user input, etc, and display in a list view using C# WPF. I need to display one source at a time only, and the number of columns is fixed within one source, but different sources may contain different number of columns, eg,
File1 may have following column: Name, Number, Cat1, Cat2, Cat3
File2 may have following column: Name, Number, CatA, CatB
File3 may have following column: Name, Index, Type1, ..., TypeN
...
Seems that the listview in C# WPF can only be used with a known number of columns, is it possible to use listview which the number of columns is only known in the RUNTIME, similar to the above data? or I should use a different approach, I have no idea yet. Thanks.
To convert csv to table (just an example, there are libraries out there that do this job better):
public static class ExtensionMethods
{
public static DataTable ConvertToDataTable(this string input)
{
DataTable result = new DataTable();
using (StringReader reader = new StringReader(input))
{
string[] columnNames = reader.ReadLine().Split(';'); //or other character
foreach (var columnName in columnNames)
{
result.Columns.Add(columnName, typeof(string));
}
while (reader.Peek() > 0)
{
result.Rows.Add(reader.ReadLine().Split(';'));
}
}
return result;
}
}
Example of the UI:
<Window x:Class="WpfApplication2.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>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition/>
</Grid.RowDefinitions>
<Button Name="btnLoad" Content="Load" Click="BtnLoad_OnClick"/>
<DataGrid Name="dgData" Grid.Row="1" ItemsSource="{Binding}"/>
</Grid>
</Window>
and the proper code behind:
public partial class MainWindow : Window
{
private DataTable table;
public MainWindow()
{
InitializeComponent();
}
private void BtnLoad_OnClick(object senderIn, RoutedEventArgs eIn)
{
OpenFileDialog dialog = new OpenFileDialog();
if (dialog.ShowDialog() == true)
{
string content = File.ReadAllText(dialog.FileName);
table = content.ConvertToDataTable();
dgData.DataContext = table;
}
}
}
Tested with data:
Name;Number;Cat1;Cat2;Cat3
someName;someNumber;someCat1;someCat2;someCat3
someOtherName;someOtherNumber;someOtherCat1;someOtherCat2;someOtherCat3
And looks like:
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.