目录
一、给列表增加按钮,打印实体信息
二、嵌套子窗体
一、给列表增加按钮,打印实体信息
private void button1_Click(object sender, EventArgs e)
{
List<Student> studentList = new List<Student>()
{
new Student() { Id = 1, Name = "John" },
new Student() { Id = 2, Name = "Emily" },
new Student() { Id = 3, Name = "Michael" }
};
// 创建一个 DataGridViewButtonColumn 对象(按钮对象)
DataGridViewButtonColumn buttonColumn = new DataGridViewButtonColumn();
DataGridViewButtonColumn buttonColumn2 = new DataGridViewButtonColumn();
buttonColumn.HeaderText = "Action"; // 设置列标题
buttonColumn.UseColumnTextForButtonValue = true;
buttonColumn.Text = "Complete";//设置按钮名称
dataGridView1.DataSource = studentList;//添加列表
dataGridView1.Columns.Add(buttonColumn);//添加按钮
dataGridView1.Columns.Add(buttonColumn2);//添加按钮
dataGridView1.CellContentClick += DataGridView1_CellContentClick;//按钮触发对应方法
}
private void DataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
// 获取点击按钮所在行的数据
var student = dataGridView1.Rows[e.RowIndex].DataBoundItem as Student;
// 打印学生信息
if (e.ColumnIndex==2)//判断按钮列数
{
MessageBox.Show($"点击了Complete按钮,学生Id: {student.Id},姓名:{student.Name}");
}
}
效果:
二、嵌套子窗体
private void button2_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
panel1.Controls.Clear();//清空旧控件
form2.TopLevel = false;//嵌入模式
form2.Parent = panel1;//转移控件
form2.Dock = DockStyle.Fill;//转移控件
form2.FormBorderStyle= FormBorderStyle.None;//不显示标题栏
form2.Show();
}