[英]Adjusting Rowheader properties on Datagridview
In Winforms DataGridView, how do I:在 Winforms DataGridView 中,我如何:
RowHeadersVisible = false
.我需要显示行标题文本,所以我不能简单地设置RowHeadersVisible = false
。First of all override the function the DataGridView known as首先覆盖称为 DataGridView 的函数
private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
e.PaintHeader(DataGridViewPaintParts.All & ~DataGridViewPaintParts.ContentBackground);
}
On button click add value to row header在按钮上单击将值添加到行标题
private void button1_Click(object sender, EventArgs e)
{
string a = "khan yousafzai";
dataGridView1.RowHeadersWidth = dataGridView1.RowHeadersWidth +(7* a.Length);
dataGridView1.Rows[0].HeaderCell.Value = a;
dataGridView2.Rows.Add();
}
Do you need to still allow sorting but not show the arrow?您是否仍然需要允许排序但不显示箭头? If not, just set each column SortMode
to NotSortable
.如果没有,只需将每列SortMode
设置为NotSortable
。 If you need to sort but not show the arrow, set the column SortMode
to Programmatic
, and manually sort the data source in the column Click
or MouseDown
event.如果需要排序但不显示箭头,将列SortMode
设置为Programmatic
,在Click
或MouseDown
事件列中手动对数据源进行排序。
After you set the column header to whatever text you need, get the width of the text using the form Graphics
class and then set the column width accordingly:将列标题设置为您需要的任何文本后,使用表单Graphics
类获取文本的宽度,然后相应地设置列宽:
Graphics g = this.CreateGraphics(); int w = (int)g.MeasureString(dataGridView1.Columns[0].HeaderText, dataGridView1.Font).Width; this.dataGridView1.Columns[0].Width = w;
First of all, how to add number line RowHeadersWidth to DataGridView in C# .Net 2.0 and above:首先,如何在C#.Net 2.0及以上的DataGridView中添加数行RowHeadersWidth:
// On Form_Load add the numeration to DataGridView Row Header
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
dataGridView1.Rows[i].HeaderCell.Value = (i + 1).ToString();
}
Now, you can resize our row header dynamically depending of its size, just like in Microsoft Excel.现在,您可以根据行标题的大小动态调整行标题的大小,就像在 Microsoft Excel 中一样。
// Dinamically adjust row header size to max current width available (like Microsoft Excel does)
private void dataGridView1_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
{
int firstDisplayedCellIndex = dataGridView1.FirstDisplayedCell.RowIndex;
int lastDisplayedCellIndex = firstDisplayedCellIndex + dataGridView1.DisplayedRowCount(true);
Graphics Graphics = dataGridView1.CreateGraphics();
int measureFirstDisplayed = (int)(Graphics.MeasureString(firstDisplayedCellIndex.ToString(), dataGridView1.Font).Width);
int measureLastDisplayed = (int)(Graphics.MeasureString(lastDisplayedCellIndex.ToString(), dataGridView1.Font).Width);
int rowHeaderWitdh = System.Math.Max(measureFirstDisplayed, measureLastDisplayed);
dataGridView1.RowHeadersWidth = rowHeaderWitdh + 35;
}
This solution its only for .Net Framework 2.0 and above, not for CF.此解决方案仅适用于 .Net Framework 2.0 及更高版本,不适用于 CF。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.