绑定DataSource时如何防止selectedindexchanged事件?

时间:2013-01-01 16:00:25

标签: c# .net combobox

我有ComboBox控件(WinForm项目)。

当我将DataSource绑定到ComboBox控件时,会触发combobox_selectedindexchanged事件。

知道在绑定DataSource时如何防止selectedindexchanged事件?

5 个答案:

答案 0 :(得分:37)

删除SelectedIndex_Changed事件的处理程序,绑定数据,然后添加处理程序。以下是在方法中如何完成此操作的简单示例:

private void LoadYourComboBox()
{
    this.comboBox1.SelectedIndexChanged -= new EventHandler(comboBox1_SelectedIndexChanged);


        // Set your bindings here . . .


    this.comboBox1.SelectedIndexChanged += new EventHandler(comboBox1_SelectedIndexChanged);
}

答案 1 :(得分:19)

我知道这是一篇旧帖子,它有一个接受的答案,但我认为我们可以使用SelectionChangeCommitted事件作为解决方案,以避免在数据绑定期间发生事件。

仅当用户更改组合框中的选择时,才会触发SelectionChangeCommitted事件。

SO上有一个similar question,这个答案由@arbiter提供。

答案 2 :(得分:5)

使用SelectionChangeCommitted事件代替'SelectedIndexChanged'

  仅当用户更改时才会引发

SelectionChangeCommitted   组合框选择。不要使用SelectedIndexChanged或   SelectedValueChanged用于捕获用户更改,因为这些事件是   当选择以编程方式改变时也会引发。

FROM https://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.selectionchangecommitted.aspx

答案 3 :(得分:2)

不要以为你可以阻止这个事件,但是你无法处理它。

分离事件处理程序,绑定,然后附加事件处理程序。

答案 4 :(得分:0)

这是简单的方法。您可以使用组合框的Tag属性。 当它为空或尚未满足时,它可以是空的或0整数值。您必须在绑定后将组合框的标记设置为其项目的计数。 在SelectedValueChanged事件中,如果Tag属性为null或0,则必须从void返回。

以下是我项目中的一些示例。

private void cb_SelectedValueChanged(object sender, EventArgs e)
{
    if (!(sender is ComboBox)) return;
    ComboBox cb = sender as ComboBox;
    if (DataUtils.ToInt(cb.Tag, 0) == 0) return;
    if (cbSmk.SelectedValue == null ) return;
    /* Continue working;  */
}

public static void ComboboxFill(ComboBox cb, string keyfld, string displayfld, string sql)
{          
    try
    {
        cb.Tag = 0;
        cb.DataSource = null;
        cb.Items.Clear();

        DataSet ds = DataMgr.GetDsBySql(sql);
        if (!DataUtils.HasDtWithRecNoErr(ds))
        {                    
            cb.Text = "No data";
        }
        else
        {
            cb.DataSource = ds.Tables[0];
            cb.DisplayMember = displayfld;
            cb.ValueMember = keyfld;
        }
        cb.Tag = cb.Items.Count;
    }
    catch (Exception ex)
    {
        Int32 len = ex.Message.Length > 200 ? 200 : ex.Message.Length;
        cb.Text = ex.Message.Substring(0, len);
    }                
}

CmpHelper.ComboboxFill(cbUser, "USER_ID", "USER_NAME", "SELECT * FROM SP_USER WHERE 1=1 ORDER by 1",-1);
相关问题