c# - Assign Unique id's to buttons in foreach loop -


i building online shopping website , @ time there 3 products in it. here's sample of products.

enter image description here

first image, product name, description, price, id , "add cart" button build programmatically , dynamically. can see every product have own button created through foreach loop. confuse how can unique id's assigned it? means when click on add cart button, give me id=3 in foreach loop. now, want how "add cart" button identify product clicked , show specification of product , proceed according it. here's sample of code: using 3-tier architecture , here's sample of code:

dataset ds=obj.searching_product(); datatable dt = new datatable(); dt = ds.tables["register_product"]; foreach(datarow dr in dt.rows) {     literal li2 = new literal();     li2.text = "<br/>";     this.panel1.controls.add(li2);     label lb1 = new label();     lb1.text = dr["name"].tostring();     this.panel1.controls.add(lb1);      //adding here's literal price, images , id etc.      literal li4 = new literal();     li4.text = "<br/>";     this.panel1.controls.add(li4);     button btn = new button();     btn.height = 19;     btn.width = 100;     btn.text = "add cart";     btn.click += new eventhandler(button_click);     this.panel1.controls.add(btn); } 

there few ways it, can create extension button class, a property hold id or simpler hack use itemid in button's id like:

button btn = new button(); btn.id = "btnitem-" + itemid; 

then extract itemid in event handler like:

void button_click(object sender, eventargs e) {     button senderbutton = sender button;     int itemid = -1;     if (senderbutton != null && senderbutton.id.contains('-'))     {         itemid = int.parse(senderbutton.id.split('-')[1]); //or int.tryparse (better)         //work itemid     } } 

as side note, better option create own button class (extending existing button class) , add new property itemid, even better option use controls gridview or repeater controls using data binding.


Comments

Popular posts from this blog

Java 3D LWJGL collision -

spring - SubProtocolWebSocketHandler - No handlers -

methods - python can't use function in submodule -