DataGridVIew中的常量值

时间:2015-06-10 09:43:33

标签: visual-studio-2010 visual-studio datagridview

我有一个包含3列的DataGridView。 我需要前两列保持不变,这些列必须始终相同,用户将无法为这些列输入不同的值。

DGV的两个第一列的值在textBox1和textBox2中。

我需要当用户要在DGV中添加新行时,前两列会自动填充这些常量值,并将焦点设置为第三列。

提前致谢

1 个答案:

答案 0 :(得分:1)

如果您不希望用户编辑前两列,只需将其ReadOnly属性设置为true:

this.dataGridView1.Columns[0].ReadOnly = true;

至于您的其他条件,首先设置以下属性以限制添加新行的时间(例如,单击按钮):

this.dataGridView1.AllowUserToAddRows = false;

然后创建自己的方法以在需要时添加新行:

private void AddNewRow()
{
    DataGridViewRow row = new DataGridViewRow();
    row.CreateCells(this.dataGridView1);
    row.Cells[0].Value = this.textBox1.Text;
    row.Cells[1].Value = this.textBox2.Text;
    this.dataGridView1.CurrentCell = row.Cells[2];
    this.dataGridView1.BeginEdit(true);
}

从技术上讲,您可以在AllowUserToAddRows == true处理DataGridView.RowsAdded事件并略微修改上述代码时执行此操作,但只要您输入一个字符,就会产生烦人的行为新行,第3列,另一个新行被添加,编辑单元失去焦点(可能在你实际输入任何有用的东西之前)。