Datagridview中的ComboBox

本文介绍了一种在DataGridView中实现自定义下拉列表的方法,通过添加ComboBox控件并根据单元格内容显示部门ID和名称,实现了数据的有效管理和便捷操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

其实不应该算标题所说,
这里没有用Datagridview控件里的DatagridviewComboBoxColumn列,
因为之前用这个,有功能实现不了,
就是显示的问题,由于我是自己写代码获得的数据源,
绑定的时候DataPropertyName显示不了数据,....
kv值都很正常.....
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;

namespace MIS
{
    public partial class FormHrDept : Form
    {
        DataSet ds = new DataSet();
        DataTable dt = new DataTable();
        ComboBox cbb1 = new ComboBox();


        public FormHrDept()
        {
            InitializeComponent();
        }

        private void FormHrDept_Load(object sender, EventArgs e)
        {
            find();
            findComBoBoxValue();
            setParentDeptIdCellValue();


        }
        private void find()//查找数据
        {
            ds.Tables.Clear();
            ds = appcode.DALL.selectAll_Dataset("HrDept");
            ds.Tables[0].TableName = "HrDept";
            dt = ds.Tables[0];
            dataGridView1.DataSource = dt;
            dataGridView1.Columns["parentDeptID"].Width = 155;
            dataGridView1.Columns["DeptName"].Width = 135;
        }
        private void setParentDeptIdCellValue()//设置parentDeptID字段的显示值
        {
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                string cellValue = dataGridView1.Rows[i].Cells["parentDeptID"].Value.ToString();
                DataRow[] dr = ds.Tables[0].Select("DeptID=" + cellValue + "");//在dt中查找包含该值的行,这里的行数只会是1,因为此字段为主键
                DataTable dtt = new DataTable();
                dtt = ds.Tables[0].Clone();
                dtt.ImportRow(dr[0]);
                string DeptNamevalue = dtt.Rows[0]["DeptName"].ToString();//取得结果行中Name字段的值, 
                string cellText = cellValue.Trim() + ":" + DeptNamevalue;//字段拼接
                DataGridViewCell cell = dataGridView1.Rows[i].Cells["parentDeptID"];//创建DataGridViewCell对象,赋值为当前单元格
                cell.Value = cellText;//为对象赋值
            }
        }
        private void findComBoBoxValue()//为下拉列表填充内容
        {
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                string DeptID = ds.Tables[0].Rows[i]["DeptID"].ToString().Trim();
                string DeptValue = ds.Tables[0].Rows[i]["DeptName"].ToString().Trim();
                string parDeptID = ds.Tables[0].Rows[i]["PARENTDEPTID"].ToString().Trim();
                string cbbText = DeptID + ":" + DeptValue;
                cbb1.Items.Add(cbbText);
                cbb1.DropDownStyle = ComboBoxStyle.DropDownList;//设置只允许选择,不允许编辑
            }
        }
        //{
        //    dsComboboxValue.Tables.Clear();

        //    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
        //    {
        //        string DeptID = ds.Tables[0].Rows[i]["DeptID"].ToString().Trim();
        //        string DeptValue = ds.Tables[0].Rows[i]["DeptName"].ToString().Trim();
        //      string   parDeptID = ds.Tables[0].Rows[i]["PARENTDEPTID"].ToString().Trim();
        //        string cbbText = DeptID + ":" + DeptValue;
        //       ParentDeptID.Items.Add(cbbText);

        //    }
        //        ParentDeptID.DisplayMember = "DeptName";
        //        ParentDeptID.ValueMember = "DeptID";
        //        ParentDeptID.DataPropertyName = "DeptName";

        //        //  dataGridView1["PARENTDEPTID",i].Value = parentDeptID + ":" + value;
        //        //   ParentDeptID.DisplayStyleForCurrentCellOnly = true;
        //        // this.ParentDeptID.DefaultCellStyle.NullValue = parentDeptID + ":" + value;
        //        //this.dataGridView1["PARENTDEPTID", i].NullValue = parentDeptID + ":" + value;

        //    }       
        //}
        //private void findComboBoxDisplayValue(string parentDeptID)
        //{         
        //    DataRow[] dr = ds.Tables[0].Select("DeptID=" + parentDeptID + "");
        //    DataTable dtt = new DataTable();
        //    dtt = ds.Tables[0].Clone();
        //    dtt.ImportRow(dr[0]);
        //    string value = dtt.Rows[0]["DeptName"].ToString();

        //    ParentDeptID.DefaultCellStyle.NullValue = parentDeptID + ":" + value;
        //}
        private void 刷新ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            find();
            setParentDeptIdCellValue();
        }
        private void 新增ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ((DataTable)dataGridView1.DataSource).Rows.Add(dt.NewRow());
            dataGridView1.CurrentCell = dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells["DeptID"];
            dataGridView1.BeginEdit(false);
        }
        private void 删除ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int index = dataGridView1.CurrentCell.RowIndex;
            string value = dataGridView1.Rows[index].Cells["DeptName"].Value.ToString();
            bool yesNo = appcode.others.showMessage_Yes_No("是否删除名称为:\"" + value + "\"的记录?删除后,将不可恢复!");
            if (yesNo)
            {
                dataGridView1.Rows.RemoveAt(index);
                int i = appcode.others.UpdateByDataSet(ds, "HrDept", appcode.others.connString());
                if (i != -1)
                {
                    panel1.Focus();
                }
            }
        }
        private void 保存ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            panel1.Focus();
            if (ds.HasChanges())
            {
 
                    for (int k = 0; k < dataGridView1.Rows.Count; k++)//保存时先循环整个表格
                    {
                        string cellvalue = dataGridView1["parentDeptID", k].Value.ToString().Trim();//取得当前行的parentDeptID字段的值
                        object deptID = dataGridView1["deptID", k].Value;//取得当前行deptID字段值
                        if (deptID==null||deptID.ToString()=="")//deptID字段是主键,不可能为空
                        {
                            ds.Tables[0].Rows.RemoveAt(k);
                            break;//如果deptID字段为空,就证明此行是新添加的行,不予下面的操作
                        }
                        int index = cellvalue.IndexOf(':');//取得冒号的索引
                        // string result = cellvalue.Remove(0, index);
                        string result1 = cellvalue.Remove(index);//删除冒号索引以后的字符
                        ds.Tables[0].Rows[k]["parentDeptID"] = result1;//修改ds的parentDeptID字段值
                    }
                    int i = appcode.others.UpdateByDataSet(ds, "HrDept", appcode.others.connString());
                    if (i != -1)
                    {
                        appcode.others.showMessage_Successfully_saved();
                        find();//重新执行一次刷新
                        //findComBoBoxValue();
                        setParentDeptIdCellValue();//重新设置parentDeptID字段显示的值
                    } 
            }
        }
        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void dataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {

        }
        private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
        {//单元格获得焦点时发生
            int columnIndex = dataGridView1.Columns["parentDeptID"].Index;//取得要添加comboBox的列索引
            if (e.ColumnIndex == columnIndex)//如果当前索引等于comboBox的列索引,这正是我要做的.
            {
                displayComboBoxOnCell(dataGridView1, cbb1, e.RowIndex, e.ColumnIndex);//调用方法;
                dataGridView1.Controls.Add(cbb1);
                string cellvalue = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString().Trim();
                for (int j = 0; j < cbb1.Items.Count; j++)
                {
                    string value2 = cbb1.GetItemText(cbb1.Items[j]);
                    if (value2 == cellvalue)
                    {
                        cbb1.SelectedIndex = j;
                        break;
                    }
                }
            }
        }
        private void displayComboBoxOnCell(DataGridView dgv, ComboBox cbb, int rowIndex, int columnIndex)
        {//将ComboBox显示到单元格
            DataGridViewCell dgvCell = dgv.Rows[rowIndex].Cells[columnIndex];//获取当前单元格
            Rectangle rect = dgv.GetCellDisplayRectangle(dgvCell.ColumnIndex, dgvCell.RowIndex, false);//取得单元格的界值,也就是位置
            cbb.Location = rect.Location;//设置ComboBox位置为当前单元格的位置
            cbb.Size = rect.Size;//大小相同
            cbb.Visible = true;          //显示ComboBox
        }

        private void dataGridView1_CellLeave(object sender, DataGridViewCellEventArgs e)//当单元格失去焦点时
        {
            updataComboBoxCellValue(dataGridView1, cbb1, e.RowIndex, e.ColumnIndex);
        }
        private void updataComboBoxCellValue(DataGridView dgv, ComboBox cbb, int rowIndex, int columnIndex)
        {//该方法将comboBox的选中内容赋值给Cell单元格
            int colIndex = dataGridView1.Columns["parentDeptID"].Index;//取得要添加comboBox的列索引
            if (columnIndex == colIndex)//如果该索引等于当前活动列的索引,说明是当前要更改值的列
            {
                DataGridViewCell cell = dgv.Rows[rowIndex].Cells[colIndex];//将当前单元格赋值给Cell对象
                if (cell.Value != null && cell.Value.ToString() != cbb.Text)//如果不为空,并且不是原值
                {
                    cell.Value = cbb.Text;//将cbb的值赋值给cell
                }
                cbb.Visible = false;//将comboBox设置隐藏
            }
        }
    }
}


研究了好几天,终于弄成功了,思路太重要了... 
记录下,以方便以后参考.,
本文用是添加控件的方式实现的,创建一个ComboBox,为其写入内容,
再在指定单元格获得焦点的时候将ComboBox写入到该单元格,
根据该列的内容显示为序号+内容,
单元格内显示是内容的序号+内容,这里写了几个循环来实现这一功能.

保存的时候又循环全部行来将指定行写入显示值的一部分的值.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值