DataGridView 单元格中添加按钮
今晚学的,说得不是很清楚//单元格获得焦点
private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex.Equals(this.dataGridView1.Columns["Company"].Index))
//判断单元格是否是"Company"列?
{
this.dataGridView1.Controls.Clear(); //移除所有控件
Button btn = new Button(); //创建Button btn
btn.Text = "..."; //设置button文字
btn.Font = new Font("Arial", 7); //设置文字格式
btn.Visible = true; //设置控件允许显示
btn.Width = this.dataGridView1.GetCellDisplayRectangle(e.ColumnIndex,
e.RowIndex,true).Height; //获取单元格高并设置为btn的宽
btn.Height = this.dataGridView1.GetCellDisplayRectangle(e.ColumnIndex,
e.RowIndex, true).Height; //获取单元格高并设置为btn的高
btn.Click += new EventHandler(btn_Click); //为btn添加单击事件
this.dataGridView1.Controls.Add(btn); //dataGridView1中添加控件btn
btn.Location = new System.Drawing.Point(((this.dataGridView1.GetCellDisplayRectangle(e.ColumnIndex,e.RowIndex,true).Right)-
(btn.Width)),
this.dataGridView1.GetCellDisplayRectangle(e.ColumnIndex,e.RowIndex,true).Y); //设置btn显示位置
//(this.dataGridView1.GetCellDisplayRectangle(e.ColumnIndex,e.RowIndex,true).Right)-(btn.Width)
//获取单元格方框右边位置减去btn的宽,得到btn在dataGridView1中的横坐标
//this.dataGridView1.GetCellDisplayRectangle(e.ColumnIndex,e.RowIndex,true).Y
//获取单元格的纵坐标并设为btn在dataGridView1中的纵坐标
}
}
void btn_Click(object sender, EventArgs e)
{
Form f = new Form();
f.ShowDialog(this.dataGridView1);
}
--------------------编程问答-------------------- 有点BUG
以下修正
private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex.Equals(this.dataGridView1.Columns["Company"].Index))
{
//this.dataGridView1.Controls.Clear(); 此处的清除控件应该放在CellLeave事件中处理
//
Button btn = new Button();
btn.Text = "...";
btn.Font = new Font("Arial", 7);
btn.Visible = true;
btn.Width = this.dataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true).Height;
btn.Height = this.dataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true).Height;
this.dataGridView1.Controls.Add(btn);
btn.Location = new System.Drawing.Point((this.dataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true)
.Right - btn.Width), this.dataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true).Y);
btn.Click += new EventHandler(btn_Click);
}
}
void btn_Click(object sender, EventArgs e)
{
Form f = new Form();
f.ShowDialog(this.dataGridView1);
}
private void dataGridView1_CellLeave(object sender, DataGridViewCellEventArgs e)
{
this.dataGridView1.Controls.Clear(); //清除集合中控件
} --------------------编程问答-------------------- 好贴! --------------------编程问答-------------------- butten 是能添加 但是如果主窗体变化 butten的位置怎么处理? --------------------编程问答-------------------- 当拖动滚动条的时候 问题完全暴漏了
补充:.NET技术 , C#