DataGridView空白的部分显示网格

因为数据绑定之后不能添加空行,所以应该分二种情况,绑定的数据行不够的时候,只能先在数据源中添加空行然后绑定数据。如果数据源为空即没有绑定时,直接添加空行。

dataGridView1.Rows.GetRowsHeight(DataGridViewElementStates.Visible)第一次执行将取道的值是0,而不是实际行高(因为行还没有显示),当显示后取到的是所有可视的行高,也就是所有可见行的总和。如果将行设置为不可调整则可以用

dataGridView1.RowTemplate.Height 取得行高(因为实际就是我们设计时看到的行高)

private void Bind()

{

this.dataGridView1.AutoGenerateColumns = false;

this.dataGridView1.ReadOnly = true;

this.dataGridView1.AllowUserToAddRows = false;

int i = this.dataGridView1.ColumnHeadersHeight;//标题行高

//int j = this.dataGridView1.Rows.GetRowsHeight(DataGridViewElementStates.Visible);

int j=this.dataGridView1.RowTemplate.Height;
int k = this.dataGridView1.Height;//控件高度

int EmptyCount = (k - i - j) / j;

DataTable Users = //;

if (Users != null)

{

if (Users .Rows.Count < EmptyCount)

{

for (int m = 0; m < EmptyCount; m++)

{

Users .Rows.Add(PatientContact.NewRow());

}

}

this.dataGridView1.DataSource = Users ;

}

else if (k > i + j)

{

for (int m = 0; m < EmptyCount; m++)

{

DataGridViewRow newrow = new DataGridViewRow();

this.dataGridView1.Rows.Add(newrow);

}

}

}

原文地址:https://www.cnblogs.com/dyufei/p/2573937.html