【问题标题】:How to remove row from datagrid and an array如何从数据网格和数组中删除行
【发布时间】:2018-10-15 13:42:40
【问题描述】:

我在 WPF 应用程序中的数据网格。显示 csv 文件。我想将 csv 文件复制到数组中。从数组中删除一个字符串,该字符串与数据网格中的选定行相同(比较索引)。最后,我在第二个数据网格中显示字符串数组。

//Storing csv file in string array
var filePath = "csvFile.csv";
using (StreamReader file = new StreamReader(filePath))
{
    while (!file.EndOfStream)
    {
        int selectedIndex =int.Parse(dgData.SelectedIndex.ToString());
        string strResult = file.ReadToEnd();
        string[] result = strResult.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
        List<string> list = new List<string>(result);
        list.RemoveAt(selectedIndex);
        foreach (string item in list)
        {
            Console.WriteLine(item);
            Console.ReadLine();
        }
        dgtest.ItemsSource = list;
    } 
    file.Close();
}

我会很高兴更正我的代码。目前我有一个错误说明:

索引超出范围。

【问题讨论】:

    标签: arrays wpf csv datagrid


    【解决方案1】:

    你把事情复杂化了。试试这样的:

    const string FilePath = "csvFile.csv";
    List<string> lines = File.ReadAllLines(FilePath)?.ToList();
    int selectedIndex = dgData.SelectedIndex;
    if (lines != null && selectedIndex > 0 && lines.Count > selectedIndex)
        lines.RemoveAt(selectedIndex);
    dgtest.ItemsSource = lines;
    

    【讨论】:

    • 谢谢@mm8。但我仍然遇到同样的错误:ArgumentOutOfRangeException.Index was out of range.
    • 一旦我选择了数据网格行并按下“删除”按钮(在这种情况下我放置了您的代码),我就会收到此错误。如何检查数据网格中所选行的值是多少?
    • 我发现了问题:在您的代码之前,我有一个代码可以从数据网格本身中删除选定的行,因此选定索引的值是'-1'。我移动了这两个代码,它现在可以工作了。除了作为 dgtest 的结果,我得到一个长度列表(整数)。
    • csv文件主要包含一个带有文本字符串的列。该csv文件被转换为列表。
    • @Aga:然后你需要决定显示哪些列并创建这样一个数据对象。但是,如果您有其他问题,请提出一个新问题。这个问题是关于如何删除一行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-06
    • 2015-10-30
    • 2012-12-11
    • 1970-01-01
    • 1970-01-01
    • 2017-12-05
    • 2021-03-27
    相关资源
    最近更新 更多