1. 程式人生 > >C#讓ListBox適應最大Item的寬度

C#讓ListBox適應最大Item的寬度

        private void button1_Click(object sender, EventArgs e)
        {

            for (int i = 1; i <= 16; i++)
            {
                listBox1.Items.Add("TTTTTTTTTTTTTTTTTTTTTTTTTTTTT" + i.ToString());
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            SizeF size = listBox1.CreateGraphics().
                        MeasureString(listBox1.Items[0].ToString(), listBox1.Font);
            MessageBox.Show(Convert.ToInt32(size.Width).ToString());
            listBox1.Width = Convert.ToInt32(size.Width)+20;
        }

        同理CheckedListBox也可以這樣控制