1

我在下面的代码我使用“SelectedLines”来查找用户当前选择的行,AllLines 来查找多行文本框中的总行数。在最后一个 for 循环中,当 i=1 成功运行但当 i 为 +1 = 2 时,它给了我错误

错误:“索引超出范围。必须为非负数且小于集合的大小。参数名称:索引?”

 // Retrieve selected lines
            List<string> SelectedLines = Regex.Split(txtNewURLs.SelectedText, @"\r\n").ToList();
            // Check for nothing, Regex.Split returns empty string when no text is inputted
            if (SelectedLines.Count == 1)
            {
                if (String.IsNullOrWhiteSpace(SelectedLines[0]))
                {
                    SelectedLines.Remove("");
                }
            }
            // Retrieve all lines from textbox
            List<string> AllLines = Regex.Split(txtNewURLs.Text, @"\r\n").ToList();
            // Check for nothing, Regex.Split returns empty string when no text is inputted
            if (AllLines.Count == 1)
            {
                if (String.IsNullOrWhiteSpace(AllLines[0]))
                {
                    AllLines.Remove("");
                }
            }

            string SelectedMessage = "The following lines have been selected";
            int numSelected = 0;
            // Find all selected lines
            foreach (string IndividualLine in AllLines)
            {
                if (SelectedLines.Any(a => a.Equals(IndividualLine)))
                {
                    SelectedMessage += "\nLine #" + AllLines.FindIndex(a => a.Equals(IndividualLine));
                   // changing the status of the selected lene from 0 to 1
                    AddURL objAddURL = new AddURL();
                    objAddURL.Where.SURL.Value = IndividualLine;
                    objAddURL.Where.ILicenseID.Value = CommonMethods.iLicenseID;
                    objAddURL.Query.Load();
                    if (objAddURL.RowCount > 0)
                    {
                        AddURL objaddurl1 = new AddURL();
                        objaddurl1.LoadByPrimaryKey(objAddURL.IAddURLID);
                        if (objaddurl1.RowCount > 0)
                        {
                            objaddurl1.IStatus = 1;
                            objaddurl1.Save();
                        }
                      //  AllLines.Remove(IndividualLine);
                    }
                    numSelected++;
                }
            }
            // int[] lineNo = new int[AllLines.Count];
            int linesNO = SelectedLines.Count;
            for (int i = 1; i <= linesNO; i++)
            {
                SelectedLines.RemoveAt(i);
            }

           // MessageBox.Show((numSelected > 0) ? SelectedMessage : "No lines selected.");

任何人都可以帮我解决这个问题或建议我新的代码吗?

4

1 回答 1

2

c# 中的索引是从零开始的。

for (int i = 0; i < linesNO; i++)
    SelectedLines.RemoveAt(i);

但是如果你想从你的文本框中删除选定的行,你的代码应该看起来像

 List<string> SelectedLines = new List<string> { "b", "c" };
 textBox1.Lines = textBox1.Lines.ToList().Except(SelectedLines).ToArray();
于 2013-04-12T07:49:44.240 回答