Home>

I want to get the CSV data and execute the work, but I want to execute it after checking only the columns that have the title, price, and image URL data once.
Therefore, I want to use DataGrid to display only the specified columns.
I implemented the following code in the button, but I do not understand after this.

Development environment
Visual Studio 2019 version 16.5.4
.NET Framework Version 4.8.03752
is.

CSV image

title price Explanation Year of issue image
Title 1 Price 1 Explanation 1 Publication year 1 Image 1
Title 2 Price 2 Explanation 1 Publication year 2 Image 2

.
.
.

↓ (I want to display only the columns marked with * in the DataGrid)

title※ price※ Explanation Year of issue image※
Title 1 * Price 1 * Explanation 1 Publication year 1 Image 1 *
Title 2 * Price 2 * Explanation 1 Publication year 2 Image 2 *

.
.
.

private void OpenFileDialogforCsv_Click (object sender, RoutedEventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog ();
            if (ofd.ShowDialog () == true)
            {
                string content = File.ReadAllText (ofd.FileName, Encoding.GetEncoding ("Shift_JIS"));
                DataTable dt = GetCsvDataTable (content);
                this.dataGrid.ItemsSource = dt.DefaultView;
            }
        }
        private DataTable GetCsvDataTable (string content) {}


xaml looks like this.

<StackPanel>
<Button Content = "Reference"
     Height = "40" Width = "100" Margin = "10"
     FontSize = "20" FontWeight = "Bold" Background = "SkyBlue" />
<DataGrid Grid.Row = "1" Name = "dataGrid" Height = "500" />
<Button Content = "Work execution"
    Height = "50" Width = "200" Margin = "25" Background = "Orange"
      FontSize = "25" FontWeight = "Bold" />
</StackPanel>
  • Answer # 1

    DataGridIs an example that corresponds.

    If the columns to be displayed or hidden are fixed, it is quick to specify the columns with xaml.

    <DataGrid
      Name = "dataGrid"
      Height = "500"
      AutoGenerateColumns = "False">
      <DataGrid.Columns>
        <DataGridTextColumn Binding = "{Binding [0]}" Header = "Title" />
        <DataGridTextColumn Binding = "{Binding [1]}" Header = "Price" />
        <DataGridTextColumn Binding = "{Binding [4]}" Header = "Image" />
      </DataGrid.Columns>
    </DataGrid>

    If you want to switch between display and non-display, it is more convenient to change it from the code.

    InitializeComponent ();
    dataGrid.AutoGeneratedColumns + = (s, e) =>
    {
        dataGrid.Columns [2] .Visibility = Visibility.Hidden;
        dataGrid.Columns [3] .Visibility = Visibility.Hidden;
    };


    DataGrid.AutoGeneratingColumn Event (System.Windows.Controls) | Microsoft Docs
    You can use this one.


    I will omit "datatable column deletion" because it is more complicated.

    As for "wpf datagrid column hidden", there are some elaborate bindings, but simple ones are surprising.

Related articles