簡體   English   中英

是否可以在不換行的情況下使用多行DataGridView單元格?

[英]Is it possible to have Multi-line DataGridView cells without wrapping text?

我知道我可以設置WrapMode為true的DefaultCellStyle的的RowTemplate ,但是這並沒有給我我想要的行為。 我在每個單元格中顯示一個字符串列表,因此我希望識別回車符,但是我不希望從長條包裝中得到文字。

有誰知道是否有可能實現這一目標?

我希望這是您要尋找的: 屏幕截圖

我使用了兩個事件:

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

}

請享用,
奧菲爾

設計者代碼:

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

我測試了這段代碼,結果是非常好的測試,請:

注意:創建表單並在上設置Datagrid,設置以下datagrid屬性

1- AutoSizeRowsMo​​de到AllCells。
2- WrapMode為目標列為True

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace DGMultiLine
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            int max = 12; //min Column Width in Char
            //do this for all rows of column for max Line Size in values

            string str = "Hello\r\nI am mojtaba\r\ni like programming very very \r\nrun this code and  pay attention to result\r\n Datagrid Must show this Line Good are you see whole of this Thats Finished!";
            string[] ss = str.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);

            //find max Line Size To Now
            for (int i = 0; i < ss.Length; i++)
                if (ss[i] != null && ss[i] != "")
                    if (ss[i].Length > max)
                        max = ss[i].Length;
            //Set target Column Width
            dataGridView1.Columns[0].Width = max*5;//for adequate value you must refer to screen resolution
            //filling datagrigView for all values
            dataGridView1.Rows[0].Cells[0].Value = str;
        }

    }
}

您可以通過實際的fullText添加隱藏的Column,並通過上述代碼添加可見的Column,以顯示字符串值,但字符串行的大小超出“最大列大小”剪輯字符串的范圍,並在末尾添加...。 (如果不清楚,請寫完整的代碼)

它通過與字符串一起\\ r \\ n為我工作。

例如“ Hello” + \\ r \\ n。 然后轉到下一行。

編輯:

剛剛看到這是WinForms。 上面的技巧僅適用於WPF。

編輯2:

您可以使用:

dataGridView1.DefaultCellStyle.WrapMode = DataGridViewTriState.True;

而且,如果您不想包裝長物品,只需執行以下操作:

String stringTest = "1234567891";
if (stringTest.Length > 8)
{
   stringTest = stringTest.Replace(stringTest.Substring(8), "...");
}

如果字符串長於8,則會添加“ ...”。

一種方法是,您可以將一些單詞放在可見的位置,然后在該單元格上的鼠標上的“工具提示”中顯示“全文”。

沒有將WrapMode設置為true,我還沒有找到一種方法。 但是,您應該能夠通過將單元格的寬度設置為足夠寬以在一行上顯示所有項目來“欺騙” DataGridView。

下面是這之中有ComboBo做的一個例子。

此類獲取DataGridView實例,並添加用於修剪寬度和高度的多行省略號(...)的行為。

用法:

MultilineTriming.Init(ref dataGridView); // that's it!

請享用,

public static class MultilineTriming
{
    private static int _rowMargins;

    public static void Init(ref DataGridView dataGridView)
    {
        dataGridView.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None;
        dataGridView.DefaultCellStyle.WrapMode = DataGridViewTriState.False;

        _rowMargins = dataGridView.RowTemplate.Height - dataGridView.Font.Height;

        Unregister(dataGridView);

        dataGridView.CellEndEdit += DataGridViewOnCellEndEdit;
        dataGridView.CellPainting += DataGridViewOnCellPainting;
        dataGridView.RowsAdded += DataGridViewOnRowsAdded;
        dataGridView.Disposed += DataGridViewOnDisposed;
    }

    private static void DataGridViewOnRowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
    {
        DataGridView view = sender as DataGridView;
        DataGridViewRow row = view.Rows[e.RowIndex];
        foreach (DataGridViewCell cell in row.Cells)
        {
            if (cell.FormattedValue == null)
            {
                continue;
            }
            Size size = TextRenderer.MeasureText((string)cell.FormattedValue, view.Font);
            row.Height = Math.Max(size.Height + _rowMargins, row.Height);
        }
    }

    private static void DataGridViewOnDisposed(object sender, EventArgs eventArgs)
    {
        DataGridView dataGridView = sender as DataGridView;
        Unregister(dataGridView);

    }

    public static void Unregister(DataGridView dataGridView)
    {
        dataGridView.RowsAdded -= DataGridViewOnRowsAdded;
        dataGridView.CellEndEdit -= DataGridViewOnCellEndEdit;
        dataGridView.CellPainting -= DataGridViewOnCellPainting;
    }

    private static void DataGridViewOnCellEndEdit(object sender, DataGridViewCellEventArgs e)
    {
        DataGridView view = sender as DataGridView;
        DataGridViewRow row = view.Rows[e.RowIndex];
        DataGridViewCell cell = row.Cells[e.ColumnIndex];

        string text = (string)cell.FormattedValue;

        if (string.IsNullOrEmpty(text)) return;

        Size size = TextRenderer.MeasureText(text, view.Font);
        row.Height = Math.Max(size.Height + _rowMargins, row.Height);
    }

    private static void DataGridViewOnCellPainting(object sender, DataGridViewCellPaintingEventArgs e)
    {
        if (e.ColumnIndex == -1 || e.RowIndex == -1 || e.FormattedValue == null)
        {
            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) - 3, e.CellBounds.Height - _rowMargins, 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 + 1, e.CellBounds.Y + _rowMargins / 2);

        e.Handled = true;
    }

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

        if (size.Width < contentWidth && size.Height < contentHeight)
        {
            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++;
            }
        }
        string res = sb.ToString();

        if (size.Height <= contentHeight)
        {
            return res;
        }

        string[] lines = res.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
        i = lines.Length;
        while (i > 1 && size.Height > contentHeight)
        {
            res = string.Join(Environment.NewLine, lines, 0, --i);
            size = TextRenderer.MeasureText(res, font);
        }

        return res;
    }
}
       if ((!e.Value.Equals("OK")) && e.ColumnIndex == 6)
        {
            e.CellStyle.WrapMode = DataGridViewTriState.True;
            //dgvObjetivos.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
            dgvObjetivos.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
        }

http://kshitijsharma.net/2010/08/23/showing-multiline-string-in-a-datagridview-cell/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM