天天看点

C# winform: ComboBox 设置下拉框数据源的公共方法

public static void SetComboList(ComboBox cboSource, string sSQL,string sWindowTxt,string sFirstItem="",DataTable dtSource=null) { string sError = string.Empty; DataTable dt=null; if (!string.IsNullOrEmpty(sSQL)) { dt = SqlLiteHelper.GetDataTable(out sError, sSQL); if (!string.IsNullOrEmpty(sError)) Common.DisplayMsg(sWindowTxt, sError); } else if (dtSource != null) { dt = dtSource.Copy(); } if (!string.IsNullOrEmpty(sFirstItem)) { DataRow dr = dt.NewRow(); dr[0] = -1; dr[1] = sFirstItem; dt.Rows.InsertAt(dr, 0); } //cboSource.Items.Clear(); cboSource.DataSource = dt; cboSource.ValueMember = dt.Columns[0].ColumnName; cboSource.DisplayMember = dt.Columns[1].ColumnName; cboSource.DropDownStyle = ComboBoxStyle.DropDownList; }

1, 初始化下拉框数据源 例子:

string sSql = "select id,valuefrom tgExpenditureItem";

Common.SetComboList(cboOutputItem, sSql, this.Text);

DataTable dtSource = new DataTable();

dtSource.Columns.Add("id");

dtSource.Columns.Add("value");

dtSource.Rows.Add(1, "aa");

dtSource.Rows.Add(2, "bb");

dtSource.Rows.Add(3,"cc");

Common.SetComboList(cboOutputItem, "", this.Text, "(全部)", dtSource);

2, 取值可以通过

cboOutputItem.SelectedIndex

cboOutputItem.SelectedItem.ToString()

cboOutputItem.SelectedValue 等方式来取

3, SqlLiteHelper 类请参考:

用于sqlite数据库的SqlLiteHelper.cs 的类

http://blog.csdn.net/keenweiwei/article/details/6845687