Adding comboboxes with a function to be called by a buttonpress - c#

So my problem is that I want to add comboboxes to a windows forms based program by clicking on a button. What I have now is:
private void addCoworkerBox()
{
DDLList.Add(new ComboBox());
comboBoxInit(coworkerIndex);
coworkerIndex++;
}
and:
private void comboBoxInit(int i)
{
var yValue = DDLCoworker.Location.Y;
DDLList[i].DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
DDLList[i].Font = new System.Drawing.Font("Microsoft Sans Serif", 10F);
DDLList[i].FormattingEnabled = true;
yValue += 34;
DDLList[i].Location = new System.Drawing.Point(380, yValue);
DDLList[i].Name = "comboBox";
DDLList[i].Size = new System.Drawing.Size(121, 28);
DDLList[i].TabIndex = 2;
DDLList[i].Items.AddRange(names.ToArray());
DDLList[i].Show();
}
the list DLLList, the int yValue and the int coworkerindex are initialized further up in my code.
I know that this is kind of a repost, but the answers to the others don't seem to help me.
The above code does not work. When I press the button that should add the new combobox, nothing happens. I have added a function for said button, that calls the addCoworkerBox() function.

You've created it just fine, but you've not added it to the form. There's a collection of controls - you need to add it to that...
Controls.Add(DDLList[i]);

Related

Prevent hardcoded values in Winform designer file while using User Controls

I am trying to include a calendar like custom user control that picks month and year. In the user control code I am setting two properties, Month and Year to current month and year.
public MonthPicker()
{
InitializeComponent();
m_MonthLabels = new Label[]
{
lblJanuary,
lblFebruary,
lblMarch,
lblApril,
lblMay,
lblJune,
lblJuly,
lblAugust,
lblSeptember,
lblOctober,
lblNovember,
lblDecember
};
m_NotSelected = new Font("Sans Serif", 8.25F, FontStyle.Regular);
m_Selected = new Font("Sans Serif", 8.25F, FontStyle.Bold);
Month = DateTime.Now.Month;
Year = DateTime.Now.Year;
lblYear.Text = Year.ToString();
groupBox2.Visible = false;
groupBox1.Height = 20;
CalendarIsDisplayed = false;
CalendarIsNotChanged = false;
SetMonthLabelSelected(Month);
}
However, when I include it in my Application form, the designer takes hard coded values for Month and Year. Consequently, when the month changes it still shows me older month.
// tsMonthPicker
//
this.tsMonthPicker.BackColor = System.Drawing.SystemColors.Control;
this.tsMonthPicker.CalendarIsDisplayed = false;
this.tsMonthPicker.CalendarIsNotChanged = false;
this.tsMonthPicker.Location = new System.Drawing.Point(104, 14);
this.tsMonthPicker.Margin = new System.Windows.Forms.Padding(0);
this.tsMonthPicker.Month = 1;
this.tsMonthPicker.Name = "tsMonthPicker";
this.tsMonthPicker.Size = new System.Drawing.Size(215, 20);
this.tsMonthPicker.TabIndex = 6;
this.tsMonthPicker.Value = new System.DateTime(2017, 1, 1, 0, 0, 0, 0);
this.tsMonthPicker.Year = 2017;
this.tsMonthPicker.Change += new Time_and_Billing_System.MonthPicker.MonthPickerChangeHandler(this.tsMonthPicker_Changed);
this.tsMonthPicker.Load += new System.EventHandler(this.tsMonthPicker_Load);
How do I change my code in user control so that the form designer file automatically takes -
this.tsMonthPicker.Month = System.DateTime.Now.Month;
this.tsMonthPicker.Year = System.DateTime.Now.Year;
Put these two lines in the Form_Load method, for the form in which this MonthPicker is embedded.
private void Form1_Load(object sender, EventArgs e)
{
this.tsMonthPicker.Month = System.DateTime.Now.Month;
this.tsMonthPicker.Year = System.DateTime.Now.Year;
}
In the Object Viewer, while the Form object is chosen, select the Events view (Lightning Bolt), find Load in the list, double-click that space, and this method will appear in the code.
You could use the DesignMode property for this. You don't state if you need a default value of Now each time the app is launched. If that is the case then you don't need the DesignMode.
public MonthPicker()
{
if (this.DesignMode)
{
//These values are only set when the control is created in design mode
this.tsMonthPicker.Month = System.DateTime.Now.Month;
this.tsMonthPicker.Year = System.DateTime.Now.Year;
}
}

Adding dynamic controls to winform not working

