admin 管理员组

文章数量: 1086019


2024年3月19日发(作者:ajax获取json数据显示)

DataGridView 动态添加新行:

DataGridView控件在实际应用中非常实用,特别需要表格显示数据时。可以静态绑定数据源,这样就自

动为DataGridView控件添加相应的行。假如需要动态为DataGridView控件添加新行,方法有很多种,

下面简单介绍如何为DataGridView控件动态添加新行的两种方法:

方法一:

int index=();

[index].Cells[0].Value = "1";

[index].Cells[1].Value = "2";

[index].Cells[2].Value = "监听";

利用()事件为DataGridView控件增加新的行,该函数返回添加新行的索引

号,即新行的行号,然后可以通过该索引号操作该行的各个单元格,如

[index].Cells[0].Value = "1"。这是很常用也是很简单的方法。

方法二:

DataGridViewRow row = new DataGridViewRow();

DataGridViewTextBoxCell textboxcell = new DataGridViewTextBoxCell();

= "aaa";

(textboxcell);

DataGridViewComboBoxCell comboxcell = new DataGridViewComboBoxCell();

(comboxcell);

(row);

方法二比方法一要复杂一些,但是在一些特殊场合非常实用,例如,要在新行中的某些单元格添加下拉框、

按钮之类的控件时,该方法很有帮助。DataGridViewRow row = new DataGridViewRow();是创建

DataGridView的行对象,DataGridViewTextBoxCell是单元格的内容是个TextBox,

DataGridViewComboBoxCell是单元格的内容是下拉列表框,同理可知,DataGridViewButtonCell

是单元格的内容是个按钮,等等。textboxcell是新创建的单元格的对象,可以为该对象添加其属性。然

后通过(textboxcell)为row对象添加textboxcell单元格。要添加其他的单元格,用同

样的方法即可。最后通过(row)为dataGridView1控件添加新的行row。

DataGridView 取得或者修改当前单元格的内容:

当前单元格指的是 DataGridView 焦点所在的单元格,它可以通过 DataGridView 对象的

CurrentCell 属性取得。如果当前单元格不存在的时候,返回Nothing(C#是null)

// 取得当前单元格内容

ine();

// 取得当前单元格的列 Index

ine(Index);

// 取得当前单元格的行 Index

ine(ex);

另外,使用 tCellAddress 属性(而不是直接访问单元格)来确定单元格所在的

行: tCellAddress.Y

列:tCellAddress.X 。这对于避免取消共享行的共享非常有用。

当前的单元格可以通过设定 DataGridView 对象的 CurrentCell 来改变。可以通过 CurrentCell 来设

定DataGridView 的激活单元格。将 CurrentCell 设为 Nothing(null) 可以取消激活的单元格。

// 设定 (0, 0) 为当前单元格

tCell = DataGridView1[0, 0];

在整行选中模式开启时,你也可以通过 CurrentCell 来设定选定行。

/// 向下遍历

private void button4_Click(object sender, EventArgs e)

...{

int row = + 1;

if (row > nt - 1)

row = 0;

tCell = idView1[0, row];

}

/// 向上遍历

private void button5_Click(object sender, EventArgs e)

...{

int row = - 1;

if (row < 0)

row = nt - 1;

tCell = idView1[0, row];

}

* 注意: idView 的索引器的参数是: columnIndex, rowIndex 或是 columnName,

rowIndex

这与习惯不同。

DataGridView 设定单元格只读:

1) 使用 ReadOnly 属性

如果希望,DataGridView 内所有单元格都不可编辑, 那么只要:

// 设置 DataGridView1 为只读

ly = true;此时,用户的新增行操作和删除行操作也被屏蔽了。

如果希望,DataGridView 内某个单元格不可编辑, 那么只要:

// 设置 DataGridView1 的第2列整列单元格为只读

s[1].ReadOnly = true;


本文标签: 添加 控件 操作 新行 共享