Random programming things I'd want to remember

Showing posts with label radiobutton. Show all posts
Showing posts with label radiobutton. Show all posts

Wednesday, December 28, 2011

Adjust the label text size of radiobutton or checkbox


txtQuestion.Text = "Question text";
int answerBreak = panel1.Height / NUMBEROFANSWERS;
int runningHeightTotal = 0;

panel1.Controls.Clear();

for (int i = 0; i < NUMBEROFANSWERS; i++)
{

  Font stringFont = new System.Drawing.Font(
    SystemFonts.DefaultFont.ToString(), 12, System.Drawing.FontStyle.Regular);

  //Gotcha 1: MeasureText does not produce accurate results
  Size textSize = TextRenderer.MeasureText(
    testQuestions[currentlyTestedQuestionID].Answers[i].AnswerText, stringFont);


  RadioButton rb = new RadioButton();
  rb.Tag = testQuestions[currentlyTestedQuestionID].Answers[i].AnswerID;

  //shift down if the previous answer took too much room
  rb.Location = new System.Drawing.Point(5, 
    (i * answerBreak >= runningHeightTotal ? i * answerBreak : runningHeightTotal + 5));
  rb.Text = testQuestions[currentlyTestedQuestionID].Answers[i].AnswerText;
  rb.Size = new System.Drawing.Size(textSize.Width, textSize.Height);
  rb.Font = stringFont;

  using (Graphics g = rb.CreateGraphics())
  {
    bool height = false;
    int linesNumber = 1;
    //so the text size is measured using the Graphics object
    Size s = g.MeasureString(rb.Text, rb.Font).ToSize();
    if (rb.Size.Height <= s.Height)
      height = true;

    if (s.Width > PANEL1WIDTH)
    {
      linesNumber = s.Width / 750;
      if (s.Width % PANEL1WIDTH > 0)
        linesNumber += 1;
    }

    rb.Size = new Size(PANEL1WIDTH, 
      height ? (s.Height + 5) * linesNumber : rb.Size.Height * linesNumber);
  }

  runningHeightTotal += rb.Height;

  panel1.Controls.Add(rb);
}
If checkbox's size needs to be adjusted, declare rb as a CheckBox, and everything will work just as well.