是否可以拥有多行 DataGridView 单元格而不换行文本?

2024-01-12

我知道我可以设置WrapMode为真DefaultCellStyle of the RowTemplate,但这并没有给我我想要的行为。我在每个单元格中显示字符串列表,因此我希望识别回车符,但我不希望长项目换行中的文本。

有谁知道是否可以实现这一目标?


I hope this is what you are looking for: Screen shot

我使用了两个事件:

  1. 我在单元格编辑后测量了高度。
  2. 我在绘制单元格时测量了文本,并根据需要修剪它,然后重复直到它适合。

Code:

public partial class Form1 : Form
{
    private readonly int _rowMargins;

    public Form1()
    {
        InitializeComponent();
        int rowHeight = dataGridView1.Rows[0].Height;
        _rowMargins = rowHeight - dataGridView1.Font.Height;
    }

    private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
    {
        DataGridView view = sender as DataGridView;
        DataGridViewCell cell = view.Rows[e.RowIndex].Cells[e.ColumnIndex];
        string text = string.Format("{0}", cell.FormattedValue);
        if (!string.IsNullOrEmpty(text))
        {
            Size size = TextRenderer.MeasureText(text, view.Font);
            view.Rows[e.RowIndex].Height = Math.Max(size.Height + _rowMargins, view.Rows[e.RowIndex].Height);
        }
    }

    private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
    {
        if (e.ColumnIndex == -1 || e.RowIndex == -1)
        {
            return;
        }
        e.Paint(e.ClipBounds, DataGridViewPaintParts.All ^ DataGridViewPaintParts.ContentForeground);

        DataGridView view = sender as DataGridView;

        string textToDisplay = TrimTextToFit(string.Format("{0}", e.FormattedValue), (int) (e.CellBounds.Width * 0.96), view.Font);

        bool selected = view.Rows[e.RowIndex].Cells[e.ColumnIndex].Selected;
        SolidBrush brush = new SolidBrush(selected ? e.CellStyle.SelectionForeColor : e.CellStyle.ForeColor);

        e.Graphics.DrawString(textToDisplay, view.Font, brush, e.CellBounds.X, e.CellBounds.Y + _rowMargins / 2);

        e.Handled = true;
    }

    private static string TrimTextToFit(string text, int contentWidth, Font font)
    {
        Size size = TextRenderer.MeasureText(text, font);

        if (size.Width < contentWidth)
        {
            return text;
        }

        int i = 0;
        StringBuilder sb = new StringBuilder();
        while (i < text.Length)
        {
            sb.Append(text[i++]);
            size = TextRenderer.MeasureText(sb.ToString(), font);

            if (size.Width <= contentWidth) continue;

            sb.Append("...");

            while (sb.Length > 3 && size.Width > contentWidth)
            {
                sb.Remove(sb.Length - 4, 1);
                size = TextRenderer.MeasureText(sb.ToString(), font);
            }

            while (i < text.Length && text[i] != Environment.NewLine[0])
            {
                i++;
            }
        }
        return sb.ToString();
    }

}

Enjoy,
Ofir

设计师代码:

partial class Form1
{
    /// <summary>
    /// Required designer variable.
    /// </summary>
    private System.ComponentModel.IContainer components = null;

    /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
    protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        base.Dispose(disposing);
    }

    #region Windows Form Designer generated code

    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
        this.dataGridView1 = new System.Windows.Forms.DataGridView();
        this.LineNumber = new System.Windows.Forms.DataGridViewTextBoxColumn();
        this.Content = new System.Windows.Forms.DataGridViewTextBoxColumn();
        ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
        this.SuspendLayout();
        // 
        // dataGridView1
        // 
        this.dataGridView1.AllowUserToDeleteRows = false;
        this.dataGridView1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) 
        | System.Windows.Forms.AnchorStyles.Left) 
        | System.Windows.Forms.AnchorStyles.Right)));
        this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
        this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
        this.LineNumber,
        this.Content});
        this.dataGridView1.Location = new System.Drawing.Point(13, 13);
        this.dataGridView1.Name = "dataGridView1";
        this.dataGridView1.RowHeadersWidth = 55;
        this.dataGridView1.RowTemplate.DefaultCellStyle.WrapMode = System.Windows.Forms.DataGridViewTriState.False;
        this.dataGridView1.Size = new System.Drawing.Size(493, 237);
        this.dataGridView1.TabIndex = 0;
        this.dataGridView1.CellEndEdit += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellEndEdit);
        this.dataGridView1.CellPainting += new System.Windows.Forms.DataGridViewCellPaintingEventHandler(this.dataGridView1_CellPainting);
        // 
        // LineNumber
        // 
        this.LineNumber.FillWeight = 30F;
        this.LineNumber.Frozen = true;
        this.LineNumber.HeaderText = "#";
        this.LineNumber.MaxInputLength = 3;
        this.LineNumber.Name = "LineNumber";
        this.LineNumber.ReadOnly = true;
        this.LineNumber.Resizable = System.Windows.Forms.DataGridViewTriState.False;
        this.LineNumber.Width = 30;
        // 
        // Content
        // 
        this.Content.HeaderText = "Content";
        this.Content.Name = "Content";
        // 
        // Form1
        // 
        this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.ClientSize = new System.Drawing.Size(518, 262);
        this.Controls.Add(this.dataGridView1);
        this.Name = "Form1";
        this.Text = "Is it possible to have Multi-line DataGridView cells without wrapping text?";
        ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
        this.ResumeLayout(false);

    }

    #endregion

    private System.Windows.Forms.DataGridView dataGridView1;
    private System.Windows.Forms.DataGridViewTextBoxColumn LineNumber;
    private System.Windows.Forms.DataGridViewTextBoxColumn Content;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

