先从工具箱拖一个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;//如果文本框输入内容后,把其值赋给其对应的单元格 }
如何将TextBox添加到dataGridView中
最新推荐文章于 2024-10-02 12:30:11 发布