0
    namespace explorer
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
                DirectoryInfo di = new DirectoryInfo("c:\\test");
                FileSystemInfo[] files = di.GetFileSystemInfos();
                checkedListBox1.Items.AddRange(files);
            }

            private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
            {
                for (int ix = 0; ix < checkedListBox1.Items.Count; ++ix)
                if (ix != e.Index) checkedListBox1.SetItemChecked(ix, false); 
            }
            //removed irrelevant parts of the code
        }
    }

チェックリスト ボックスのイベント ハンドラーを作成する方法を忘れてしまいました。1 つ選択する必要があります。複数のファイルがありますが、チェック ボックスで選択したファイルが 1 つだけ必要です。

4

2 に答える 2

2

ItemCheck イベントで項目のチェックを解除しているため、スタック オーバーフローを回避するために、イベント ハンドラーをオフにするか、変数をフラグとして使用する必要があります。

private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e) {
  checkedListBox1.ItemCheck -= checkedListBox1_ItemCheck;
  for (int ix = 0; ix < checkedListBox1.Items.Count; ++ix) {
    if (ix != e.Index) {
      checkedListBox1.SetItemChecked(ix, false);
    }
  }
  checkedListBox1.ItemCheck += checkedListBox1_ItemCheck;
}

変数を使用した例:

bool checkFlag = false;

private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e) {
  if (!checkFlag) {
    checkFlag = true;
    for (int ix = 0; ix < checkedListBox1.Items.Count; ++ix) {
      if (ix != e.Index) {
        checkedListBox1.SetItemChecked(ix, false);
      }
    }
    checkFlag = false;
  }
}
于 2012-10-11T14:38:08.970 に答える
1

コレクションを作成List<FileSystemInfo>し、チェックしたすべてのファイルをコレクションに追加し、チェックを外すと削除できます。私が見るように、ハンドラー自体はすでに作成されています( checkedListBox1_ItemCheck)。質問をもっと明確に書くことを検討する必要があるかもしれません。

于 2012-10-11T14:32:47.773 に答える