簡體   English   中英

c# - 如何在c#中的checkedlistbox中禁用選中/取消選中的項目

[英]How to disable check/uncheck of an item in a checkedlistbox in c#

我有一個包含 10 個項目的 CheckedListBox。 在每個項目檢查一個方法被調用。 我想禁用正在執行該方法的特定項目的復選框,以便用戶在作業完成之前無法取消選中該項目。

** 取消選中一個項目會調用另一個方法。

這是ItemCheck事件的代碼

private void host_listbox_ItemCheck(object sender, ItemCheckEventArgs e)
        {

            int index = e.Index;
            try
            {
                string sitem = host_listbox.Items[index].ToString();
                host_list[sitem].checked_event=e;
                if (!host_list[sitem].is_busy)
                {
                    host_config.listEnabled = false;
                    host_list[sitem].con_worker.RunWorkerAsync();

                }
                if (host_listbox.GetItemCheckState(index) == CheckState.Checked)
                {
                    host_list[sitem].connected = false;
                }

            }
            catch(Exception ex)
            {
                output_textbox.AppendText("connection failed..............." +ex.ToString() +Environment.NewLine);

            }



        }

您可以使用以下代碼檢查/取消選中checkedListBox中的項目

checkedListBox.SetItemChecked(item, true);

有關更多信息,請轉到Microsoft文檔。

  private void host_listbox_ItemCheck(object sender, ItemCheckEventArgs e)
  {

      int index = e.Index;
      try
      {
          string sitem = host_listbox.Items[index].ToString();
          if (host_list[sitem].is_busy // or whatever indicates that background worker is running or any condition that specifies, that you do not want to let this item to be changed)
              e.NewValue = e.CurrentValue; //Change the value back
          else
          { 
          //Let the checked state of the item change

如果相關的后台工作正在運行,則此代碼可防止檢查狀態更改:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        workerList = new List<BackgroundWorker>();

        for (int i = 0; i < 10; i++)
        {
            var el = new BackgroundWorker();
            el.DoWork += (s, e) =>
            {
                Thread.Sleep(5000);
            };

            workerList.Add(el);
            checkedListBox1.Items.Add("el " + i);
        }
    }

    private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
    {
        var worker = workerList[e.Index];

        if (worker.IsBusy)
        {
            e.NewValue = e.CurrentValue;
            return;
        }

        if (e.NewValue == CheckState.Checked)
            worker.RunWorkerAsync();
    }

    public List<BackgroundWorker> workerList { get; set; }
}

想想,只有funcion解決方案設置了選擇模式

CheckedListBox.SelectionMode = SelectionMode.None;
private void ItemCheck(object sender, ItemCheckEventArgs e)
{
  if (busy)
    e.NewValue = e.CurrentValue;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM