Automatically auto-check every new item in a checkedboxlist in c#

白昼怎懂夜的黑 提交于 2021-02-10 14:18:33

问题


I am trying to auto check every new item in my checkedboxlist I have a button that does that it will auto select all, but we don't want it that way to be controlled by a button. we want it so for every new item we get automatically will get checked.

This is my button that auto select all if there are new 20 items this will auto select all and then submit those new items

Here is the code it works but is not I want I want to auto select for every new items coming in, because I have another process that will keep adding new items to the checkedboxlist, also the lst_BarcodeScanEvents is the checkedboxlist name

private void btn_SelectALLScans_Click(object sender, EventArgs e)
        {
            for (var i = 0; i < lst_BarcodeScanEvents.Items.Count; i++)
            {
                lst_BarcodeScanEvents.SetItemChecked(i, true);
            }
        }

I checked other sources like google and stackoverflow but I could not find anything to my request here.

Here is the main class where I have the logic of buttons, checkedlistbox and more. and the button method btn_ConnectT_Click calls the methods from the second class

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using System.Web;
using BarcodeReceivingApp.Core.Domain;
using BarcodeReceivingApp.Functionality;

namespace BarcodeReceivingApp
{
    public partial class BarcodeReceivingForm : Form
    {
        //GLOBAL VARIABLES
        private const string Hostname = "myip";
        private const int Port = 23;
        private TelnetConnection _connection;
        private ParseReceivingBarcode _parseReceivingBarcode;
        private ButtonsDisplay _buttonsDisplay;


        public BarcodeReceivingForm()
        {
            InitializeComponent();
            //FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
            WindowState = FormWindowState.Maximized;
        }

        private void btn_ConnectT_Click(object sender, EventArgs e)
        {
            _connection = new TelnetConnection(Hostname, Port);
            _connection.ServerSocket(Hostname, Port, this);
        }

        private void btn_StopConnection_Click(object sender, EventArgs e)
        {
            _connection.Exit();
        }

        private void btn_RemoveItemFromListAt_Click(object sender, EventArgs e)
        {
            if (lst_BarcodeScanEvents.CheckedItems.Count != 0)
                for (var i = lst_BarcodeScanEvents.CheckedItems.Count; i > 0; i--)
                    lst_BarcodeScanEvents.Items.RemoveAt(lst_BarcodeScanEvents.CheckedIndices[i - 1]);
            else
                MessageBox.Show(@"Element(s) Not Selected...");
        }

        private void BarcodeReceivingForm_Load(object sender, EventArgs e)
        {
            _buttonsDisplay = new ButtonsDisplay(this);
            _buttonsDisplay.ButtonDisplay();
        }

        private void btn_ApplicationSettings_Click(object sender, EventArgs e)
        {
            var bcSettingsForm = new BarcodeReceivingSettingsForm();
            bcSettingsForm.Show();
        }

        private void btn_ClearBarcodeList_Click(object sender, EventArgs e)
        {
            lst_BarcodeScanEvents.Items.Clear();
        }

        private void lst_BarcodeScanEvents_ItemAdded(object sender, ListBoxItemEventArgs e)
        {
            MessageBox.Show(@"Item was added at index " + e.Index + @" and the value is " + lst_BarcodeScanEvents.Items[e.Index].ToString());                          
        }

        private void btn_SubmitData_Click(object sender, EventArgs e)
        {
            var receivingFullBarcode = new List<string>();
            _connection.GetBarcodeList();
        }

        private void btn_SelectALLScans_Click(object sender, EventArgs e)
        {
            for (var i = 0; i < lst_BarcodeScanEvents.Items.Count; i++)
            {
                lst_BarcodeScanEvents.SetItemChecked(i, true);
            }
        }

    }
}

Here is the second class where I use a telnet port 23 that scan barcodes where and puts it to the checkedlistbox, now the main emethods here that inserts the data to the checkedlistbox is the method serversocket and the readwrite method

