Loop in Listbox

MiPakTeh 1,476 Reputation points
2023-07-20T10:47:02.91+00:00

Hi All,

I have 5 lines in txtfile, it show listbox1 and count every number in listbox2 and item Max /item Min in listbox3 then textbox1 for search lines using loop.Problem at textbox when key in 0, 1, 4, 5 it become error value index but key in line 2 and 3 it OK.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Bat_10
{
    public partial class Form1: Form
    {
        List < string > Data1 = new List < string > ();
        List < string > Data2 = new List < string > ();
        List < string > Data3 = new List < string > ();
        //List<myItem> MyItems = new List<myItem>();
        public static List < string > list = new List < string > ();
        int Lines = 0;
        int Lines_a = 0;
        string text = "";
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            foreach(var s in File.ReadLines(@"D:\Ori_1.txt").Skip(1).Select(s => s.Split(new []
            {
                ','
            }, 3)[2]))
            {
                listBox1.Items.Add(Lines++ +" " + s);
                Data1.Add(s);
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            foreach(var item in Data1)
            {
                //++Lines_a;
                listBox2.Items.Add(item + "   =>" + Lines_a++);
                var MyItems = new List < myItem > ();
                int min = int.MaxValue;
                int max = int.MinValue;
                for(int j = 0; j <= 9; j++)
                {
                    String Number_ = j.ToString();
                    int NumberCount_ = item.ToString().Replace(",", "").ToCharArray().Count(c => c.ToString() == Number_);
                    listBox2.Items.Add(Number_ + " = " + NumberCount_);
                    MyItems.Add(new myItem()
                    {
                        Index = Convert.ToInt32(Number_.ToString()), Value = NumberCount_
                    });
                }
                foreach(myItem ITM in MyItems)
                {
                    if(ITM.Value < min)
                    {
                        min = ITM.Value;
                    }
                    if(ITM.Value > max)
                    {
                        max = ITM.Value;
                    }
                }
                string List = "";
                string List_ = "";
                foreach(myItem ITM in MyItems)
                {
                    if(ITM.Value == min)
                    {
                        List += "Min = " + min.ToString() + " , " + "ItemMin = " + ITM.Index.ToString() + "  " + " || ";
                    }
                    if(ITM.Value == max)
                    {
                        {
                            List_ += "Max = " + max.ToString() + " , " + "ItemMax = " + ITM.Index.ToString() + "     => ";
                        }
                    }
                }
                listBox2.Items.Add(List + "   " + List_ + Lines_a);
                Data3.Add(List + "   " + List_ + "  ");
            }
        }
        private void button2_Click(object sender, EventArgs e)
        {
            var duplicates = Data3.Select((t, i) => new
            {
                Index = i, Text = t
            }).GroupBy(g => g.Text).Where(g => g.Count() > 1).ToList();
            foreach(var item in duplicates)
            {
                var result = item.Select(i => i.Index + "  " + i.Text).ToArray();
                text = string.Join("  ", result);
                listBox3.Items.Add(text);
            }
        }
        private void listBox3_SelectedIndexChanged(object sender, EventArgs e)
        {
            listBox4.Items.Clear();
            string curItem = listBox3.SelectedItem.ToString().Trim().Replace(" ", "");
            // Use regex to match numbers followed by the letter "M"
            var matches = Regex.Matches(curItem, @"\d+M");
            // Use LINQ to extract the numeric part of the matching result
            var arr = matches.Cast < Match > ().Select(m => int.Parse(m.Value.TrimEnd('M'))).ToList();
            foreach(var item in arr)
            {
                int index = item;
                for(int i = index * 12; i < ((index + 1) * 12); i++)
                {
                    string listbox1item = listBox2.Items[i].ToString();
                    listBox4.Items.Add(listbox1item);
                }
                int index_ = item + 1;
                for(int i = index_ * 12; i < ((index_ + 1) * 12); i++)
                {
                    if(index_ == 0) return;
                    string listbox1item = listBox2.Items[i].ToString();
                    listBox4.Items.Add(listbox1item);
                }
            }
        }
        private void button3_Click(object sender, EventArgs e)
        {
            const string sPath = "C:\\Users\\family\\Documents\\Checking.txt";
            System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(sPath);
            foreach(var item in listBox4.Items)
            {
                SaveFile.WriteLine(item.ToString());
            }
            SaveFile.Close();
            MessageBox.Show("Programs saved!");
        }
        private void button4_Click(object sender, EventArgs e)
        {
            listBox4.Items.Clear();
            int myString = Convert.ToInt32(textBox1.Text);
            bool found = false;
            for(int i = 0; i <= listBox3.Items.Count - 1; i++)
            {
                if(listBox3.Items[i].ToString().Contains(myString.ToString()))
                {
                    listBox3.SetSelected(i, true);
                    found = true;
                    break;
                }
            }
            if(!found)
            {
                MessageBox.Show("Item not found!");
            }
        }
    }
}
public partial class myItem
{
    public int Index;
    public int Value;
    public override string ToString()
    {
        return Index.ToString() + " => " + Value.ToString();
    }
}

