简体   繁体   中英

Binding Datagrid first column into a list using WPF

I have two columns Path and Filename as datagrid1, I want to bind the path column into a list<> so that I can copy all the files to a different location by clicking one button. can some one help me please? looking for c# wpf code.

Path            FileName
C:\Temp\abc.txt abc.txt
C:\Temp\xyz.txt xyz.txt
C:\Temp\a.txt   a.txt

The Code

XAML

<DataGrid AutoGenerateColumns="False" Height="193" HorizontalAlignment="Left"
          Margin="169,6,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="200"              
          ItemsSource="{Binding}">
          <DataGrid.Columns>
              <DataGridTextColumn Header="Path" Binding="{Binding Path}" />
              <DataGridTextColumn Header="FileName" Binding="{Binding FileName}" />
          </DataGrid.Columns>
</DataGrid>

Behind

public class ReportFiles
    {
        public string Path { get; set; }
        public string FileName { get; set; }
    }

What basically I am doing is to collect the files from local drives and copy them all to C:\\ReportFiles. I have created two buttons. Attach and Save. Attach will browse and get the files. In dataGrid1, I am taking the old path and filename. When finish collecting all the files. Click on save button. This will take Path column from datagrid and start coping file from datagrid Path column to C:\\ReportFiles. The loop will do this job.

The problem is the list, I cant make datagrid column as list of collection. Hope this clears.

DataGrid code:

<DataGrid AutoGenerateColumns="False" Height="193" HorizontalAlignment="Left" Margin="169,6,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="200" ItemsSource="{Binding ReportFiles}">
                <DataGrid.Columns>
                    <DataGridTextColumn Header="Path" Binding="{Binding Path}" />
                    <DataGridTextColumn Header="FileName" Binding="{Binding FileName}" />
                </DataGrid.Columns>
            </DataGrid>

MainWindow.cs:

public partial class EditReport : Window
{
        public List<ReportFiles> listabove = new List<ReportFiles>();

 public class ReportFiles
    {
        public string RealName { get; set; }
        public string TargetName { get; set; }
    }

    private void buttonAttach_Click(object sender, RoutedEventArgs e)
        {
        Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
              if (dlg.ShowDialog() == true)
        {
foreach (string str in dlg.FileNames)
                     {
                     ReportFiles list = new ReportFiles();
                     list.RealName = str;
                     list.TargetName = filename;
                     dataGrid1.Items.Add(new { RealName = list.RealName, TargetName = list.TargetName });
            string fileName = @"C:\Temp\" + filename + System.IO.Path.GetExtension(str).Trim(); ;
                    if (File.Exists(fileName))
                    continue;
                    else
                        {
                        try
                        {
                             File.Copy(str, fileName);
                        }
                        catch (Exception err)
                             {
                             MessageBox.Show(err.Message);
                             return;
                             }
                        }
            }
        }
}

private void btnSave_Click(object sender, RoutedEventArgs e)
       {
            ReportFiles rep = new ReportFiles();
            DataRowView paths = (System.Data.DataRowView)dataGrid1.Items[0];
            rep.RealName = Convert.ToString(paths.Row.ItemArray[0]);

       }
}

I looked through your code and it doesnt look really well-structured,
as well it wasn't working especially that "buttonAttach_Click()" function.

There are different things to mention here.

  1. Rename Class ReportFiles to ReportFile as it only describes "one" File, not a bunch of them.

  2. Propertys of ReportFiles weren't named properly.
    RealName , TargetName are not really self-explanatory, so i changed them to Path , FileName

  3. You were adding the Items as an Anonymous Object to the DataGrid with the following call:

    dataGrid1.Items.Add(new { RealName = list.RealName, TargetName = list.TargetName});

    It's much cleaner and easier to work with later, if you add the object itself.
    Especially because you already created that in the lines before.
    So i changed it to:

    ReportFile reportFile = new ReportFile();
    reportFile.Path = str;
    reportFile.FileName = System.IO.Path.GetFileName(str);
    dataGrid1.Items.Add(reportFile);

  4. I did not understand what you did in the btnSave_Click function. But i assume, that you want to copy the existing files you selected before, to the C:\\Temp\\ Directory, so i changed that too.
    As you see now, you can simple foreach over the DataGrid.Items and do with them what you like.


So it comes down to a really simple solution:

public class ReportFile
{
  public string Path { get; set; }
  public string FileName { get; set; }
}

private void buttonAttach_Click(object sender, RoutedEventArgs e)
{
  Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
  if (dlg.ShowDialog() == true)
  {
    foreach (string str in dlg.FileNames)
    {
      ReportFile reportFile = new ReportFile();
      reportFile.Path = str;
      reportFile.FileName = System.IO.Path.GetFileName(str);
      dataGrid1.Items.Add(reportFile);
    }
  }
}

private void btnSave_Click(object sender, RoutedEventArgs e)
{
  foreach (ReportFile reportFile in dataGrid1.Items)
  {
    string fileName = @"C:\Temp\" + reportFile.FileName;
    if (File.Exists(fileName))
      continue;
    else
    {
      try
      {
        File.Copy(reportFile.Path, fileName);
      }
      catch (Exception err)
      {
        MessageBox.Show(err.Message);
        return;
      }
    }
  }
}




@ Any of the mods, please delete the first Answer, as it doesnt count anymore

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM