i'm working in ASP.NET in visual studio.
I tried to dynamicly create a list of buttons in C# and make its appears on an update panel, and it worked.
My problem is the following : i've created this list with a for loop and so, every buttons has the same OnClick method. So, when i click on one of its, it doesn't do anything.
Do you have any ideas of what my problem can be ?
this is my for loop for creating :
for (int i = 1; i < eq.Count; i += 3)
{
Button nom = new Button();
nom.Text = "btn-"+ Convert.ToString(i);
nom.ID = ("Nom" + i).ToString();
nom.Click += new EventHandler(btn_Agent_Click);
Panel.Controls.Add(nom);
Button refurl = new Button();
refurl.Text = equipes[i + 2];
refurl.ID = ("refURL" + i).ToString();
indice++;
}
Have a great day ! :)
I have achieved creating dynamic buttons using the following code for click event
nom.Click += (s, e) => {
// add your logic here for each button where s,e are (object sender, EventArgs e)
};
Hope it helps!
Related
I am creating dynamically buttons in windows forms by using the code below. I want to have a context menu with different options pop up when a button is being right clicked. I made the context menu strp and it shows up but i cant figure out how to make the different options perform the functions i have written for them. Any idea how i can connect the items to their functions ?
void AddButton(Shape s){
Button b = new Button();
b.Text = s.name;
b.Width = sceneItemsList.Width-6;
b.TabStop = false;
b.FlatStyle = FlatStyle.Flat;
b.BackColor = Color.LightGray;
b.FlatAppearance.BorderColor = Color.Black;
ContextMenuStrip cm = new ContextMenuStrip();
cm.Items.Add("Deselect");
cm.Items.Add("Edit");
if (s is GroupShape)
{
cm.Items.Add("Ungroup");
}
cm.Items.Add("Delete");
b.ContextMenuStrip = cm;
}
Figured it out! This is my code if anyone else is struggling with this. Basically you make a loop that goes through all the opptions and adds a click eventhadler
cm.Items[0].Click += (sender, e) => {
Console.WriteLine("ok");
};
I have a form over which I have a panel. When a button is clicked, I turn my panel to invisible and I show a DataGridView ( a table from sql ). My problem is... is there any way to put a button somewhere on my form so I can go back to the main menu ( on click, to set the panel visibility to true ).
I tried using DataGridViewButtons but it's not ok. I want just one single button, anywhere on my form, called Back that would take me back. Somehow, it won't let me place a button anywhere unless I have a panel. Is there any solution?
I can add any code if necessary, just tell me which
menu.Visible = false;
DataGridView dgw = new DataGridView();
dgw.Parent = this;
dgw.Location = new Point(
this.ClientSize.Width / 3 - dgw.Size.Width / 2,
this.ClientSize.Height / 4 - dgw.Size.Height / 2);
dgw.Anchor = AnchorStyles.None;
dgw.AutoSize = true;
dgw.BackColor = Color.FromArgb(210, 121, 84);
dgw.Text = "Login";
dgw.Padding = new Padding(10);
dgw.BorderStyle = BorderStyle.FixedSingle;
While it is far more easy to create your form from the designer, placing a Button on the form code is as simple as creating the datagrid.
private void CreateButton()
{
var button = new Button
{
Text = "Press me",
Name = "SomeButtonName",
Location = new Point(10,10),
Size = new Size(100,20),
Visible = true,
};
button.Click += (s, e) => this.ButtonClicked();
this.Controls.Add(button);
}
private void ButtonClicked()
{
// this will fire on click
}
You can call `this.CreateButton()' everywhere you'll like.
I'm trying to call events of dynamically created buttons sending parameters, but when I click nothing happens, just Post Back the page.
public void adicionarComanda()
{
List<Comanda> lc = ControllerComanda.getComanda();
foreach (Comanda comanda in lc)
{
Button bt = new Button();
bt.Text = comanda.nome_Pessoa;
bt.CssClass = "botoes";
bt.Click += btnNome1_Click;
bt.CommandArgument = comanda.nome_Pessoa;
HtmlGenericControl li = new HtmlGenericControl("li");
li.Controls.Add(bt);
ulBotoes.Controls.Add(li);
}
}
And the Event
protected void btnNome1_Click(object sender, EventArgs e)
{
string nomePessoa = (sender as Button).CommandArgument;
Session["currentUser"] = nomePessoa.ToString();
Response.Redirect("~/Mobile/Pages/produtosCategoria.aspx");
}
But nothing Happens when I click the button, just PostBack the page. How can I fix this problem?
Thank you guys
You need to re-render all dynamically generated controls on every postback. I suggest creating a method that generates the these controls then call that method on every postback in Page_Load.
Have you thought about maybe passing "currentuser" as a parameter? bt.Attributes.Add("onclick", "javascript:redirect('~/Mobile/Pages/produtosCategoria.aspx?name=comanda.nome_Pessoa')";
Instead of defining click function you can use another approach - PostBackUrl.
public void adicionarComanda()
{
List<Comanda> lc = ControllerComanda.getComanda();
foreach (Comanda comanda in lc)
{
Button bt = new Button();
bt.Text = comanda.nome_Pessoa;
bt.CssClass = "botoes";
bt.PostBackUrl = String.Format("~/Mobile/Pages/produtosCategoria.aspx?user={0}", comanda.nome_Pessoa);
HtmlGenericControl li = new HtmlGenericControl("li");
li.Controls.Add(bt);
ulBotoes.Controls.Add(li);
}
}
Then in the redirected page you can use Request.QueryString["user"] , and use it as required.
I have an array of button created dynamically, suppose 8 buttons, what I want is that when I click a particular button its background picture is changed and the name of button is stored in a linked list. When I click the same button again the background picture goes back to the original and the button name is deleted from linked list. Now I am able to do the first part, the second click is not working as I want it to.
Basically it's a datastructures project (shopping store) therefore I am using linked list, I have a linked list whose content is displayed through picture boxes[] and labels. Here what i am trying to do is when I click the picture box, the content of that particular node is added to a new linked list (added to the cart) and when I click on the picturebox again that particular item is deleted from the linked list (removed from the cart). Clicking it for the first time it is doing what i want it to do but the second click is not really working.
It's a datastructures project therefore I can't really use any built in classes for linked list, I had to write all methods myself and I did and they work.
cb[i].Click += (sender, e)=>{
if (flag == 0) {
// Console.WriteLine(obj.Retrieve(index).NodeContent);
// Console.WriteLine(obj.Retrieve(index).number);
inv.Add(obj.Retrieve(index).NodeContent, obj.Retrieve(index).number);
bill += Convert.ToInt32(obj.Retrieve(index).number);
cb[index].Image = Image.FromFile(#"F:\uni work\3rd semester\project images\rcart.jpg");
flag++;
}
else if (flag == 1)
{
// Console.WriteLine(bill);
bill -= Convert.ToInt32(obj.Retrieve(index).number);
// Console.WriteLine(bill);
inv.Delete(index);
cb[index].Image = Image.FromFile(#"F:\uni work\3rd semester\project images\cart.png");
flag--;
}
Since you are using a LinkedList it does have a Contains Method and a Remove Method that take a string. You haven't specified exactly what your problem is this should work. When you assign images to a control you loose the information that tells you what Image it is.
public partial class Form1 : Form
{
LinkedList<String> myList = new LinkedList<String>();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < 8; i++)
{
Button b = new Button() { Height = 30, Width = 70, Location = new Point(i, 50 * i),Name = "NewButton" + (i + 1).ToString() , Tag=i};
b.Click += b_Click;
this.Controls.Add(b);
}
}
void b_Click(object sender, EventArgs e)
{
Button b = (Button)sender;
if(myList.Contains(b.Name)) //Check if button is in the List then Change Picture and remove
{
b.BackgroundImage = Properties.Resources.Peg_Blue;
myList.Remove(b.Name);
}
else
{
b.BackgroundImage = Properties.Resources.Peg_Red;
myList.AddLast(b.Name);
}
}
}
Why not create a class for each button, containing the two images and switch between them on each click?
I don't know whether it is clear. I mean a form has an input textbox and a button. If I input 5 in the textbox and click on the button, the form will add 5 labels...
The question is I don't know it is 5 or 4 or 3……before the code is running and the input.
I don't know how to add the labels and how to define or get their names in order to use them later in the code.
I am just learning windows applications development with VS using C#....
And also this is my first ask in stackoverflow please forgive me if it is not clear. Is there anybody can help me?
let's split your entire problem into few steps of understanding:
What basically down the line, you are asking, is to how to add controls dynamically in a winform, in your case the control is label, so wrap your label creating logic in a function like below:
protected Label CreateLabel(string Id, string text)
{
Label lbl = new Label();
lbl.Name = Id;
lbl.Text = text;
return lbl;
}
Now you need to add as many labels as the number entered in a given textBox and upon a button click, so possibly something like below in button's click event:
protected void button_Clicked(object sender, EventArgs e)
{
//make sure nothing invalid string comes here
int counter = Convert.ToInt32(txtCount.text);
for(int i=0;i<counter;i++)
{
var lbl = CreateLabel("rand"+i, "Label" +i);
container.Controls.Add(lbl);//container can be your form
}
}
Now the basic problem in winforms you will face, will be about the positioning of these dynamically added labels. The most simple way to go about it is to add your labels to winforms FlowLayoutPanel. It automatically aligns the controls. There are other layout controls available aswell. so do this :
drag and drop a FlowLayoutPanel on your form and give it the name "container", rest assured
For example:
for(var i=0; i<N; i++ ) {
var l= new Label();
l.Text = "some name #" + i.ToString();
l.Width = 200;
l.Location = new Point(30, 20);
parent.Controls.Add(l);
}
You can use this as:
Label[] arrLabel;
int num = 0;
int.TryParse(textBox1.Text, out num);
arrLabel = new Label[num];
for (int i = 0; i < num; i++)
{
arrLabel[i] = new Label();
arrLabel[i].Text = "Label #" + (i+1);
arrLabel[i].Width = 20;
arrLabel[i].Location = new Point(30+10*(i+1), 20);
this.Controls.Add(arrLabel[i]);
}