using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace BarcodeReceivingApp.Functionality
{
    public class TelnetConnection
    {
        private Thread _readWriteThread;
        private TcpClient _client;
        private NetworkStream _networkStream;
        private string _hostname;
        private int _port;
        private BarcodeReceivingForm _form;
        private bool _isExiting = false;

        public TelnetConnection(string hostname, int port)
        {
            this._hostname = hostname;
            this._port = port;
        }

        public void ServerSocket(string ip, int port, BarcodeReceivingForm f)
        {
            this._form = f;
            try
            {
                _client = new TcpClient(ip, port);
            }
            catch (SocketException)
            {
                MessageBox.Show(@"Failed to connect to server");
                return;
            }
            _networkStream = _client.GetStream();
            _readWriteThread = new Thread(ReadWrite);
            //_readWriteThread = new Thread(() => ReadWrite(f));
            _readWriteThread.Start();
        }

        public void Exit()
        {
            _isExiting = true;
        }

        public void ReadWrite()
        {
            do
            {
                var received = Read();
                if (received == null)
                    break;

                if (_form.lst_BarcodeScanEvents.InvokeRequired)
                {
                    var received1 = received;
                    _form.lst_BarcodeScanEvents.Invoke(new MethodInvoker(delegate
                    {
                        _form.lst_BarcodeScanEvents.AddItem(received1 + Environment.NewLine);
                    }));
                }
            } while (!_isExiting);

            //var material = received.Substring(10, 5);
            //_form.label5.Text += string.Join(Environment.NewLine, material);

            CloseConnection();

        }

        public List<string> GetBarcodeList()
        {
            var readData = new List<string>();

            foreach (string list in _form.lst_BarcodeScanEvents.Items)
            {
                readData.Add(list);
                MessageBox.Show(list);
            }

            return readData;
        }
        public string Read()
        {
            var data = new byte[1024];
            var received = "";

            var size = _networkStream.Read(data, 0, data.Length);
            if (size == 0)
                return null;

            received = Encoding.ASCII.GetString(data, 0, size);

            return received;
        }

        public void CloseConnection()
        {
            MessageBox.Show(@"Closed Connection",@"Important Message");
            _networkStream.Close();
            _client.Close();
        }
    }
}

so now like I said before for every new items it gets inserted to the checkedlistbox I want it to be auto selected everytime it adds a new data to the checkedlistbox.


回答1:


The problem, usually simple, of setting the Checked state of a newly added Item of a CheckedListBox, was somewhat complicated because of the nature of the Listbox in question.

The CheckedListBox is a Custom Control with custom events and properties.
It's actually a relatively common customization (one implementation can be see in this MSDN Forum post:
Have ListBox an event when addid or removing Items?) but it might complicate the interpretation of the events.

The Custom Control, when adding a new Item to the List (from a class other than the Form that hosts the Control), raises the custom ItemAdded event

private void [CheckedListBox]_ItemAdded(object sender, ListBoxItemEventArgs e)

The Index of the Item added is referenced by the e.Index property of the custom ListBoxItemEventArgs object.
With the code provided, it can be determined that this event handler is the natural place where the Checked state of the new Item can be set:

private void lst_BarcodeScanEvents_ItemAdded(object sender, ListBoxItemEventArgs e)
{
    lst_BarcodeScanEvents.SetItemChecked(e.Index, true);
}



回答2:


For that I suggest to create an event that you subscribe after you InitializeComponent() of your form like so :

    public Form1()
    {
        InitializeComponent();
        lst_BarcodeScanEvents.ControlAdded += new ControlEventHandler(AddedNewSelect);
    }

    private void AddedNewSelect(object sender, ControlEventArgs e)
    {
        lst_BarcodeScanEvents.SetItemChecked(e.Control.TabIndex, true);
    }


来源:https://stackoverflow.com/questions/54696061/automatically-auto-check-every-new-item-in-a-checkedboxlist-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!