datagridview绑定数据,同样可以文件读取数据、循环赋值添加到DataTable
private void datablind()
{
DataTable dt = new DataTable();
dt.Columns.Add("name");
dt.Columns.Add("sex");
dt.Columns.Add("age");
DataRow d1 = dt.NewRow();
d1[0] = "AIR";
d1[1] = "man";
d1[2] = 23;
dt.Rows.Add(d1);
DataRow d2 = dt.NewRow();
d2[0] = "Mike";
d2[1] = "man";
d2[2] = 25;
dt.Rows.Add(d2);
m_data.DataSource = dt;
}
datagridview内添加其他控件:
可添加Button -> DataGridViewButtonColumn;
CheckBox -> DataGridVieCheckBoxColum;
ComboBox ->DataGridVieComboBoxColum;
Image ->DataGridVieImageColum;
Link ->DataGridVieLinkColum;
TextBox ->DataGridVieTextBoxColum;
首先创建所需要控件属性列,然后创建相应控件属性Cell,添加数据到Items内,然后创建一个新行将cell加入,最后再将行加入datagridview内。
DataGridViewComboBoxColumn comboxCL1 = new DataGridViewComboBoxColumn();
comboxCL1.HeaderText = "name";
DataGridViewComboBoxColumn comboxCL2 = new DataGridViewComboBoxColumn();
comboxCL2.HeaderText = "sex";
DataGridViewComboBoxColumn comboxCL3 = new DataGridViewComboBoxColumn();
comboxCL3.HeaderText = "age";
m_data.Columns.AddRange(comboxCL1, comboxCL2, comboxCL3);
DataGridViewComboBoxCell c1 = new DataGridViewComboBoxCell(); c1.Items.Add("AIR"); c1.Items.Add("Mike"); c1.Items.Add("Luce"); DataGridViewComboBoxCell c2 = new DataGridViewComboBoxCell(); c2.Items.Add("man"); c2.Items.Add("man"); c2.Items.Add("woman"); DataGridViewComboBoxCell c3 = new DataGridViewComboBoxCell(); c3.Items.Add(23); c3.Items.Add(25); c3.Items.Add(21);
DataGridViewRow r1 = new DataGridViewRow(); r1.Cells.Add(c1); r1.Cells.Add(c2); r1.Cells.Add(c3); m_data.Rows.Add(r1);
datagridview单元格属性DefaultCellStyle
内含背景颜色BackColor,字体Font,字体颜色ForeColor,选中时背景颜色SelectionBackColor,选中时字体颜色SelectionForeColor,布局Alignment,是否换行WrapMode,格式Format。
m_data.DefaultCellStyle.Alignment = DataGridViewContentAlignment.BottomCenter;
m_data.DefaultCellStyle.WrapMode = DataGridViewTriState.True;
datagridview常用属性:
允许用户添加行AllowUserToAddRows;
允许用户删除行AllowUserToDeleteRows;
单元格是否可编辑ReadOnly;
自动调整大小AutoSize;
自动调节列宽度AutoSizeColumnsMode;
自动调节行高度AutoSizeRowsMode;
选择模式SelectionMode;