我有一个包含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);
}
}
答案 0 :(得分:1)
您可以使用此代码
检查/取消选中checkedListBox中的项目checkedListBox.SetItemChecked(item, true);
更多信息请转到microsoft documentation
答案 1 :(得分:1)
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
答案 2 :(得分:0)
如果关联的后台工作正在运行,此代码会阻止检查状态更改:
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; }
}
答案 3 :(得分:0)
请注意,只有功能解决方案才是设置选择模式
CheckedListBox.SelectionMode = SelectionMode.None;