I have a form that allows you to add multiple product ids to a buy. screenshot !
When you start the program here is what you see !
So every time you press a plus button another row appears !.
In order to avoid too many lines of code I decided to create a function so that it takes the number or the row where the plus button was pressed and adds 1 to it, so that the next row appears.
Right now it returns a string with the code, but I dont know how to execute it..
I have searched how to execute a string but the solution can never apply to my code.
//function
public string plus(int n)
{
string r="";
r = "label" + (n + 1) + ".Visible = true;";
r += "combobox" + (n + 1) + ".Visible = true;";
r += "plusButton" + (n + 1) + ".Visible = true;";
r += "minusButton" + (n + 1) + ".Visible = true;";
return r;
}
//plus button
private void plus1_Click(object sender, EventArgs e)
{
//code to execute (plus(1));
}
Opinions and sugestions would be greatly appreciated, solutions even more!
Executing c# expression from string is really a bad idea and not what you want in this case. You could see this post for a detailed answer, but you really shouldn't.
I recommend you store all you component inside a collection like so.
public void plus(int n)
{
labelsArray[n].Visible =
comboboxArray[n].Visible =
plusButtonArray[n].Visible =
minusButtonArray[n].Visible = true;
}
private void plus1_Click(object sender, EventArgs e)
{
plus(1);
}
You'd also need to declare new arrays to index your controls, and populate them with them. For exemple, for you labels array:
private Label[] labelsArray;
// Replace Form1 with the name of your class. This the constructor of your form.
public Form1()
{
labelsArray = new [] {label1, label2, label3, ... };
}
Eventually, you could also create those controls dynamically instead of toggling their visibility.
You don't need to define the code as a string. There are much better ways to do that. If you don't want to save your controls in separate collections and all your controls are child controls of your Form
, you can run the same code with the following function:
public void plus(int n)
{
((Label)this.Controls.Find("label" + (n + 1), false)[0]).Visible = true;
((ComboBox)this.Controls.Find("combobox" + (n + 1), false)[0]).Visible = true;
((Button)this.Controls.Find("plusButton" + (n + 1), false)[0]).Visible = true;
((Button)this.Controls.Find("minusButton" + (n + 1), false)[0]).Visible = true;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.