在Winforms DataGridView中,我该如何:
RowHeadersVisible = false
。答案 0 :(得分:5)
首先覆盖DataGridView称为
的函数private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
e.PaintHeader(DataGridViewPaintParts.All & ~DataGridViewPaintParts.ContentBackground);
}
在按钮上单击向行标题添加值
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();
}
答案 1 :(得分:1)
您是否仍需要排序但不显示箭头?
如果没有,只需将每列SortMode
设置为NotSortable
即可。
如果您需要排序但不显示箭头,请将列SortMode
设置为Programmatic
,然后在Click
或MouseDown
列事件中手动对数据源进行排序。
将列标题设置为您需要的任何文本后,使用表单Graphics
类获取文本的宽度,然后相应地设置列宽:
Graphics g = this.CreateGraphics();
int w = (int)g.MeasureString(dataGridView1.Columns[0].HeaderText, dataGridView1.Font).Width;
this.dataGridView1.Columns[0].Width = w;
答案 2 :(得分:0)
首先,如何在C#.Net 2.0及以上版本中将数字行RowHeadersWidth添加到DataGridView:
// 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();
}
现在,您可以根据其大小进行dinamically大小调整行标题,就像在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;
}
此解决方案仅适用于.Net Framework 2.0及更高版本,不适用于CF.