iT邦幫忙

0

C# DataGridView英文過長時無法自動換行

Ming 2022-10-14 16:29:411261 瀏覽
  • 分享至 

  • xImage
DataGridView1.DefaultCellStyle.WrapMode = DataGridViewTriState.True;
DataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;

目前有使用這兩行程式碼自動換行,但遇到路徑或者英文過長時無法截斷自動換行。
請問各位是否有方法或屬性可以讓路徑或過長的英文也能自動換行。
謝謝大家。

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中
0
cliffliu
iT邦新手 4 級 ‧ 2022-10-15 08:07:46
Ming iT邦新手 5 級 ‧ 2022-10-17 08:36:11 檢舉

已有使用但沒有效果

0
judahliu
iT邦新手 5 級 ‧ 2022-10-24 14:41:10

用DataGridViewCellStyle.WrapMode的話好像有限定 Text 的資料型別

0
JamesDoge
iT邦高手 1 級 ‧ 2023-01-12 03:52:29

使用DataGridView的CellPainting事件

private void DataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
    //如果儲存格有值
    if (e.Value != null)  
    {
        //使用 StringFormat 來設定文字格式
        using (StringFormat stringFormat = new StringFormat())  
        {
            //文字對齊方式:靠左對齊
            stringFormat.Alignment = StringAlignment.Near;   
            
            //文字水平置中
            stringFormat.LineAlignment = StringAlignment.Center;  
            
            //截斷字元,超出的部分會用...取代
            stringFormat.Trimming = StringTrimming.Word;  
            
            //指定要把文字繪製在幾行內,超過的行就會自動換行
            stringFormat.FormatFlags = StringFormatFlags.LineLimit; 
            
            //使用筆刷來繪製文字
            using (Brush brush = new SolidBrush(e.CellStyle.ForeColor)) 
            {
                //繪製文字,使用儲存格中的值,並使用儲存格的字體,筆刷,儲存格範圍,和stringFormat
                e.Graphics.DrawString((string)e.Value, e.CellStyle.Font, brush, e.CellBounds, stringFormat);                 
            }
        }
        
        //標記處理完成
        e.Handled = true;  
    }
}

注意 這個事件必須在 form_load 或儲存格繪製之前綁定,並且需要讓 DataGridView 的 AutoSizeRowsMode 屬性為 None。

private void Form1_Load(object sender, EventArgs e)
{
    //綁定CellPainting事件,指定事件處理常式是DataGridView1_CellPainting
    this.dataGridView1.CellPainting += new DataGridViewCellPaintingEventHandler(DataGridView1_CellPainting);
    
    //設定 AutoSizeRowsMode 屬性為 None,這樣儲存格高度不會自動調整
    DataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None;
    
    //設定DefaultCellStyle.WrapMode屬性為True, 讓文字自動換行
    DataGridView1.DefaultCellStyle.WrapMode = DataGridViewTriState.True;
}

我要發表回答

立即登入回答