DataGridView控件的应用和问题总结
1.在DataGridView 中通过遍历每一行的指定单元格
foreach (DataGridViewRow row in this.dgvBookList.Rows)
{
if (row.Cells["BarCode"].Value.ToString() == this.txtBarCode.Text.Trim())
{
row.Cells["BookCount"].Value = Convert.ToInt32(row.Cells["BookCount"].Value) + Convert.ToInt32(this.txtAddCount.Text.Trim());
this.dgvBookList.Refresh();
}
}
2.DataGridView SelectedRow 和 CurrentRow属性区别
用SelectedRows时必须 单击该行最前面的的方格而不能点击表格里有数据的单元格。
用CurrentRow时点哪都行。
SelectedRows表示的是你在DataGridView中所选择的行,其中Count属性是表示的选择的行数
CurrentRow表示的就是你所选择的当前行,只有一行
Rows表示的是DataGridView中所有的行数
3.DateGridView SelectionChanged事件
(1)注意 每当加载DataGridView列表时都会触发多次SelectionChanged事件,导致无故发生异常
(2)解决方案
在加载DataGridView前,先将事件与事件方法断开
this.dgvBookList.SelectionChanged -= new EventHander(this.dgvBookList_SelectionChanged);
加载DataGridView
在加载晚DataGridView后将SelectionChanged事件与方法开启关联
this.dgvBookList.SelectedChanged += new EventHander(this.dgvBookList_SelectionChanged);//只开启关联会发现加载后DataGridView不会刷新
调用一次SelectionChanged方法
dgvBookList_SelectionChanged(null,null);
(3)注意,当删除dgv的某一行时也会触发SelectionChanged事件
4.当对数据库修改信息后,DataGridView同步刷新
//(objStu与List集合里目标对象是同一个地址,所有objStu就是目标对象)
int objStudentId = Convert.ToInt32(this.lbStudentId.Text.Trim());
foreach(Student objStu in this.studentList)
{
if(objStu.StudentId == objStudentId)
{
objStu.StudentName = this.txtStudentName.Text.Trim();
objStu.StudentAddress = this.txtStudentAddress.Text.Trim();
}
}
this.dgvStudentInfo.Reflush();//修改可以通过Reflush方法刷新
5.加粗显示相关的借书数据
this.dgvNonReturnList.Columns["BorrowCount"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
this.dgvNonReturnList.Columns["BorrowCount"].DefaultCellStyle.Font = new Font("微软雅黑",14);