Search code examples
c#winformsdatagridviewdatagridviewcolumn

c# datagridview row width automatically increases on scrolling


My Datagridview contains DateTimeColumn which overlaps the another next row column on scrolling. I had set the DatagridView properties like

AutoSizeColumnsMode : Fill

AutoSizeRowsMode: AllCellsExceptheaders

AllowUserstoAddRows: True

But it show me following result. Any Help will be great

enter image description here

My Code

  private void dataGridView4_CellClick(object sender, DataGridViewCellEventArgs e)
    {
        try
        {
            if (e.RowIndex != -1)
            {
                if (e.ColumnIndex == 1 || e.ColumnIndex == 2)
                {

                    oDateTimePicker = new DateTimePicker();


                    dataGridView4.Controls.Add(oDateTimePicker);


                    oDateTimePicker.Format = DateTimePickerFormat.Short;


                    Rectangle oRectangle = dataGridView4.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true);


                    oDateTimePicker.Size = new Size(oRectangle.Width, oRectangle.Height);


                    oDateTimePicker.Location = new Point(oRectangle.X, oRectangle.Y);
                    oDateTimePicker.TextChanged += new EventHandler(dateTimePicker_OnTextChange);
                    oDateTimePicker.Visible = true;
                }
            }
        }
        catch (Exception E)
        {
            MessageBox.Show(E.ToString());
        }
    }



    private void dateTimePicker_OnTextChange(object sender, EventArgs e)
    {

        dataGridView4.CurrentCell.Value = oDateTimePicker.Text.ToString();
    }

Solution

  • It seems instead of a using real DataGridViewColumn you are aligning some DateTimePicker above the DataGridView.

    Instead on aligning some DateTimePicker controls above your DataGridView you should create a custom DataGridViewColumn.

    Here is a good MSDN Example that implements a CalendarColumn.