List directory files in a DataGrid

两盒软妹~` 提交于 2019-12-01 22:45:55

You can create DataGrid with one column:

<DataGrid x:Name="myDataGrid" AutoGenerateColumns="False">
    <DataGrid.Columns>
        <DataGridTextColumn IsReadOnly="True" Binding="{Binding}" Header="Name"/>
    </DataGrid.Columns>
</DataGrid>

and fill it in your code like this:

myDataGrid.ItemsSource = new DirectoryInfo(path).GetFiles();

By setting ItemsSource to FileInfo[] you have option to create other columns bound to other properties for FileInfo class. This DataGrid will work with any IEnumerable assigned to ItemsSource. If it won't be a string already then ToString() will be called

You first have to add Columns in your DataGrid (using VS is pretty simple with the designer) and then you can use something like:

for (int i = 0; i < Object.Length; i++)
    dataGrid.Rows[i].Cells[0].Value = Object[i];

In this case i'm using Cells[0], but you can specify any cell on your row to put the values.

You should be able to bind your listbox to the DataGrid something like:

<Window x:Class="Bind02.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Bind02" Height="300" Width="300"
>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="Auto"/>
        </Grid.ColumnDefinitions>
        <ListBox Name="listBox" ItemsSource="{Binding}"/>
        <StackPanel Grid.Column="1">
            <Button Click="OnLoad">_Load</Button>
            <Button Click="OnSave">_Save</Button>
            <Button Click="OnAdd">_Add</Button>
            <Button Click="OnEdit">_Edit</Button>
            <Button Click="OnDelete">_Delete</Button>
            <Button Click="OnExit">E_xit</Button>
        </StackPanel>
    </Grid>
</Window>

Instead of:

object[] AllFiles = new DirectoryInfo(path).GetFiles().ToArray();

use

List<string> AllFiles = new DirectoryInfo(path).GetFiles().ToList();
MyDataGrid.ItemSource = Allfiles;

This will automatically bind the files to the DataGrid.

Raj
string [] fileEntries = Directory.GetFiles(targetDirectory);

List<FileInfo> fileList = new List<FileInfo>();

foreach (string file in fileEntries)
{

fileList.Add(new FileInfo(file));
}

datagrid.ItemsSource = fileList;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!