开发者

Displaying dynamic columns in a listbox

开发者 https://www.devze.com 2023-04-01 22:05 出处:网络
I want to write an application that will display data from a CSV file. I th开发者_如何学Goought it would be easiest to use a listbox to do this.

I want to write an application that will display data from a CSV file.

I th开发者_如何学Goought it would be easiest to use a listbox to do this.

I'm just not sure how to define the data template in order to accommodate as many columns as the csv wishes to define. Is there a way to define the number of columns in, say, a grid based on maybe the item count in a list?


Use a ListView rather than a ListBox, then you can use a GridView for the columns, or you could use a DataGrid which additionally can create columns automatically based on the data it gets, this requires properties though, which are not as nice to create on the fly.

I would suggest you parse the data into array objects and you create the columns by iterating over its length. Adding bindings like this: new Binding("[" + i + "]").

Here's a rough outline:

<ListView Name="csvLv"/>
var view = new GridView();
csvLv.View = view;
using (var reader = new StreamReader(@"PathGoesHere.csv"))
{
    //This is just a sketch and all the data extraction depends on your format
    var lines = reader.ReadToEnd()
        .Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)
        .Select(x => x.Split(',')).ToArray();
    var headers = lines[0];
    var data = lines.Skip(1);
    for (int i = 0; i < headers.Length; i++)
    {
        view.Columns.Add(new GridViewColumn()
        { 
            Header= headers[i],
            DisplayMemberBinding = new Binding("[" + i + "]")
        });
    }
    csvLv.ItemsSource = data;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消