Jonas Willander Jonas Willander - 24 days ago 6
C# Question

C# Array strings in a Group of Radio Buttons

My code is C# windows form

I have a file with data:



David One And Two/Three

Alex One Two Four And Five/Six

Amanda Two Seven/Ten

Micheal Seven/Nine




and trying to have them in array like


string[] Names = File.ReadAllLines("C:\Students\Name.txt", Encoding.Default);




and have them in Group of Radio Buttons


RadioButton[] n = new RadioButton[Names.Length];

for (int i = 0; i < Names.Length; i++)
{
n[i] = new RadioButton();
n[i].Text = Names[i];
n[i].Location = new Point(10, 10 + i * 20);
groupBox1.Controls.Add(n[i]);
}


But it shows as my attached image

I tried without Encoding.Default and Encoding.UTF8 but the same problem.


What is I'am doing wrong? Please see my image and help me. Thank you in advance!



enter image description here

Answer

I'm guessing your file contains empty lines at the end. You can try to remove them before creating a radio button:

for (int i = 0; i < Names.Length; i++)
 {
   var name = Names[i];
   if(name.Trim() == string.Empty) continue;

   n[i] = new RadioButton();
   n[i].Text = Names[i];
   n[i].Location = new Point(10, 10 + i * 20);
   groupBox1.Controls.Add(n[i]);
 }

If your text is trimmed you can try to increase the width of the control:

n[i].Width = 300; // Put a value which will show the entire text
Comments