datagridview是winform中的表格控件,在其属性中可以调整关于列的数目,列的名称以及字体颜色,是否可编辑等内容,具体可以在属性里面看,那里说明的也比较通俗易懂。我分享一下关于添加数据和删除数据的一些经验技巧
首先得在项目里先添加一个代码文件,定义数据类型,比如
private void AddRow(Student stu)
{
object[] row =
{
stu.Id ,
stu.Name,
stu.Sex ? "男" : "女",
stu.Phone
};
grid.Rows.Add(row);
}
private void addBtn_Click(object sender, EventArgs e)
{
object[] row = new object[4];
row[0] = 20201004;
row[1] = "zhang";
row[2] = "男";
row[3] = "13899990000";
grid.Rows.Add(row);
}
先说一下怎么样通过代码对列进行设置
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
InitGridView();
}
private void InitGridView()
{
// 列的设置
this.grid.ColumnCount = 4;
grid.Columns[0].Name = "学号";
grid.Columns[1].Name = "姓名";
grid.Columns[2].Name = "性别";
grid.Columns[3].Name = "手机号";
AddRow(new Student(20201001, "shao", true, "13810012345"));
AddRow(new Student(20201002, "li", false, "13610022349"));
AddRow(new Student(20201003, "wang", true, "13810087282"));
}
通过这种方式可直接设置列
添加操作
private void addBtn_Click(object sender, EventArgs e)
{
object[] row = new object[4];
row[0] = 20201004;
row[1] = "zhang";
row[2] = "男";
row[3] = "13899990000";
grid.Rows.Add(row);
}
其中grid为表格名称
删除操作
private void deleteBtn_Click(object sender, EventArgs e)
{
// 单项删除
// grid.Rows.RemoveAt(0);
// 多项删除
foreach (DataGridViewRow row in grid.SelectedRows)
{
grid.Rows.Remove(row);
}
}