txtfile:

xxxx

040792,19920506,0019,1124,0592,0950,2479,7139,3114,4609,7836,8981,4465,6114,5301,5311,1949,1606,3775,6226,1271,7455,7227,9258,0407

040992,19920510,4162,5766,9514,9309,9344,1573,5077,1037,6498,8325,7203,4754,7849,6908,4809,0464,1932,8240,2725,6294,9991,5707,6754

040992,19920510,4162,5766,9514,9309,9344,1573,5077,1037,6498,8325,7203,4754,7849,6908,4809,0464,1932,8240,2725,6294,9991,5707,6754

041192,19920514,5371,5472,3489,6872,2455,0600,4590,7261,3384,8670,7869,5664,4100,1683,6817,4710,6375,4702,9716,6082,9674,8899,7760

041192,19920514,5371,5472,3489,6872,2455,0600,4590,7261,3384,8670,7869,5664,4100,1683,6817,4710,6375,4702,9716,6082,9674,8899,7760

040792,19920506,0019,1124,0592,0950,2479,7139,3114,4609,7836,8981,4465,6114,5301,5311,1949,1606,3775,6226,1271,7455,7227,9258,0407
Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,922 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,303 questions
0 comments No comments
{count} votes

Accepted answer
  1. Jiale Xue - MSFT 48,876 Reputation points Microsoft Vendor
    2023-07-21T02:37:22.32+00:00

    Hi @MiPakTeh , Welcome to Microsoft Q&A.

    In the code you provided, listBox3_SelectedIndexChanged has a piece of code that does not know its purpose and will cause index errors. It is recommended to delete it.

    int index_ = item + 1;
    for(int i = index_ * 12; i < ((index_ + 1) * 12)
    {
        if(index_ == 0) return;
        string listbox1item = listBox2.Items[i].ToString();
        listBox4.Items.Add(listbox1item);
    }
    

    The reason for the error you mentioned is that your interpretation is to judge whether the entire string of characters contains the number you input. And the first line contains 0, 1, 4, 5 which is why you said the error. What is the meaning of your search?

    enter image description here

    If you are searching for whether the leading number of each line contains your search number, it should be changed to:

    private void button4_Click(object sender, EventArgs e)
    {
        listBox4.Items.Clear();
        if(!textBox1.Text.All(c => Char.IsDigit(c)) || textBox1.Text.Length == 0) return;
        int myString = Convert.ToInt32(textBox1.Text);
        bool found = false;
        for(int i = 0; i <= listBox3.Items.Count - 1; i++)
        {
            string curItem = (listBox3.Items[i].ToString().Trim().Replace(" ", ""));
            // Use regex to match numbers followed by the letter "M"
            var matches = Regex.Matches(curItem, @"\d+M");
            // Use LINQ to extract the numeric part of the matching result
            var arr = matches.Cast < Match > ().Select(m => int.Parse(m.Value.TrimEnd('M'))).ToList();
            if(arr.Contains(myString))
            {
                listBox3.SetSelected(i, true);
                found = true;
                break;
            }
        }
        if(!found)
        {
            MessageBox.Show("Item not found!");
        }
    }
    

    enter image description here

    Best Regards,

    Jiale


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". 

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.