如何删除多行文本框中的选定行?

时间:2013-04-12 07:23:22

标签: c# .net textbox multiline

我在下面的代码中使用过" SelectedLines"要按用户查找当前选定的行,AllLines要在多行文本框中找到总行数。在最后一次循环时,当i = 1时,它成功运行,但当我是+1 = 2时,它会给我错误

  

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

 // 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.");

请问有谁可以帮我解决这个问题或建议我新代码?

1 个答案:

答案 0 :(得分:1)

c#中的指数基于零。

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

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

 List<string> SelectedLines = new List<string> { "b", "c" };
 textBox1.Lines = textBox1.Lines.ToList().Except(SelectedLines).ToArray();