Datagridview add Combobox 2

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;


namespace MyTestDGV_Combobox
{
    public partial class Employees : Form
    {
        string connectionString =
            "Integrated Security=SSPI;Persist Security Info=False;" +
            "Initial Catalog=Northwind;Data Source=localhost";




        public Employees()
        {
            InitializeComponent();


        }


        private void Employees_Load(object sender, EventArgs e)
        {
            try
            {
                SetUpDataGridView1();
            }
            catch (SqlException)
            {
                MessageBox.Show("The connection string <"
                    + connectionString
                    + "> failed to connect.  Modify it "
                    + "to connect to a Northwind database accessible to "
                    + "your system.",
                    "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                Application.Exit();
            }


        }


        private void SetUpDataGridView1()
        {
            dataGridView1.VirtualMode = true;
            dataGridView1.AutoSize = true;
            dataGridView1.DataSource = Populate("SELECT * FROM Employees");
            dataGridView1.TopLeftHeaderCell.Value = "Employees";
            dataGridView1.RowHeadersWidthSizeMode =  DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders;
            dataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
            dataGridView1.AllowUserToAddRows = false;
            dataGridView1.AllowUserToDeleteRows = false;


            // 下面自动产生的列移除 -------------------------------------------------------------------------
            // a DataGridViewComboboxColumn could be used instead.
            dataGridView1.Columns.Remove(ColumnName.TitleOfCourtesy.ToString());
            //dataGridView1.Columns.Remove(ColumnName.ReportsTo.ToString());


            //需要增加列
            //AddLinkColumn();
            AddComboBoxColumns();
           // AddButtonColumn();
            //AddOutOfOfficeColumn();
        }


        private void AddComboBoxColumns() //----------------------------------------------------------------
        {
            //---------------------------****************************************************----------------------------------------------------------
            DataGridViewComboBoxColumn comboboxColumn = CreateComboBoxColumn();
            SetAlternateChoicesUsingDataSource(comboboxColumn);
            //comboboxColumn.HeaderText = "TitleOfCourtesy (via DataSource property)";
            dataGridView1.Columns.Insert(0, comboboxColumn);


            //comboboxColumn = CreateComboBoxColumn();
            //SetAlternateChoicesUsingItems(comboboxColumn);
            //comboboxColumn.HeaderText = "TitleOfCourtesy (via Items property)";
            Tack this example column onto the end.
            //DataGridView1.Columns.Add(comboboxColumn);
        }


        private void SetAlternateChoicesUsingDataSource(DataGridViewComboBoxColumn comboboxColumn)
        {
            {
                comboboxColumn.DataSource = RetrieveAlternativeTitles();
                //comboboxColumn.ValueMember = ColumnName.TitleOfCourtesy.ToString();
                //comboboxColumn.ValueMember = ColumnName.FirstName.ToString(); //----------------------------------此处修改----------------
                comboboxColumn.ValueMember = "CategoryName";
                comboboxColumn.DisplayMember = comboboxColumn.ValueMember;
            }
        }


        private DataTable RetrieveAlternativeTitles()//返回选择的标题
        {
            //return Populate("SELECT distinct TitleOfCourtesy FROM Employees");
           // return Populate("SELECT distinct [FirstName]   FROM [Employees] "); //----------------------------------此处修改----------------
            return Populate("SELECT  [CategoryName]  FROM [Categories]  ");
        }


        private DataGridViewComboBoxColumn CreateComboBoxColumn()
        {
            DataGridViewComboBoxColumn column =    new DataGridViewComboBoxColumn();
            {
                //column.DataPropertyName = ColumnName.TitleOfCourtesy.ToString();
                //column.HeaderText = ColumnName.FirstName.ToString();// //----------------------------------此处修改----------------
                column.HeaderText = "CategoryName";
                //column.DataPropertyName = ColumnName.FirstName.ToString(); //----------------------------------此处修改----------------
                column.DataPropertyName = "CategoryName";
                column.DropDownWidth = 160;
                column.Width = 90;
                column.MaxDropDownItems = 3;
                column.FlatStyle = FlatStyle.Flat;
            }
            return column;


        }


        private void AddLinkColumn()
        {
            throw new NotImplementedException();
        }


        private DataTable Populate(string sqlCommand)
        {
            SqlConnection northwindConnection = new SqlConnection(connectionString);
            northwindConnection.Open();


            SqlCommand command = new SqlCommand(sqlCommand, northwindConnection);
            SqlDataAdapter adapter = new SqlDataAdapter();
            adapter.SelectCommand = command;


            DataTable table = new DataTable();
            table.Locale = System.Globalization.CultureInfo.InvariantCulture;
            adapter.Fill(table);


            return table;
        }




        private void DataGridView1_CellValueNeeded(object sender,  DataGridViewCellValueEventArgs e)
        {


            //if (IsCheckBoxColumn(e.ColumnIndex))
            //{
            //    string employeeId = GetKey(e);
            //    if (!inOffice.ContainsKey(employeeId))
            //    {
            //        bool defaultValue = false;
            //        inOffice.Add(employeeId, defaultValue);
            //    }


            //    e.Value = inOffice[employeeId];
            //}
        }




        private void dataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs anError)
        {
            MessageBox.Show("Error happened " + anError.Context.ToString());


            if (anError.Context == DataGridViewDataErrorContexts.Commit)
            {
                MessageBox.Show("Commit error");
            }
            if (anError.Context == DataGridViewDataErrorContexts.CurrentCellChange)
            {
                MessageBox.Show("Cell change");
            }
            if (anError.Context == DataGridViewDataErrorContexts.Parsing)
            {
                MessageBox.Show("parsing error");
            }
            if (anError.Context == DataGridViewDataErrorContexts.LeaveControl)
            {
                MessageBox.Show("leave control error");
            }


            if ((anError.Exception) is ConstraintException)
            {
                DataGridView view = (DataGridView)sender;
                view.Rows[anError.RowIndex].ErrorText = "an error";
                view.Rows[anError.RowIndex].Cells[anError.ColumnIndex].ErrorText = "an error";


                anError.ThrowException = false;
            }


        }


        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            //if (IsANonHeaderLinkCell(e))
            //{
            //    MoveToLinked(e);
            //}
            //else if (IsANonHeaderButtonCell(e))
            //{
            //    PopulateSales(e);
            //}
 
        }


     


