当前位置:编程学习 > C#/ASP.NET >>

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,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.zzzyk.com/kf/201111/111180.html

 

摘自 keenweiwei的专栏

补充:软件开发 , C# ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,