如何将TextBox添加到dataGridView中

先从工具箱拖一个textbox到窗体form1中.然后设置其为visible属性为false

在窗体加载中写 
private void Form1_Load(object sender, EventArgs e)
        {

             textBox1.Visible = false;
            textBox1.Width = 0;
            dataGridView1.Controls.Add(textBox1); //这句很重要的
        }

datagridview1的CurrentCellChanged的事件中写
        private void dataGridView1_CurrentCellChanged(object sender, EventArgs e)
        {
            this.textBox1.Visible = false;
            this.textBox1.Width = 0;
            try
            {
                //前提是你的datagridview1一定要有数据呀
                    if (dataGridView1.Columns[dataGridView1.CurrentCell.ColumnIndex].HeaderText == "你选中的单元格所在的列名")
                {
                    //以下是把把textbox1的位置与datagridview1的单元格的位置一样,不过长宽均比单元格的短2
                    this.textBox1.Left = dataGridView1.GetCellDisplayRectangle(dataGridView1.CurrentCell.ColumnIndex, dataGridView1.CurrentCell.RowIndex, true).Left;
                    this.textBox1.Top = dataGridView1.GetCellDisplayRectangle(dataGridView1.CurrentCell.ColumnIndex, dataGridView1.CurrentCell.RowIndex, true).Top;
                    this.textBox1.Width = dataGridView1.GetCellDisplayRectangle(dataGridView1.CurrentCell.ColumnIndex, dataGridView1.CurrentCell.RowIndex, true).Width-2;
                    this.textBox1.Height = dataGridView1.GetCellDisplayRectangle(dataGridView1.CurrentCell.ColumnIndex, dataGridView1.CurrentCell.RowIndex, true).Height - 2;
        
                    string str = Convert.ToString(this.dataGridView1.CurrentCell.Value);                                                this.textBox1.Text = str;//将单元格的值赋给文本框
                    this.textBox1.Visible = true;
                }
            }
            catch
            {
            }
        }
在文本框的Validating事件中
        private void textBox1_Validating(object sender, CancelEventArgs e)
        {
            this.dataGridView1.CurrentCell.Value = this.textBox1.Text;//如果文本框输入内容后,把其值赋给其对应的单元格
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值