I have code for creating textboxes. I'm repeating this code three times in different areas. I'm trying to learn more about methods and classes, so I would like to know if there is any possibility of creating textboxes using methods or classes without repeating code.
private void incomes_Click(object sender, EventArgs e)
{
panel1.Controls.Clear();
TextBox textbox1 = new TextBox();
textbox1.Size = new Size(75,23);
textbox1.Text = "Name";
textbox1.Location = new Point(0, 0);
panel1.Controls.Add(textbox1);
TextBox textbox2 = new TextBox();
textbox2.Size = new Size(75, 23);
textbox2.Text = "Sum";
textbox2.Location = new Point(80, 0);
panel1.Controls.Add(textbox2);
}
答案 0 :(得分:1)
Absolutely! You can create a method that accepts the differing parameters and creates the textbox with those specifications:
private void incomes_Click(object sender, EventArgs e)
{
panel1.Controls.Clear();
TextBox textbox1 = CreateTextBox("Name", 0);
TextBox textbox2 = CreateTextBox("Sum", 80);
// Now you can use the textbox values...
}
private TextBox CreateTextBox(string text, int x)
{
TextBox textbox = new TextBox();
textbox.Size = new Size(75, 23);
textbox.Text = text;
textBox.Location = new Point(x, 0);
panel1.Controls.Add(textbox);
return textbox;
}