Pet*_*Lee 5 c# truncate datagridview
我有一个关于单元格截断的问题(替换为“...”):
列右对齐时如何在单元格左侧显示替换“...”?
我使用的是非等宽字体,所以我不能只计算字符来做一些字符串操作作为一种解决方法,我需要一个解决方案。我相信应该有。
为了说明我的问题,我在这里模拟我的 DataGridView
Left Context (Right aligned column) | Center Word | Right Context (Left aligned column)
left context not truncated | CenterWord | Right context not truncated
...Here is the long left context truncated | CenterWord | Here is the long right context truncated...
Run Code Online (Sandbox Code Playgroud)
我想我已经说清楚了。
谢谢。请帮帮我。
彼得
PS:同样的问题可以在这个链接找到:http : //objectmix.com/csharp/341736-datagridview-cell-format-question.html
这绝对是一件不寻常的事情——但是(就像其他事情一样)它是可以做到的。这是测量绳子的大小并将其与细胞的大小进行比较的问题。(请注意,我假设数据是由用户输入的。如果您进行数据绑定,则基本上必须使用其他事件。)
这可行,但可能需要一些微调:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
dataGridView1.Columns.Add("col1", "col1");
dataGridView1.Columns[0].CellTemplate.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
dataGridView1.Columns.Add("col2", "col2");
dataGridView1.Columns.Add("col3", "col3");
dataGridView1.Rows.Add();
dataGridView1.CellEndEdit += new DataGridViewCellEventHandler(dataGridView1_CellEndEdit);
dataGridView1.ColumnWidthChanged += new DataGridViewColumnEventHandler(dataGridView1_ColumnWidthChanged);
}
void dataGridView1_ColumnWidthChanged(object sender, DataGridViewColumnEventArgs e)
{
if (e.Column.Index == 0)
{
// We need to truncate everything again when the width changes
foreach (DataGridViewRow row in dataGridView1.Rows)
{
RightTruncateText(row.Cells[0]);
}
}
}
void RightTruncateText(DataGridViewCell cell)
{
// check if the content is too long:
using (Graphics g = Graphics.FromHwnd(this.Handle))
{
SizeF size = g.MeasureString((string)cell.Tag, dataGridView1.Font); // NOTE: using the tag
if (size.Width > cell.Size.Width)
{
StringBuilder truncated = new StringBuilder((string)cell.Tag);
truncated.Insert(0, "...");
// Truncate the string until small enough (NOTE: not optimized in any way!)
while (size.Width > cell.Size.Width)
{
truncated.Remove(3, 1);
size = g.MeasureString(truncated.ToString(), dataGridView1.Font);
}
cell.Value = truncated.ToString();
}
else
{
cell.Value = cell.Tag;
}
}
}
void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 0)
{
// Save the value in the tag but show the truncated value
DataGridViewCell cell = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
cell.Tag = cell.Value; // Saving the actual state
RightTruncateText(cell);
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5816 次 |
| 最近记录: |