动态添加列和行

方法一

通过手动添加Datatable,再绑定dataGridView

DataTable dt = new DataTable();//建立个数据表
dt.Columns.Add(new DataColumn("id", typeof(int)));//在表中添加int类型的列
dt.Columns.Add(new DataColumn("Name", typeof(string)));//在表中添加string类型的Name列
DataRow dr;//
for (int i = 0; i < 3; i++)
{
      dr = dt.NewRow();
      dr["id"] = i;
      dr["Name"] = "Name" + i;
      dt.Rows.Add(dr);//在表的对象的行里添加此行
}

dataGridView1.DataSource =dt;


如果要添加一个textbox效果的列,可做如下处理

dt.Columns.Add(new DataColumn("选中", typeof(bool));

 

方法二

直接在dataGridView中插入

dataGridView1.ColumnCount = 4;
dataGridView1.ColumnHeadersVisible = true;

// Set the column header style.
DataGridViewCellStyle columnHeaderStyle = new DataGridViewCellStyle();

columnHeaderStyle.BackColor = Color.Beige;
columnHeaderStyle.Font = new Font("Verdana", 10, FontStyle.Bold);
dataGridView1.ColumnHeadersDefaultCellStyle = columnHeaderStyle;

// Set the column header names.
dataGridView1.Columns[0].Name = "Recipe";
dataGridView1.Columns[1].Name = "Category";
dataGridView1.Columns[2].Name = "Main Ingredients";
dataGridView1.Columns[3].Name = "Rating";

// Populate the rows.
string[] row1 = new string[] { "Meatloaf", "Main Dish", "ground beef","**" };
string[] row2 = new string[] { "Key Lime Pie", "Dessert", "lime juice, evaporated milk", "****" };
string[] row3 = new string[] { "Orange-Salsa Pork Chops", "Main Dish", "pork chops, salsa, orange juice", "****" };
string[] row4 = new string[] { "Black Bean and Rice Salad", "Salad", "black beans, brown rice", "****" };
string[] row5 = new string[] { "Chocolate Cheesecake", "Dessert", "cream cheese", "***" };
string[] row6 = new string[] { "Black Bean Dip", "Appetizer", "black beans, sour cream", "***" };
object[] rows = new object[] { row1, row2, row3, row4, row5, row6 };

foreach (string[] rowArray in rows)
{
    dataGridView1.Rows.Add(rowArray);
}

 

插入DataGridViewCheckBoxColumn列

DataGridViewCheckBoxColumn column = new DataGridViewCheckBoxColumn();
{
  column.HeaderText = "选中";
  column.Name = isSelected;
  column.AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
  column.FlatStyle = FlatStyle.Standard;
  column.ThreeState = true;
  column.CellTemplate = new DataGridViewCheckBoxCell();
  column.CellTemplate.Style.BackColor = Color.Beige;
}
DataGridView1.Columns.Insert(
0, column);

 

DGV的常用属性设置

1. 禁用编辑功能

dataGridView1.ReadOnly = true ;

2.不让DataGridView自动生成列

只需要把属性AutoGenerateColumns设为false即可。
需要注意: 在界面设计的属性窗口中是看不到AutoGenerateColumns属性的,

需要在代码中设定,比如在窗口的构造函数中设定:dataGridView1.AutoGenerateColumns = false;

 

你们的评论、反馈,及对你们有所用,是我整理材料和博文写作的最大的鼓励和唯一动力。欢迎讨论和关注!
没有整理与归纳的知识,一文不值!高度概括与梳理的知识,才是自己真正的知识与技能。 永远不要让自己的自由、好奇、充满创造力的想法被现实的框架所束缚,让创造力自由成长吧! 多花时间,关心他(她)人,正如别人所关心你的。理想的腾飞与实现,没有别人的支持与帮助,是万万不能的。