转载:http://blog.sina.com.cn/s/blog_629e606f01014d4b.html

ComboBox最经常使用的事件就是SelectedIndexChanged。但在将ComboBox绑定到某个数据源的过程中,会触发SelectedIndexChanged
事件,而这个时候用户并没有选择内容,其SelectedValue也不是对应字段的值。那么时写在SelectedIndexChanged中的处理代码就会因为SelectedValue的内容不正确引发异常。
一般网上找到的方法是添加一个标记位,在绑定前设置为false,绑定完成后设置回true。

void BindComboBox()
{
    flag=false;
    ComboxBox1.ValueMember="ValueColumn";
    ComboxBox1.DisplayMember="DisplayColumn";
    ComboxBox1.DataSource=DataTable1;
    flag=true;
}
 
 
private void ComboxBox1_SelectedIndexChanged(object sender, EventArgs e)
{
     if(flag)
     {
          //Do something
      }   
}

另外还有一种办法,就是在绑定前,将SelectedIndexChanged的委托去掉,等绑定完成后,再添加事件委托。

 
void BindComboBox()
{          //去除委托
            ComboBox1.SelectedIndexChanged -= new EventHandler(ComboBox1_SelectedIndexChanged);           
            ComboBox1.DataSource = null;
            ComboBox1.ValueMember = "ValueColumn";          
            ComboBox1.DataSource = DataTable1;
            //添加委托 
            ComboBox1.SelectedIndexChanged += new EventHandler(ComboBox1_SelectedIndexChanged);
            ComboBox1.DisplayMember = "DisplayColumn";
}

两种方法都可以,但是之间的优劣暂时没去比较。感觉好像处理一下委托会好点。因为这种办法真的减少了事件的激发次数。
不知道还有没有其他解决方案呢?

另,贴上一段完整的代码例子。这个例子是访问SqlServer数据库的AdventureWorks,通过ProductCategory和ProductSubCategory两级目录分类去查看Product表的内容。分别使用两个ComboBox和DataGridView完成数据绑定。效果就是选择之后会联动改变相关内容。

 
public partial class frmProduct : Form
    {
DataSet DS = new DataSet();
        String ConnectionString = "integrated security=true; database=AdventureWorks; server=localhost; ";
        public frmProduct()
        {
            InitializeComponent();
        }
       
        private void frmProduct_Load(object sender, EventArgs e)
        {
            SqlDataAdapter da = new SqlDataAdapter("select ProductCategoryID,[Name] from Production.ProductCategory", ConnectionString)
;
            cbbCategories.SelectedIndexChanged -= newEventHandler(cbbCategories_SelectedIndexChanged);
            da.Fill(DS, "ProductCategory");
            cbbCategories.DataSource = null;
            cbbCategories.ValueMember = "ProductCategoryID";          
            cbbCategories.DataSource = DS.Tables["ProductCategory"];
            cbbCategories.SelectedIndexChanged += newEventHandler(cbbCategories_SelectedIndexChanged);
            cbbCategories.DisplayMember = "Name";//这句放在事件委托之后才会有联动效果,下同
        }

private void cbbCategories_SelectedIndexChanged(object sender, EventArgs e)
        {
            SqlDataAdapter da = new SqlDataAdapter("select ProductSubCategoryID,[Name] from Production.ProductSubCategory where  ProductCategoryID=" + cbbCategories.SelectedValue.ToString(), ConnectionString)
;
            if (DS.Tables["ProductSubCategory"] != null)
            {
                DS.Tables["ProductSubCategory"].Clear();
            }
            da.Fill(DS, "ProductSubCategory");
            cbbSubCategories.SelectedIndexChanged -= newEventHandler(cbbSubCategories_SelectedIndexChanged);
            cbbSubCategories.DataSource = null;           
            cbbSubCategories.ValueMember = "ProductSubCategoryID";
            cbbSubCategories.DataSource = DS.Tables["ProductSubCategory"];
            cbbSubCategories.SelectedIndexChanged += newEventHandler(cbbSubCategories_SelectedIndexChanged);
            cbbSubCategories.DisplayMember = "Name";
        }

private void cbbSubCategories_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbbSubCategories.SelectedIndex == -1)
                return;
            SqlDataAdapter da=new SqlDataAdapter("select * from Production.Product where ProductSubCategoryID=" + cbbSubCategories.SelectedValue.ToString(), ConnectionString);
            dgvProduct.DataSource = null;
            if (DS.Tables["Product"] != null)
                DS.Tables["Product"].Clear();
            da.Fill(DS, "Product");
            dgvProduct.DataSource = DS.Tables["Product"];
        }
    }

