Unable to autosize rows in datagridview(WinForms 3.5)

    General discussion

  • Hi,

    I have a datagridview(readonly) bound to a datasource(Data Table).Certain rows have multiline text.I need to wrap them and automatically adjust row height so that it fits the cell contents(Like MS EXCEL).

    The columns have their own autosizelayoutmodes set.

    Column - AutoSizeMode

    Column1 - Fill

    Column2 - DisplayedCells

    Column3 - None

    I tried setting autosizemodes for rows to displayed cells and wrapmode to true but it didn't work.Any suggestions/solutions?

    Thanks in advance!!!!

    Friday, May 18, 2012 4:44 PM

All replies

  • Hi mimu,

    If you want to automatically adjust row height, you can set the DataGridView.AutoSizeRowsMode Property to AllCells, please check the sample below.

            private void Form1_Load(object sender, EventArgs e)
                DataTable dt = new DataTable();
                dt.Rows.Add("abcdefg" + Environment.NewLine + "abcdefg","abcdefg",  "abcdefg");
                dt.Rows.Add("abcdefg", "abcdefg" + Environment.NewLine + "abcdefg", "abcdefg");
                dt.Rows.Add("abcdefg", "abcdefg", "abcdefg" + Environment.NewLine + "abcdefg");
                this.dataGridView1.DataSource = dt;
                this.dataGridView1.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
                this.dataGridView1.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
                this.dataGridView1.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
                this.dataGridView1.DefaultCellStyle.WrapMode = DataGridViewTriState.True;
                this.dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;        

    If there is anything unclear, please let me know.

    Best Regards,

    Bob Wu [MSFT]
    MSDN Community Support | Feedback to us

    Monday, May 21, 2012 7:29 AM
  • Hi Bob,

    Thanks for the code snippet.It almosts solves my problem.

    It seems that it automatically wraps new line chars.But if the string is too long to fit in the datagridview cell, is there any property to set so that it automatically wraps long strings?

    dt.Rows.Add("abcdefgaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "abcdefg", "abcdefg" + Environment.NewLine + "abcdefg");



    Monday, May 21, 2012 3:47 PM
  • Hi Mimu,

    I'm afraid no, But you can change the cell value in the DataGridView.ColumnWidthChanged Event handler, see

    Best Regards,

    Bob Wu [MSFT]
    MSDN Community Support | Feedback to us

    Thursday, May 24, 2012 7:06 AM
  • Thanks Bob.

    Regards, Mimu

    Monday, May 28, 2012 5:47 PM