List directory files in a DataGrid

后端 未结 5 1871
悲哀的现实
悲哀的现实 2021-01-22 00:10

I have searched many topics and can\'t find an answer on using the WPF DataGrid to list file name contents from a directory. I am able to output the contents in a <

相关标签:
5条回答
  • 2021-01-22 00:53
    string [] fileEntries = Directory.GetFiles(targetDirectory);
    
    List<FileInfo> fileList = new List<FileInfo>();
    
    foreach (string file in fileEntries)
    {
    
    fileList.Add(new FileInfo(file));
    }
    
    datagrid.ItemsSource = fileList;
    
    0 讨论(0)
  • 2021-01-22 00:57

    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>
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2021-01-22 01:01

    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.

    0 讨论(0)
  • 2021-01-22 01:15

    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.

    0 讨论(0)
提交回复
热议问题