TechTips .NET/ CSLA.NET / ASP.NET / VB.NET / C# / SQL Server / MySql / Android/ Photography
  • Aug
    23

    Showing Multiline string in a DataGridView Cell

    Filed under: .NET, C#;

    Hi,

    Recently I need to show multi-line string in a datagridview cell. To achieve that we need to write code in CellFormatting event of DataGridview. Following is the code

    private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
            {
                if (e.Value.Equals("Error"))
                {
                    e.CellStyle.BackColor = Color.Red;
                    e.CellStyle.ForeColor = Color.White;
                    
                }
                else
                {
                    if ((!e.Value.Equals("OK")) && e.ColumnIndex==2)
                    {
                        e.CellStyle.BackColor = Color.Green;
                        e.CellStyle.ForeColor = Color.White;
                        e.CellStyle.WrapMode = DataGridViewTriState.True;
                        dataGridView1.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
                        dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
                        
                    }
                    
                }
            }
    

    I hope this help!

    Kshitij

    8 Comments
 

8 responses to “Showing Multiline string in a DataGridView Cell” RSS icon

  • Stumbled into this site by chance but I¡¯m sure glad I clicked on that link. You definitely answered all the questions I¡¯ve been dying to answer for some time now. Will definitely come back for more of this. Thank you so much

  • awesome solution…thank you a lot

  • With this tip, now I’m the master of the grid! yeah!

    Thanks man!

  • Good to know this helps you man!

  • Fantastic! I just added the following in VB.Net (Based on your code) and it works like a dream!

    Private Sub frmExamDef_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    DataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells
    DataGridView1.DefaultCellStyle.WrapMode = DataGridViewTriState.True
    DataGridView1.Columns(1).AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells
    DataGridView1.Columns(3).AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells
    DataGridView1.Columns(4).AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells
    DataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells
    End Sub

  • Glad to know it helps Henk…


Leave a reply

Pictures

Translate

EnglishFrenchGermanHindiItalianPortugueseRussianSpanish
| More