C# ComboBox 数据源绑定后数据的添加

   由于ComboBox绑定后,数据动态变化会出现一系列"内存保护"错误,无意中发现老外写的一些东西

即在静态绑定的情况下,不改变数据源,增加ComboBox的选项,这里用ComboBox.Items.add是会报错的.

测试表内容如下:

       表TestTable:      SeqNo    Content 
                                   as1         张三 
                                   as2         李四 
                                   33          as11 
                                   55          as22 
                                    丁          ad33

 

代码如下:

private void Form1_Load(object sender, EventArgs e) { string conditionStr = "as"; this.comboBox1.TextChanged -= new System.EventHandler(this.comboBox1_TextChanged); string str1 = "SELECT Content,SeqNo From TestTable Where (Content like '" + conditionStr + "%' Or SeqNo like '" + conditionStr + "%') Order by Content"; tempDataTable = GetData(str1); comboBox1.DisplayMember = "Content"; comboBox1.DataSource = tempDataTable; comboBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend; comboBox1.AutoCompleteSource = AutoCompleteSource.ListItems; this.comboBox1.TextChanged += new System.EventHandler(this.comboBox1_TextChanged); } public static DataTable GetComboBoxedDataTable(DataTable oldDataTable, string valueColumn, string textColumn, string topRowValue, string topRowText) { DataTable newDataTable = new DataTable(); newDataTable.Columns.Add(valueColumn); newDataTable.Columns.Add(textColumn); foreach (DataRow oldDR in oldDataTable.Rows) { DataRow newDR = newDataTable.NewRow(); newDR[0] = oldDR[valueColumn].ToString(); newDR[1] = oldDR[textColumn].ToString(); newDataTable.Rows.InsertAt(newDR, newDataTable.Rows.Count); } // Add your 'Select an item' option at the top DataRow dr = newDataTable.NewRow(); dr[0] = topRowValue; dr[1] = topRowText; newDataTable.Rows.InsertAt(dr, 0); return newDataTable; } private void comboBox1_TextChanged(object sender, EventArgs e) { this.comboBox1.TextChanged -= new System.EventHandler(this.comboBox1_TextChanged); comboBox1.DataSource = GetComboBoxedDataTable(tempDataTable, "Content", "SeqNo", "王五", "as3"); this.comboBox1.TextChanged += new System.EventHandler(this.comboBox1_TextChanged); } private DataTable GetData(string strSQl) { DataTable dtData = new DataTable(); using (SqlConnection thisConnection = new SqlConnection( @"Data Source=(local);Initial Catalog=AVE661;Integrated Security=True")) { using (SqlDataAdapter thisAdapter = new SqlDataAdapter( strSQl, thisConnection)) { thisAdapter.Fill(dtData); } thisConnection.Close(); } return dtData; }

 

 

你可能感兴趣的:(C#)