首页 > 解决方案 > C#输入数组长于使用removeAt后的列数

问题描述

我很清楚,在尝试合并 ZRP 和 08-0729-01-MAR 时,从数据表中显式删除一列后会导致此问题,因此无论如何要删除该列而不会出现异常?请帮忙

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    { 
        DataTable dt = new DataTable();
        string filepath = @"C:\Users\2563911\source\repos\test.txt";
        using (System.IO.TextReader tr = File.OpenText(filepath))
        {
            string line;

            while ((line = tr.ReadLine()) != null)
            {
                if (!line.StartsWith("-"))
                {
                    if (line.Length < 82 || line.Contains("MY01"))
                    {

                        string[] items = line.Replace("MY01", "").Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);

                        try
                        {
                            if (dt.Columns.Count == 0)
                            {
                                // Create the data columns for the data table based on the number of items
                                // on the first line of the file
                                for (int i = 0; i < items.Length; i++)
                                {
                                    dt.Columns.Add(new DataColumn("Column" + i, typeof(string)));

                                }
                             }

                            dt.Rows.Add(items);


                            foreach (DataRow dr in dt.Rows)
                            {
                                dr[2] = dr[1].ToString() + dr[2].ToString();
                            }
                            dt.Columns.RemoveAt(1);                                
                        }

                        catch (System.ArgumentException c)
                        {
                            MessageBox.Show(c.Message);
                            break;
                        }
                    }
                }
            }
            //show it in gridview
            this.DataGridView.DataSource = dt;
        }
    }
}

示例文本文件:

MY01 CISCO ZPRP 08-0729-01-MAR 08-0729-01
MY01 CISCO ZPRP 08-0729-01-MAR 08-0729-01
MY01 CISCO ZPRP 08-0729-01-MAR 08-0729-01
MY01 CISCO ZPRP 10- 2919-01$1

标签: c#datatable

解决方案


推荐阅读