1. 程式人生 > >winform將含有超過兩列的DataTable值繫結到combobox,並有"請選擇"或"全部"選擇項

winform將含有超過兩列的DataTable值繫結到combobox,並有"請選擇"或"全部"選擇項

        #region 顯示多列DataTable到combobox
        /// <summary>
        /// 顯示多列DataTable到combobox
        /// </summary>
        /// <param name="dataTable">含有超過兩列的DataTable</param>
        /// <param name="comboBox">combobox控制元件名</param>
        /// <param name="TextColumn">顯示的text對應的列</param>
        /// <param name="ValueColumn">value值對應的列</param>
        /// <param name="isNeedShowEmpty">是否顯示‘請選擇’</param>
        /// <param name="isNeedShowAll">是否顯示‘全部’</param>
        public static void ToDataTableCombobox(DataTable dataTable, ComboBox comboBox, string TextColumn, string ValueColumn, bool isNeedShowEmpty, bool isNeedShowAll)
        {
            if (dataTable == null || comboBox == null || dataTable.Columns.Count == 0)
            {
                return;
            }
            DataTable dtnew = new DataTable();
            dtnew.Columns.Add("text");
            dtnew.Columns.Add("value");
            if (isNeedShowEmpty)
            {
                DataRow emptyRow = dtnew.NewRow();
                emptyRow[1] = "";
                emptyRow[0] = "--請選擇--";
                dtnew.Rows.InsertAt(emptyRow, 0);
            }
            else if (isNeedShowAll)
            {
                DataRow emptyRow = dtnew.NewRow();
                emptyRow[1] = "";
                emptyRow[0] = "全部";
                dtnew.Rows.InsertAt(emptyRow, 0);
            }
            for (int i = 0; i < dataTable.Rows.Count; i++)
            {
                DataRow dr = dtnew.NewRow();
                dr["text"] = dataTable.Rows[i][TextColumn];
                dr["value"] = dataTable.Rows[i][ValueColumn];
                dtnew.Rows.Add(dr);
            }

            comboBox.DataSource = dtnew;//GetItemList()
            comboBox.DisplayMember = dtnew.Columns[0].ColumnName;//"text";
            comboBox.ValueMember = dtnew.Columns[1].ColumnName; //"value";
        }
        #endregion