滚动条时的C#复选框标题问题
Posted
技术标签:
【中文标题】滚动条时的C#复选框标题问题【英文标题】:C# checkbox header issue when scroll the bar 【发布时间】:2021-11-28 02:31:07 【问题描述】:我有一个包含多列的 datagridview,并且我在其中一个列标题中创建了一个自定义复选框。由于我想在滚动条时修复列中的复选框标题,所以我创建了“滚动”事件来处理它。
private void dataGridView1_Scroll(object sender, ScrollEventArgs e)
if (e.ScrollOrientation == ScrollOrientation.HorizontalScroll)
chbx.Location = new Point(chbx.Location.X - (e.NewValue - e.OldValue), chbx.Location.Y);
if (chbx.Location.X < dataGridView1.Location.X)
chbx.Visible = false;
else
chbx.Visible = true;
它的作品(图1)。但是,当我单击刷新按钮(gridview 中的数据刷新)并再次滚动条时,出现以下问题(图 2)。
Picture 1
Picture 2.
private void btnRefresh_Click(object sender, EventArgs e)
dataGridView1.DataSource = null;
SetupDGV();
private void SetupDGV()
///.....
chbx = new CheckBox();
Point headerCellLocation = dataGridView1.GetCellDisplayRectangle(0, -1, true).Location;
chbx.Name = "enableCHBX";
chbx.Location = new Point(headerCellLocation.X + 60, headerCellLocation.Y + 8);
chbx.BackColor = Color.White;
chbx.Size = new Size(15, 15);
// Assign Click event to the Header CheckBox.
cbx.Click += new EventHandler(chbxEnable_Click);
dataGridView1.Controls.Add(chbx);
对此有何建议?
【问题讨论】:
列数改变还是网格宽度改变?它是否创建了一个重复的复选框,因为您没有擦除dataGridView1.Controls
集合并删除您创建的 chkbx
?
【参考方案1】:
我已删除 dataGridView1_Scroll
事件处理程序。
相反,我使用了Paint
事件:this.dataGridView1.Paint += this.Handle_Paint;
在Paint Event Handler
里面我有以下代码:
private void Handle_Paint(object sender, PaintEventArgs e)
//// Get the header cell
var cell = this.dataGridView1.Columns[0].HeaderCell;
//// Get the Location
var headerCellLocation = dataGridView1.GetCellDisplayRectangle(0, -1, true).Location;
//// Get the Horizontal Scrolling Offset (if the User has scrolled)
var scrollOffset = this.dataGridView1.HorizontalScrollingOffset;
//// Get the Cell width (minus) the checkbox width (minus) any scrolling there is
var widthVal = cell.Size.Width - this.chbx.Size.Width - scrollOffset;
//// Get 1/4 of the Cells height (so the checkbox sits in the center)
var quarterCellHeight = cell.Size.Height / 4;
//// Calculate the new Location for the Checkbox
var newLocation = new Point(headerCellLocation.X + widthVal, headerCellLocation.Y + quarterCellHeight);
//// Update the Location
this.chbx.Location = newLocation;
我还在SetupDGV
方法中添加了以下if
语句:
if (this.dataGridView1.Controls.Contains(this.chbx))
this.dataGridView1.Controls.Remove(this.chbx); //// Remove so we don't have a duplicate
这确保我们在刷新网格数据时不会在 dataGridView 内创建重复的复选框。
这是一个简短的结果视频: https://gyazo.com/e544b38b1ca065bb16e4f279fc5aa24e
【讨论】:
以上是关于滚动条时的C#复选框标题问题的主要内容,如果未能解决你的问题,请参考以下文章