ComboBox绑定数据源时触发SelectedIndexChanged事件的处理办法的更多相关文章

  1. ext中处理Combobox组件点击触发后台事件的问题

    ext的Combobox组件在绑定数据的时候需要一个Store来绑定数据,在store里面我们可以设置autoLoad属性,这个属性表示Store可以自动的到后台获取数据,ext实质上就是封装好的ja ...

  2. DropDownList 控件不能触发SelectedIndexChanged 事件

    相信DropDownList 控件不能触发SelectedIndexChanged 事件已经不是什么新鲜事情了,原因也无外乎以下几种: 1.DropDownList 控件的属性 AutoPostBac ...

  3. 整理:WPF用于绑定命令和触发路由事件的自定义控件写法

    原文:整理:WPF用于绑定命令和触发路由事件的自定义控件写法 目的:自定义一个控件,当点击按钮是触发到ViewModel(业务逻辑部分)和Xaml路由事件(页面逻辑部分) 自定义控件增加IComman ...

  4. focusout([data],fn) 当元素失去焦点时触发 focusout 事件。

    focusout([data],fn) 概述 当元素失去焦点时触发 focusout 事件. focusout事件跟blur事件区别在于,他可以在父元素上检测子元素失去焦点的情况.大理石平台怎么样 参 ...

  5. blur([[data],fn]) 当元素失去焦点时触发 blur 事件。

    blur([[data],fn]) 概述 当元素失去焦点时触发 blur 事件.大理石平台生产厂 这个函数会调用执行绑定到blur事件的所有函数,包括浏览器的默认行为.可以通过返回false来防止触发 ...

  6. GridView点击行触发SelectedIndexChanged事件

    1.在<% @Page ...... %>指令中添加 EnableEventValidation="false" 2.在RowDataBound事件中添加 protec ...

  7. [C# 基础知识系列]专题五:当点击按钮时触发Click事件背后发生的事情 (转载)

    当我们在点击窗口中的Button控件VS会帮我们自动生成一些代码,我们只需要在Click方法中写一些自己的代码就可以实现触发Click事件后我们Click方法中代码就会执行,然而我一直有一个疑问的—— ...

  8. input中的内容改变时触发的事件

    input中的内容改变时触发的事件 1. onchange事件与onpropertychange事件的区别: onchange事件在内容改变(两次内容有可能相等)且失去焦点时触发:onproperty ...

  9. jQuery和javaScript页面加载完成时触发的事件

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...

随机推荐

  1. SignalR2.0开发实例之——创建房间聊天

    SignalR作为一个强大的集线器,已经在hub里面集成了Gorups,也就是分组管理,使用方法如下: //作用:将连接ID加入某个组 //Context.ConnectionId 连接ID,每个页面 ...

  2. Cookie 添加,读取,删除

    Name,value – 声明时 new Cookie(key,value); Path        - 默认值,即为当前保存cookie的这个serlvet所在的路径. 如果Cookie在这样的路 ...

  3. 【转】C++中的位拷贝与值拷贝

    [转]http://blog.csdn.net/liam1122/article/details/1966617 为了便于说明我们以String类为例: 首先定义String类,而并不实现其成员函数. ...

  4. UVA 10037 贪心算法

    题目链接:http://acm.hust.edu.cn/vjudge/contest/122829#problem/A 题目大意:N个人夜里过河,总共只有一盏灯,每次最多过两个人,然后需要有人将灯送回 ...

  5. POJ1276:Cash Machine(多重背包)

    Description A Bank plans to install a machine for cash withdrawal. The machine is able to deliver ap ...

  6. 如何使用JSONP

    1.使用$.getJSON() $.getJSON(" http://跨域的dns/document!searchJSONResult.action?name1="+value1+ ...

  7. Mysql中natural join和inner join的区别

    假设有如下两个表TableA,TableB TableA TableB Column1 Column2 Column1 Column3 1 2 1 3 TableA的Column1列名和TableB的 ...

  8. Android 源码编译环境搭建(64位Ubuntu)各种依赖包安装

    1.准备: 普通PC(要求能上网), PC的操作系统Ubuntu 10.04 LTS(64位的),已经下载好的Android 1.6_r1的源代码. 2.Linux的依赖package安装: 为了更快 ...

  9. PHP 中filter_var的使用

    filter_var() 函数通过指定的过滤器过滤变量. 如果成功,则返回已过滤的数据,如果失败,则返回 false. 语法 :filter_var(variable, filter, options ...

  10. $parse , $interpolate ,$complie , $destroy

    $parse 是angular 提供的javascript解析器 . var getter = $parse(expression); var setter = getter.assign; cont ...