I am creating dynamic PictureBox and label in WinForms. For this I have created a method which creates these items on the basis of given integer. In the first run while loading the form, its works smoothly, but when I pass any integer from a dropdown box, it does not make any changes. I tried debugging the code, and all the labels are created accordingly but it is not reflected in the winForm. I tried using Invalidate, Update, Refresh but non of them worked.
Here is the method that I have implemented.
private void createPictureBox(int size)
{
//this.Controls.Clear();
panel1.Controls.Clear();
Label[] ParameterLabel = new Label[size];
PictureBox[] ParameterBack = new PictureBox[size];
int y_value = 11;
this.Refresh();
for (int i = 0; i < size; ++i)
{
ParameterLabel[i] = new Label();
ParameterLabel[i].Text = "Test Text";
ParameterLabel[i].Font = new System.Drawing.Font("Calibri", 8, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(128)));
ParameterLabel[i].ForeColor = System.Drawing.Color.White;
ParameterLabel[i].BackColor = System.Drawing.Color.FromArgb(1, 0, 64);
ParameterLabel[i].Size = new System.Drawing.Size(145, 20);
ParameterLabel[i].Location = new Point(30, y_value);
ParameterLabel[i].Anchor = AnchorStyles.Left;
ParameterLabel[i].Visible = true;
ParameterBack[i] = new PictureBox();
ParameterBack[i].Image = Image.FromFile(STR_SETTING_PATH + "\\" + STR_IDEA_NO_XXXXX + "_01_nv.png");
ParameterBack[i].Size = new System.Drawing.Size(400, 32);
ParameterBack[i].Location = new Point(2, y_value - 10);
ParameterBack[i].Anchor = AnchorStyles.Left;
ParameterBack[i].Visible = true;
//this.Controls.Add(ParameterBack[i]);
y_value += 37;
}
panel1.Controls.AddRange(ParameterLabel);
panel1.Controls.AddRange(ParameterBack);
panel1.Invalidate();
}
Who can you distinguish between controls created in the first call and those created in other calls? I've tested your function with a tiny change, it seems to be working fine:
int CallIndex = 0; // this is on the form level
private void button1_Click(object sender, EventArgs e)
{
createPictureBox(3);
CallIndex += 1;
}
private void createPictureBox(int size)
{
// this has the exact same code as your method (copy-paste into my visual studio),
// except this change:
// ParameterLabel[i].Text = "Test Text";
ParameterLabel[i].Text = string.Format("Test {0}", CallIndex); // instead of the row above
}
I did remove the previously added controls and added the new one after which apparently solved my problem. The problem was due to piling of Controls one over another. I first removed the previously created controls using
this.Controls.Remove(UserControl1);
Then re-created its instance, which solved my problem.

C# - Drag and Drop from picture box earlier code-created

I am trying to code a drag and drop system with pictureboxes. I did this earlier, except this time, I created the pictureboxes by code and not in the designer.
DASporter dasporter = new DASporter();
List<int> landids = dasporter.getLandenBySport(1);
DALand daland = new DALand();
Land land = null;
PictureBox[] landenfotos = new PictureBox[landids.Count];
int teller = 80;
for (int i = 0; i <= landids.Count - 1; i++)
{
land = daland.getLand(landids[i]);
landenfotos[i] = new PictureBox();
landenfotos[i].Name = "Picturebox" + land.Id.ToString();
landenfotos[i].Location = new Point(70, teller);
landenfotos[i].Tag = land.Naam;
landenfotos[i].Size = new Size(70, 70);
landenfotos[i].Image = Image.FromFile("images/" + land.Vlag);
landenfotos[i].SizeMode = PictureBoxSizeMode.Zoom;
this.Controls.Add(landenfotos[i]);
teller += 60;
}
If you create them in the designer, you can use the eventmanager to search the right event. Now, I can't use this so i need an alternative.
Anyone who had this problem too and got it solved? I can't find a solution anywhere.
You can add event handlers easily by typing
landenfotos[i].MouseMove +=<Tab><Tab>
Pressing <Tab> twice after += will create an event handler automatically.
It will complete the line to
landenfotos[i].MouseMove += new MouseEventHandler(SomeMethodName_MouseMove);
and add the method
void SomeMethodName_MouseMove(object sender, MouseEventArgs e)
{
throw new NotImplementedException();
}
And of course Intellisense will show you all the available events to choose from :-)

dynamic radio button text alignment

