datagridview
第一种绑定datatable
初始化
dgv.Columns.Clear();
dgv.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
new DataGridViewTextBoxColumn(),
new DataGridViewTextBoxColumn()
});
dgv.Columns[0].HeaderText = "类目";
dgv.Columns[0].DataPropertyName = "Name";//这地方的字符串对应datatable中的列名
dgv.Columns[0].Width = 128;
dgv.Columns[0].ReadOnly = true;
dgv.Columns[1].HeaderText = "出现频率";
dgv.Columns[1].DataPropertyName = "Value";//这地方的字符串对应datatable中的列名
dgv.Columns[1].Width = 100;
dgv.Columns[1].ReadOnly = true;
开始绑定
DataTable dt = new DataTable();
dt.Columns.Add("Name");
dt.Columns.Add("Value");
dt.Rows.Clear();
DataRow dr = dt.NewRow();
dr["Name"] = "a";
dr["Value"] = "leiArray";
dt.Rows.Add(dr);
dgv.DataSource = dt;
第二种 直接给datagridview添加行
初始化
private void ssss()
{
dgv.Columns.Clear();
dgv.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
new DataGridViewTextBoxColumn(),
new DataGridViewTextBoxColumn(),
new DataGridViewTextBoxColumn()
});
dgv.Columns[0].HeaderText = "序号";
dgv.Columns[0].Width = 70;
dgv.Columns[0].ReadOnly = true;
dgv.Columns[1].HeaderText = "标题";
dgv.Columns[1].Width = 100;
dgv.Columns[1].ReadOnly = true;
dgv.Columns[2].HeaderText = "URL";
dgv.Columns[2].Visible = true;
dgv.RowCount = 1;
添加行
private void button1_Click(object sender, EventArgs e)
{
DataGridViewRow dr = new DataGridViewRow();
foreach (DataGridViewColumn c in this.dgv.Columns)
{
dr.Cells.Add(c.CellTemplate.Clone() as DataGridViewCell); //给行添加单元格
}
dr.Cells[1].Value = "1111";
dr.Cells[2].Value = "3333";
this.dgv.Rows.Add(dr);
}