ListBox 和 Datasource - 防止第一个项目被选中

4

本文介绍了ListBox 和 Datasource - 防止第一个项目被选中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

嘿.我有以下代码填充我的列表框

Hey. I've got the following code that populates my list box

UsersListBox.DataSource = GrpList;

但是,在填充该框后,默认选择列表中的第一项,并触发选择的索引已更改"事件.如何防止在填充列表框后立即选择项目,或者如何防止触发事件?

However, after the box is populated, the first item in the list is selected by default and the "selected index changed" event fires. How do I prevent the item from being selected right after the list box was populated, or how do I prevent the event from firing?

谢谢

推荐答案

为了防止事件触发,这里有两个我过去使用过的选项:

To keep the event from firing, here are two options I have used in the past:

  1. 在设置 DataSource 时取消注册事件处理程序.

  1. Unregister the event handler while setting the DataSource.

UsersListBox.SelectedIndexChanged -= UsersListBox_SelectedIndexChanged;
UsersListBox.DataSource = GrpList;
UsersListBox.SelectedIndex = -1; // This optional line keeps the first item from being selected.
UsersListBox.SelectedIndexChanged += UsersListBox_SelectedIndexChanged;

  • 创建一个布尔标志以忽略该事件.

  • Create a boolean flag to ignore the event.

    private bool ignoreSelectedIndexChanged;
    private void UsersListBox_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ignoreSelectedIndexChanged) return;
        ...
    }
    ...
    ignoreSelectedIndexChanged = true;
    UsersListBox.DataSource = GrpList;
    UsersListBox.SelectedIndex = -1; // This optional line keeps the first item from being selected.
    ignoreSelectedIndexChanged = false;
    

  • 这篇关于ListBox 和 Datasource - 防止第一个项目被选中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

    The End

    相关推荐

    C# 中的多播委托奇怪行为?
    Multicast delegate weird behavior in C#?(C# 中的多播委托奇怪行为?)...
    2023-11-11 C#/.NET开发问题
    6

    参数计数与调用不匹配?
    Parameter count mismatch with Invoke?(参数计数与调用不匹配?)...
    2023-11-11 C#/.NET开发问题
    26

    如何将代表存储在列表中
    How to store delegates in a List(如何将代表存储在列表中)...
    2023-11-11 C#/.NET开发问题
    6

    代表如何工作(在后台)?
    How delegates work (in the background)?(代表如何工作(在后台)?)...
    2023-11-11 C#/.NET开发问题
    5

    没有 EndInvoke 的 C# 异步调用?
    C# Asynchronous call without EndInvoke?(没有 EndInvoke 的 C# 异步调用?)...
    2023-11-11 C#/.NET开发问题
    2

    Delegate.CreateDelegate() 和泛型:错误绑定到目标方法
    Delegate.CreateDelegate() and generics: Error binding to target method(Delegate.CreateDelegate() 和泛型:错误绑定到目标方法)...
    2023-11-11 C#/.NET开发问题
    14