是否有可能具有多行的DataGridView细胞无文本换行? [英] Is it possible to have Multi-line DataGridView cells without wrapping text?

查看:115
本文介绍了是否有可能具有多行的DataGridView细胞无文本换行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我可以设置 WrapMode 来真正的 DefaultCellStyle RowTemplate ,但是这并没有给我我想要的行为。我每个显示单元内的字符串列表,所以我想回车予以承认,但我不希望从长项将连续文本。

I know I can set WrapMode to true on the DefaultCellStyle of the RowTemplate, however this doesn't give me the behaviour I want. I am displaying a list of strings within each cell, and I therefore want the carriage returns to be recognised, but I don't want text from long items wrapping.

请问任何人都知道,如果有可能实现这一目标。

Does anyone know if it's possible to achieve this?

推荐答案

我希望这是你在找什么:

I hope this is what you are looking for:

我用了两个事件:


  1. 我一个单元格编辑后测得的高度。

  2. 我画的细胞时所测得的文本,修剪它,如果需要的话,重复,直到它符合

代码:

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;
}

这篇关于是否有可能具有多行的DataGridView细胞无文本换行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