如何在DataGrid中删除选定的列?(C#/ WPF)

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (81)

如何在DataGrid中删除选定的列(及其行)?

选择复选框和Excel记录:

CsvGrid.SelectAllCells();
foreach (var checkBox in CheckBoxes.Children.OfType<CheckBox>().Where(x => x.IsChecked == true))
{
    for(int i = 0; i < CsvGrid.SelectedCells.Count; i++)
    {
        if (checkBox.Tag != CsvGrid.Columns[i].Header) // How to remove this Column and its lines?
    }
}
ApplicationCommands.Copy.Execute(null, CsvGrid);
String result = (string) Clipboard.GetData(DataFormats.Text);
CsvGrid.UnselectAllCells();

SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.FileName = "Document";
saveFileDialog.DefaultExt = ".xls";
saveFileDialog.Filter = "Excel|*.xls|Excel 2010|*.xlsx|CSV files (*.csv)|*.CSV";
saveFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
if (saveFileDialog.ShowDialog() == true)
{
    File.WriteAllText(saveFileDialog.FileName, result.Replace(',', ' '));
    MessageBox.Show("File created!");
}

读取CSV表。使用LumenWorks写入DataTable

using LumenWorks.Framework.IO.Csv;

DataTable csvTable = new DataTable();
using (CsvReader csvReader = new CsvReader(new StreamReader(FilePath.Text), true))
{
    csvTable.Load(csvReader);

    for (int i = 0; i < csvTable.Columns.Count; i++)
    {
        csvTable.Columns[i].ColumnName = csvTable.Columns[i].ColumnName.Replace("_", " ");
    }

    CsvGrid.ItemsSource = csvTable.DefaultView;
}
提问于
用户回答回答于

您可以将可见性设置为折叠:

CsvGrid.Columns[i].Visibility = Visibility.Collapsed;

更改绑定源:

WPF:

<Grid>
    <DataGrid x:Name="TheGrid" ItemsSource="{Binding dataTable}">
        <DataGrid.Columns>
            <DataGridTemplateColumn Header="Delete">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <CheckBox Tag="2" Checked="Remove_me"></CheckBox>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
        </DataGrid.Columns>
    </DataGrid>
</Grid>

代码背后:

   DataTable dt1 = new DataTable();

   public MainWindow()
    {
        InitializeComponent();
        dt1 = new DataTable();

        dt1.Columns.Add("1");

        dt1.Columns.Add("2");

        dt1.Columns.Add("3");

        DataRow dr = dt1.NewRow();

        TheGrid.ItemsSource = dt1.DefaultView;
    }
    private void Remove_me(object sender, RoutedEventArgs e)
    {

        CheckBox checkbox = (CheckBox)sender;
        dt1.Columns.Remove(checkbox.Tag.ToString())

        TheGrid.ItemsSource = null;
        TheGrid.ItemsSource = dt1.DefaultView;

    }

扫码关注云+社区

领取腾讯云代金券