Skip to content

DataGridView 使用笔记

1. 绑定DataTable数据源:

this.dataGridView1.Columns[0].DataPropertyName = "medalname";
this.dataGridView1.Columns[1].DataPropertyName = "availablecount";
this.dataGridView1.Columns[2].DataPropertyName = "takencount";
this.dataGridView1.Columns[3].DataPropertyName = "usedcount";
this.dataGridView1.Columns[4].DataPropertyName = "bannedcount";
this.dataGridView1.Columns[5].DataPropertyName = "phonecount";
this.dataGridView1.AutoGenerateColumns = false;
this.dataGridView1.DataSource = dt; //dt是一个DataTable

2. 按条件设置某一单元格背景及文字颜色

//当第3列的值大于2时置为红底白字,否则白底黑字
for (int i = 0; i < this.dataGridView1.Rows.Count;i++ )
{
	DataGridViewCell cell = this.dataGridView1.Rows[i].Cells[2];
	if (Convert.ToInt32(cell.Value) > 0)
	{
		cell.Style.BackColor = Color.Red;
		cell.Style.ForeColor = Color.White;
	}
	else
	{
		cell.Style.BackColor = Color.White;
		cell.Style.ForeColor = Color.Black;
	}
}

3. 选中整行:

把DataGridView的SelectionMode属性改为FullRowSelect

4.取消Row Header:

把DataGridView的RowHeadersVisible属性改为False

5. 取消多行选择:

把MultiSelect属性改为False

6. 禁止所有选择:

this.dataGridView1.SelectionChanged += new System.EventHandler(this.dataGridView1_SelectionChanged);
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
	this.dataGridView1.ClearSelection();
}

7. 列填充整个GridView

AutoSizeColumnsMode改为Fill

8. 禁止空行

AllowUserToAddRows改为False

0 0 votes
Article Rating
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x