在datagridview当鼠标移到某行时,该行改变颜色 Winform: DataGridView属性中有个SelectMode之类的属性,可以设定是选择单元格还是选择行。 在DataGirdView属性中还有DefaultCellStyle之类的属性,可以设定选中时的背景色、字体颜色等。
private void dataGridView1_CellMouseEnter(object sender, DataGridViewCellEventArgs e) //鼠标移动到某行时更改背景色 { if (e.RowIndex >= 0) { dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.LightBlue; } } private void dataGridView1_CellMouseLeave(object sender, DataGridViewCellEventArgs e) //鼠标移开时还原背景色 { if (e.RowIndex >= 0) { dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.White; } } /// <summary> /// 鼠标移动事件处理 /// </summary> /// <param name= "sender "> </param> /// <param name= "e "> </param> private void dataGridView1_MouseMove(object sender, MouseEventArgs e) { DataGridView.HitTestInfo hti = this.dataGridView1.HitTest(e.X, e.Y); //如果坐标在单元格内 if (hti.Type == DataGridViewHitTestType.Cell) { //取消选择所有的选定单元格 this.dataGridView1.ClearSelection(); // 设置控件内所有行的颜色 for (int i = 0; i < this.dataGridView1.Rows.Count; i++) { this.dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.White; if (i % 2 == 0) { this.dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.FromArgb(224, 224, 224); } else { this.dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.FromArgb(192, 192, 192); } if (this.dataGridView1.RowCount > hti.RowIndex) { //设置控件内鼠标移动到的颜色 this.dataGridView1.Rows[hti.RowIndex].DefaultCellStyle.BackColor = Color.FromArgb(255, 255, 192) } } } } private void Form1_Load(object sender, EventArgs e) { //设置奇偶行颜色 dataGridView1.RowsDefaultCellStyle.BackColor = Color.White; dataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.Beige; //设置奇偶行选中的颜色 dataGridView1.DefaultCellStyle.SelectionBackColor = Color.White dataGridView1.AlternatingRowsDefaultCellStyle.SelectionBackColor = Color.Beige; } asp.net protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { int i; //执行循环,保证每条数据都可以更新 for (i = 0; i < GridView1.Rows.Count; i++) { //首先判断是否是数据行 if (e.Row.RowType == DataControlRowType.DataRow) { //当鼠标停留时更改背景色 e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#00A9FF'"); //当鼠标移开时还原背景色 e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c"); } } }

473

被折叠的 条评论
为什么被折叠?