        enum ColumnName
        {
            EmployeeId,
            LastName,
            FirstName,
            Title,
            TitleOfCourtesy,
            BirthDate,
            HireDate,
            Address,
            City,
            Region,
            PostalCode,
            Country,
            HomePhone,
            Extension,
            Photo,
            Notes,
            ReportsTo,
            PhotoPath,
            OutOfOffice
        };








        #region check state
        Dictionary<string, bool> inOffice = new Dictionary<string, bool>();
        private void dataGridView1_CellValuePushed(object sender, DataGridViewCellValueEventArgs e)
        {
            if (IsCheckBoxColumn(e.ColumnIndex))
            {
                string employeeId = GetKey(e);
                if (!inOffice.ContainsKey(employeeId))
                {
                    inOffice.Add(employeeId, (Boolean)e.Value);
                }
                else
                {
                    inOffice[employeeId] = (Boolean)e.Value;
                }
            }


        }
        #endregion




        private string GetKey(DataGridViewCellValueEventArgs e)
        {
            return dataGridView1.Rows[e.RowIndex].Cells[ColumnName.EmployeeId.ToString()].Value.ToString();
        }


        private bool IsCheckBoxColumn(int columnIndex)
        {
            DataGridViewColumn outOfOfficeColumn = dataGridView1.Columns[ColumnName.OutOfOffice.ToString()];
            return (dataGridView1.Columns[columnIndex] == outOfOfficeColumn);
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值