是否可以拥有多行 DataGridView 单元格而不换行文本? 的相关文章

随机推荐

  • 无论如何,我可以在谷歌合作实验室下载该文件吗?

    我正在这个 Codelab 的 Google Colaboratory 中尝试张量流 我需要下载 http download tensorflow org example images flower photos tgz http down
  • PHP 复选框多重删除

    我的实现似乎不起作用 您能指出可能出现的问题或指出更好的解决方案吗 当我选中复选框并单击删除按钮时 它似乎没有执行任何操作 请帮助我 div class page img class page src images DISCLAIMER p
  • 获取当月数据记录条数

    我正在尝试查找数据库中当月结束的车辆记录总数 我不知道我应该在里面写什么InvoiceDate本例中的部分 public void MonthlyStatus NetContext context var monthlyStatus fro
  • Zend Framework,将 URL 的扩展名映射到格式参数?

    是否可以将 URL 的扩展名映射到 ZF 中的格式参数 我希望默认路由仍然有效 包括从 URI 映射参数 因此您可以说 http example com controller action param1 value1 param2 valu
  • 何时返回 IOrderedEnumerable?

    Should IOrderedEnumerable纯粹用作语义值的返回类型 例如 当在表示层中消费模型时 我们如何知道集合是否需要排序或已经排序 如果存储库用一个存储过程包装了一个存储过程 该怎么办 ORDER BY条款 存储库是否应该返回
  • 不存在类型变量 U 的实例,因此 void 符合 U

    我正在努力避免isPresent检查下面的代码 但编译器发出错误消息 没有类型变量的实例U存在使得void符合U 打电话给printAndThrowException 这是我的代码 values stream filter value gt
  • 您在 ASP.NET MVC 中使用什么视图引擎? [关闭]

    Closed 这个问题是基于意见的 help closed questions 目前不接受答案 我知道您可以在 ASP NET MVC 中使用几种不同的视图引擎 ASPX 显然 NV速度 Brail NHaml et al 默认的 ASPX
  • 更改“查看购物车”按钮的文本

    我正在使用 woocommerce 插件 但我遇到了如何更改查看购物车按钮文本的问题 希望有人可以帮助解决我的问题 这是my site http unlieusurterre fix it buddy clients com the tru
  • 无服务器 python 请求具有长时间超时?

    我有几个遵循类似格式的 python 脚本 您传入一个日期 它要么 检查我的 S3 存储桶中文件名中包含该日期的文件 并解析它 或者 运行一个 python 脚本 对文件进行一些分析该日期的文件 运行时间超过 1 小时 我正在寻找一种无服务
  • PHP MySQL 数据库连接

    执行查询 和其他数据库操作 后是否有必要显式关闭数据库连接 不 php 自动执行此操作 不过 您可以将其称为 良好的编程实践 来清理 也称为关闭连接
  • Apache Spark + Parquet 不遵守使用“分区”暂存 S3A 提交器的配置

    我正在使用本地计算机上的 Apache Spark 3 0 将分区数据 Parquet 文件 写入 AWS S3 而无需在计算机中安装 Hadoop 当我有很多文件要写入大约 50 个分区 partitionBy date 时 我在写入 S
  • 如果并行处理,为什么在无限的数字流中按素数过滤会花费很长时间?

    我正在创建一个从 2 亿开始的无限整数流 使用朴素的素性测试实现来过滤该流以生成负载并将结果限制为 10 Predicate
  • 将 HTML 转换为 DOM 以在 Node 中进行操作

    如果我从页面中抓取一些原始 HTML 或者以其他方式制作 HTML 字符串 我可以将其转换为 DOM NodeList 对象吗 那么我可以操作该 NodeList 中的对象并将其再次保存为字符串吗 像这样的东西 request url fu
  • 如何查看kubernetes中pod和veth的关系

    有没有办法看看kubernetes v1 15 2 pod和veth的关系 现在我可以看到主机中的 veth 但不知道哪个 pod 拥有 vethe4297f4 flags 4163
  • 使用 boost Spirit 完全解码 http 标头值

    我再一次发现自己在追求振奋精神 我再一次发现自己被它打败了 HTTP 标头value采用一般形式 text html q 1 0 text q 0 8 image gif q 0 6 image jpeg q 0 6 image q 0 5
  • 将 QString 转换为 char* [重复]

    这个问题在这里已经有答案了 可能的重复 QString 到 char 的转换 https stackoverflow com questions 2523765 qstring to char conversion 我有一个函数 STL 中
  • 分段阅读_第 2538 章

    我是 IBM Websphere MQ 新手 我正在尝试将消息添加到远程 websphere MQ 队列管理器 我在尝试连接时遇到以下错误 另外 我尝试了论坛中提供的许多可能的解决方案 例如将 net 框架更改为 3 5 当我 ping 远
  • 是否可以在 Spring Boot 应用程序中使用 ObjectDB

    我想在我的 Spring Boot 应用程序中使用 ObjectDB 我应该如何配置application yml文件 我不想将 persistence xml 添加到我的应用程序中 那可能吗 您可以按照本教程操作 http spring
  • Rails:渲染 XML 添加 标签

    我有一个 Rails 控制器 它将以 XML 格式输出散列 例如 class MyController lt ApplicationController GET example xml def index output a gt b res
  • 是否可以拥有多行 DataGridView 单元格而不换行文本?

    我知道我可以设置WrapMode为真DefaultCellStyle of the RowTemplate 但这并没有给我我想要的行为 我在每个单元格中显示字符串列表 因此我希望识别回车符 但我不希望长项目换行中的文本 有谁知道是否可以实现