1.表格名称:dgv;操作列名称:ColOperate
2.相关代码如下:
private void Load(object sender, EventArgs e)
{
//初始化调用 前提是表格先填充好数据
//循环遍历添加每行的控件
for (int i = 0;i < dgv.Rows.Count; i++)
{
MulAutoBtnEdit(i);
}
}
/// <summary>
/// 绘制单元格内的控件
/// </summary>
/// <param name="rowIndex"></param>
private void MulAutoBtnEdit(int rowIndex)
{
int index = this.dgv.Columns["ColOperate"].Index;
Label btnAdd = GetBtnByType("BtnAdd", "新增", rowIndex);
Label btnEdit = GetBtnByType("BtnEdit", "修改", rowIndex);
Label btnDel = GetBtnByType("BtnDel", "删除", rowIndex);
this.dgv.Controls.Add(btnAdd);
this.dgv.Controls.Add(btnEdit);
this.dgv.Controls.Add(btnDel);
Rectangle rectangle = this.dgv.GetCellDisplayRectangle(index, rowIndex, true);//获取当前单元格上的矩形区域
btnAdd.Size = btnEdit.Size = btnDel.Size = new Size(rectangle.Width / 3 + 1, rectangle.Height);
btnAdd.Location = new Point(rectangle.Left, rectangle.Top+5);
btnEdit.Location = new Point(rectangle.Left + btnAdd.Width, rectangle.Top+5);
btnDel.Location = new Point(rectangle.Left + btnAdd.Width + btnDel.Width, rectangle.Top+5);
}
/// <summary>
/// 封装需要显示的控件
/// </summary>
/// <param name="strBtnName"></param>
/// <param name="strBtnText"></param>
/// <param name="rowIndex"></param>
/// <returns></returns>
private Label GetBtnByType(string strBtnName, string strBtnText,int rowIndex)
{
Label lab = new Label();
lab.Name = strBtnName;
lab.Text = strBtnText;
lab.ForeColor = strBtnName== "BtnDel"? Color.Red: Color.FromArgb(64, 158, 255);
lab.BackColor= Color.Transparent;
lab.Cursor= Cursors.Hand;
lab.Tag= rowIndex.ToString();
lab.AutoSize= true;
lab.Click += lab_Click;
return lab;
}
/// <summary>
/// 控件对应的点击事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void lab_Click(object sender, EventArgs e)
{
if (sender is Label)
{
Label btn = (Label)sender;
int index=Convert.ToInt32(btn.Tag);
F101_UserInfoModel uInfo= dgv.Rows[index].DataBoundItem as F101_UserInfoModel;
MessageBox.Show(string.Format("{0}{1}的数据", btn.Text,uInfo.UserName));
}
}