DataGridView控件1——手动添加数据,遍历数据
DataGridView控件
用于网格形式显示数据,行和列由用户自定义。
应用,显示数据,管理数据,操作数据
DataGridView的组成:行,列,单元格
行:DataGridViewRow,DataGridViewRowCollection,Rows
列:DataGridViewColumn,DataGridViewColumnCollection,Columns
FillWeight,ColumnType,Name,DataPropertyName,HeaderText,ReadOnly,Visible
单元格:DataGridViewCell,Value,Selected,RowIndex,ColumnIndex,FormattedValue
DataGridView常用属性:
AllowUserToAddRows
AllowUserToDeleteRows
AutoSizeColumnMode
ColumnHeadersHight
ColumnHeadersVisible
Columns
DataSource 数据源——DataTable或List集合
EnableHeaderVisualStyle
MultiSelect
RowHeadersVisible
SelectionMode
知识点1:
手动添加空行,手动添加一行数据,遍历行数据(无数据源)
代码如下:
using System; using System.Windows.Forms; namespace ControlsTest { public partial class FormDataGridView : Form { public FormDataGridView() { InitializeComponent(); } private void btnAdd_Click(object sender, EventArgs e) { //添加一个空行 dgv1.Rows.Add();//方法1 dgv1.AllowUserToAddRows = true;//方法2 } private void btnAddData_Click(object sender, EventArgs e) { //代码添加一行数据 //方法1 dgv1.Rows.Add(new object[] { 1000, "黎明", true, "12345678" }); //方法2 DataGridViewRow row = new DataGridViewRow(); DataGridViewCell cell0 = new DataGridViewTextBoxCell(); cell0.Value = 1001; DataGridViewCell cell1 = new DataGridViewTextBoxCell(); cell1.Value = "王强"; DataGridViewCell cell2 = new DataGridViewCheckBoxCell(); cell2.Value = false; DataGridViewCell cell3 = new DataGridViewTextBoxCell(); cell3.Value = "87654321"; row.Cells.AddRange(cell0, cell1, cell2, cell3); dgv1.Rows.Add(row); } private void btnGet_Click(object sender, EventArgs e) { //遍历行,获取行中单元格的数据 foreach (DataGridViewRow row in dgv1.Rows) { int id = int.Parse(row.Cells[0].Value.ToString()); string name = row.Cells[1].Value.ToString(); bool state = Convert.ToBoolean(row.Cells[2].Value); string phone = row.Cells[3].Value.ToString(); MessageBox.Show(id.ToString() + name + state.ToString() + phone); } } } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?