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,value from 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://www.BkJia.com/kf/201111/111180.html
摘自 keenweiwei的專欄