2
votes

im trying to create a nullable DateTimePicker which can optionally show some hint text when the control is marked as having a null date.. to achieve this, ive inherited from DateTimePicker and added a Label control with hint text that covers the text part when the control is marked as having a null date.. the problem is that if the DateTimePicker is set to display the usual calender icon, the width of this button is VARIABLE..

the images below show the same DateTimePicker control with different sizes.. as soon as the calender icon button starts to overlap the text, it is changed to a smaller, simple dropdown icon button..

enter image description hereenter image description hereenter image description hereenter image description here

i can try using reflection to read/write private fields but im at a loss as to what to read..

my question.. how do i find out the width of the calender icon displayed in the DateTimePicker control correctly..

2

2 Answers

2
votes

i found a way myself.. =).. the DateTimePicker displays the calender icon button when the control is wider than the text displayed.. when the button starts to clip the text, the control automatically falls back to displaying a smaller dropdown button (visible in the second row of the images in the original question).. so we find out the width of the text, the calender icon button, the dropdown button, and the control itself.. the math that follows is simple..

const int C_BUTTONICON_WIDTH = 34;
const int C_BUTTONARROW_WIDTH = 17;

protected int GetLabelWidth()
{
    int iControlW = this.Width;
    int iTextW = TextRenderer.MeasureString(this.Text, this.Font).Width;

    int iLabelW = 0;
    if (iTextW <= iControlW - C_BUTTONICON_WIDTH)
    {
        iLabelW = iControlW - C_BUTTONICON_WIDTH;
    }
    else
    {
        iLabelW = iControlW - C_BUTTONARROW_WIDTH;
    }
    return iLabelW;
}

you might need to adjust a few pixels depending on the placement of the Label itself.. =).. served my purpose.. =)

0
votes