When i add a radio button in visual c# the text name of the radio button is aligned perfectly to the right . if i create a radio button dynamically and give it several properties etc.. when i debug and view it, the text or name of the radio button is shifted slighted up and to the right of the radio button? i am looked over several properties including padding etc.. but i am not able to figure out how to correct this dynamically. what is going on and how can i fix this?
here is example of the properties i am using right now
radio_ip_addresses[i] = new RadioButton();
radio_ip_addresses[i].Name = "radio_" + i;
radio_ip_addresses[i].Text = ip_addresses.Dequeue();
radio_ip_addresses[i].Location = new Point(x, y);
radio_ip_addresses[i].Font = new Font("Microsoft Sans Serif", 8, FontStyle.Bold);
radio_ip_addresses[i].ForeColor = Color.White;
radio_ip_addresses[i].TextAlign = ContentAlignment.MiddleLeft;
radio_ip_addresses[i].Visible = true;
radio_ip_addresses[i].Parent = this;
Thanks Rotem, i took your suggestion to check the designer.cs i should have thought of that. it was autosize that was the key :), see below from what i found in the designer.cs.
this.radioButton1.AutoSize = true;
this.radioButton1.Location = new System.Drawing.Point(192, 50);
this.radioButton1.Name = "radioButton1";
this.radioButton1.Size = new System.Drawing.Size(85, 17);
this.radioButton1.TabIndex = 71;
this.radioButton1.TabStop = true;
this.radioButton1.Text = "radioButton1";
this.radioButton1.UseVisualStyleBackColor = true;

C# Add Controls To Panel In a Loop

I wish to add a button for every line in a file to a panel.
My code so far is:
StreamReader menu = new StreamReader("menu.prefs");
int repetition = 0;
while(!menu.EndOfStream)
{
Button dynamicbutton = new Button();
dynamicbutton.Click += new System.EventHandler(menuItem_Click);
dynamicbutton.Text = menu.ReadLine();
dynamicbutton.Visible = true;
dynamicbutton.Location = new Point(4+repetition*307, 4);
dynamicbutton.Height = 44;
dynamicbutton.Width = 203;
dynamicbutton.BackColor = Color.FromArgb(40,40,40);
dynamicbutton.ForeColor = Color.White;
dynamicbutton.Font = new Font("Lucida Console", 16);
dynamicbutton.Show();
menuPanel.Controls.Add(dynamicbutton);
repetition++;
MessageBox.Show(dynamicbutton.Location.ToString());
}
menu.Close();
The problem is that only the first control gets created.
The code looks fine but there could be a following situations.
1.You might have only one entry in the file, so you are experiencing only One Button added to the panel.
2.Your panel width is smaller than the sum of all the dynamic buttons width.
I suspect no 2 is the main reason that is causing problem.
So, I recommend that you use FlowLayoutPanel. To add a dynamic content as it automatically layout all the child controls.
Each time it is generating the same name for dynamic controls. That's the reason why it is showing only the last one. It simply overwrites the previous control each time.
int x = 4;
int y = 4;
foreach(PhysicianData pd in listPhysicians)
{
x = 4;
y = panPhysicians.Controls.Count * 30;
RadioButton rb = new RadioButton();
rb.CheckedChanged += new System.EventHandler(rbPhysician_CheckedChanged);
rb.Text = pd.name;
rb.Visible = true;
rb.Location = new Point(x, y);
rb.Height = 40;
rb.Width = 200;
rb.BackColor = SystemColors.Control;
rb.ForeColor = Color.Black;
rb.Font = new Font("Microsoft Sans Serif", 10);
rb.Show();
rb.Name = "rb" + panPhysicians.Controls.Count;
panPhysicians.Controls.Add(rb);
}
Try this code
StreamReader menu = new StreamReader("menu.prefs");
var str = menu.ReadToEnd();
var items = str.Split(new string[] {"\r\n" } , StringSplitOptions.RemoveEmptyEntries);
foreach (var item in items)
{
Button dynamicbutton = new Button();
dynamicbutton.Click += new System.EventHandler(menuItem_Click);
dynamicbutton.Text = item;
dynamicbutton.Visible = true;
dynamicbutton.Location = new Point(4+repetition*307, 4);
dynamicbutton.Height = 44;
dynamicbutton.Width = 203;
dynamicbutton.BackColor = Color.FromArgb(40,40,40);
dynamicbutton.ForeColor = Color.White;
dynamicbutton.Font = new Font("Lucida Console", 16);
dynamicbutton.Show();
menuPanel.Controls.Add(dynamicbutton);
repetition++;
}
The problem with Panel and similar controls other than the FlowLayoutPanel is when you create a control and a second one, the second is created at the same position if you are not changing it's location dynamically or setting it according to the other already added controls. Your control is there, it's in the back of the first control.
A flowLayoutPanel is better as it will add the controls next to each other as you add them while compromising more finer control at their positioning.
I also have similar problems with panels. For what you are doing it could be useful to just add strings to a listbox rather than using labels and a panel. That should be simpler.

Categories