asp.net - Dynamically added controls remove when dropdown event fired in the datalist in user control -


i working on asp.net vb.net web form - reservation web application, in 1 aspx page , rest user-control page.

at run-time of aspx page, user controls load per step , name define in db, in below link.

asp.net custom user control add dynamically

in first step, first user-control bind in page-init used shows reservation availability detail in .net datalist control (see images).

enter image description here

all details bind generate run-time control via data-list's item_databound event.

  1. imageofroom (asp.net image control) - on click popup open scroll functionality
  2. name (direct databound)
  3. amenities (icon(s)) - dynamically add db.
  4. no. of room per room type (asp.net dropdown control) - dynamically add db , on selected index changed, need dropdown bind in same row , on change of adult dropdown price vary.
  5. total price (direct databound)
  6. book (button)

enter image description here

now issue whenever event of datalist(click on romm-image or dropdown selected index changed) fired, dynamic control remove ammenities, dynamic dropdown of other row etc.

what tried :- ispostback, relevant event of page-life cycle, ajax-jquery, viewstate.

i checked also, no luck. : dynamically added controls in asp.net

i analyze that, user-control rebound , event fired, no datalist rebind , no - databound event fire , dynamic control removed. if wish, share code (but huge code).

so question how retain dynamic controls , value when dropdown selected index changed or image click event fired in datalist in usercontrol?

i not used update-panel, work? if yes, please give sample data.

good answer sample data. please suggest if possible via other control grid-view or else, ready change it.

updated code

load user control code in aspx page, usercontrol define load user control per current step. “uc” user control tag in aspx page.

<div id="divplaceholder" runat="server">         <uc:dynamiccontrolhost id="ucdynamiccontrolhost" runat="server" />  </div> 

in page_load page_prerender( ispostback ) , below code execute load runtime user-control.

public control setusercontrolpath(string path)     {         control c = null;         if (this.dynamicallcontent.controls.count > 0)         {             //check new control not same current control             if (!this.usercontrolpath.equals(path))             {                 //remove old item because can not replace them!                 this.dynamicphallcontent.controls.clear();                 c = page.loadcontrol(path + ".ascx");                 c.id = path;                  //add new item                 this.dynamicallcontent.controls.add(c);                 lock (_usercontrollockobject)                 {                      //store new path                     _strusercontrol = path;                 }             }         }         else         {                  c = page.loadcontrol(path + ".ascx");                 c.id = path;                 this.dynamicallcontent.controls.add(c);                 _strusercontrol = path;          }         return c;     } 

structure of datalist in usercontrol

<asp:updatepanel id="employeesupdatepanel" runat="server" updatemode="conditional"> <contenttemplate>           <asp:datalist id="dllodgingavailabledetails" showheader="true" onselectedindexchanged="dllodgingavailabledetails_selectedindexchanged" runat="server" cellpadding="2" cellspacing="2" borderwidth="1px" bordercolor="black"      onitemdatabound="dllodgingavailabledetails_itemdatabound" borderstyle="solid" gridlines="horizontal" horizontalalign="justify">     <headerstyle cssclass="submit_butt"></headerstyle>     <headertemplate>                 lodging item type details      &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;     <asp:button id="btnbookroom" runat="server" text="book rooms" cssclass="submit_butt" onclick="btnbookroom_click" />     </headertemplate>             <itemtemplate>         <table cellpadding="2" cellspacing="0" border="1" style="width: 100%";>             <tr>                                 <td style="width:170px">                                         <asp:imagebutton id="imglodging" onclick="imglodging_click" commandargument='<%# eval("itemtypeid") %>'                     runat="server" imageurl='<%# eval("photo") %>' width="150px" height="120px" />                 </td>                                <td style="width:180px">                 <b>name</b><br />                  <span><%# eval("itemtypename") %></span><br />                 <b>occupancy</b>&nbsp;<span><%# eval("occupancy") %></span>                     <br />&nbsp;                     <asp:panel id="placeholderammenities"  runat="server" visible="true" ></asp:panel>                  </td>                 <td style="width:100px">                                         <b>room</b><br />                      <asp:hiddenfield runat="server"  id="hdnitemtypeid" value='<%# eval("lodgingitemtypeid") %>' />                      <asp:dropdownlist id="ddlavailable"  runat="server"                        appenddatabounditems="true" selectedvalue='<%# bind("lodgingreservationsavailable") %>' >                          <asp:listitem value="0" text="0"/>                          <asp:listitem value="1" text="1"/>                          <asp:listitem value="2" text="2"/>                      </asp:dropdownlist>                                    </td>                 <td>                  </td>                 <td style="width:100px">                     <div id="dvadult" runat="server"></div>                     <asp:placeholder runat="server" id="placeholderadult" viewstatemode="enabled" enabletheming="false" visible="true" ></asp:placeholder>                 </td>                 <td style="width:50px">                       <asp:label runat="server"  id="lblnumbernight" ></asp:label>                 </td>                 <td style="width:50px">                       <asp:placeholder id="placeholderprice" runat="server" visible="true"></asp:placeholder>                 </td>                 <td style="width:50px">                  <b>total</b><br />                      <asp:label runat="server" id="lbltotalamount" ></asp:label>                 </td>                 <td style="width:100px">                  <asp:button id="btnbookroom" runat="server" text="book rooms" cssclass="submit_butt" />                 </td>             </tr>                    </table>     </itemtemplate>     <separatorstyle backcolor="lime" font-bold="false" font-italic="false" font-overline="false" font-strikeout="false" font-underline="false" horizontalalign="center" /> </asp:datalist> </contenttemplate> </asp:updatepanel> 

datalist item data bound event code (its inside image binding , price related field add , creating dynamic control per condition)

  protected void dllodgingavailabledetails_itemdatabound(object sender, datalistitemeventargs e)     {         try         {             if (e.item.itemtype == listitemtype.item || e.item.itemtype == listitemtype.alternatingitem)             {                                     image img = e.item.findcontrol("imglodging") image;                 if (img != null)                 {                     string bytesval = ((system.data.datarowview)(e.item.dataitem)).row.itemarray[3].tostring();                     if (string.isnullorwhitespace(bytesval)) return;                     byte[] bytes = (byte[])((system.data.datarowview)(e.item.dataitem)).row.itemarray[3];                     string base64string = convert.tobase64string(bytes, 0, bytes.length);                     img.imageurl = "data:image/png;base64," + base64string;                 }                 dropdownlist ddllist = e.item.findcontrol("ddlavailable") dropdownlist;                 label lbldipositamount = e.item.findcontrol("lbltotalamount") label;                 label lblnumbernight = e.item.findcontrol("lblnumbernight") label;                 var placeholderammenities = e.item.findcontrol("placeholderammenities") panel;                 ddllist.attributes.add("onchange", " openlodgingnumber1(this,'" + ddllist.selectedvalue + "');");                 int? lodgingitemtypeid = convert.toint32(((system.data.datarowview)(e.item.dataitem)).row.itemarray[1]);                 dataset ds = new dataset();                 ds = lodgingdata.selectlodgingitemtypeamenitydateset(lodgingitemtypeid);                  datatable dt = new datatable();                 if (ds != null)                 {                     dt = ds.tables[0];                     if (dt.rows.count > 0)                     {                         (int j = 0; j < dt.rows.count; j++)                         {                             image image = new image();                             image.id = "imgammenities" + j + datetime.now.tostring();                             string bytesval = dt.rows[j]["amenityicon"].tostring(); //((system.data.datarowview)(e.item.dataitem)).row.itemarray[4].tostrin();                             //if (string.isnullorwhitespace(bytesval)) return;                             if (bytesval != string.empty)                             {                                 byte[] bytes = (byte[])dt.rows[j]["amenityicon"];                                 string base64string = convert.tobase64string(bytes, 0, bytes.length);                                 image.imageurl = "data:image/png;base64," + base64string;                                 image.height = 20;                                 image.width = 20;                                 image.enableviewstate = true;                                                                     placeholderammenities.controls.add(image);                                 placeholderammenities.controls.add(new literalcontrol("&nbsp;"));                             }                         }                     }                 }                  decimal pricetotal = 0;                 var placeholderprice = e.item.findcontrol("placeholderprice") placeholder;                 dataset dsprice = new dataset();                 dsprice = lodgingdata.selectlodgingitemtypeprice(lodgingitemtypeid);                 if (dsprice != null)                 {                     datatable dtprice = new datatable();                     dtprice = dsprice.tables[0];                     if (dtprice.rows.count > 0)                     {                         datetime fromdate = convert.todatetime(txtfromdate.text);                         datetime todate = convert.todatetime(txttodate.text);                         double daterange = ((todate - fromdate).totaldays + 1);                         lblnumbernight.text = daterange.tostring();                          //for (datetime date = fromdate; date >= todate; date.adddays(1))                         (int d = 0; d < convert.toint32(daterange); d++ )                         {                             datetime date = fromdate.adddays(d);                             //dataview dv = new dataview(dtprice);                             datatable dtprice1 = new datatable();                             datarow[] rows = dtprice.select("#" + date + "# >= pricestartdate and" + "#" + date + "# <= priceenddate");                                        if (rows.length > 0)                             {                                 dtprice1 = rows.copytodatatable();                             }                             if (dtprice1.rows.count > 0)                             {                                 (int j = 0; j < dtprice1.rows.count; j++)                                 {                                     label lbl = new label();                                     string dayofweek = dtprice1.rows[j]["dayofweekid"].tostring();                                     if (dayofweek.trim() == edayofweek.all.tostring().trim())                                     {                                         lbl.id = "lbl" + j;                                         lbl.text = dtprice1.rows[j]["price"].tostring();                                         pricetotal += convert.todecimal(dtprice1.rows[j]["price"]);                                                                                     placeholderprice.controls.add(lbl);                                         placeholderprice.controls.add(new literalcontrol("<br />"));                                     }                                     else if (convert.toint32(dayofweek) == convert.toint32(date.dayofweek + 1))                                     {                                         lbl.id = "lbl" + j;                                         lbl.text = dtprice1.rows[j]["price"].tostring();                                         pricetotal += convert.todecimal(dtprice1.rows[j]["price"]);                                         placeholderprice.controls.add(lbl);                                         placeholderprice.controls.add(new literalcontrol("<br />"));                                     }                                 }                             }                             else                             {                                 dataview dv1 = new dataview(dtprice);                                 dv1.rowfilter = "pricestartdate null or priceenddate null";                                 //dv1.rowfilter = "pricestartdate == null ,  priceenddate == null";                                 datatable dtprice2 = new datatable();                                 dtprice2 = dv1.totable();                                 (int j = 0; j < dtprice2.rows.count; j++)                                 {                                     label lbl = new label();                                     string dayofweek = dtprice2.rows[j]["dayofweekid"].tostring();                                     if (dayofweek.trim() == edayofweek.all.tostring().trim())                                     {                                         lbl.id = "lbl" + j;                                         lbl.text = dtprice2.rows[j]["price"].tostring();                                         pricetotal += convert.todecimal(dtprice2.rows[j]["price"]);                                         placeholderprice.controls.add(lbl);                                         placeholderprice.controls.add(new literalcontrol("<br />"));                                     }                                     else if (convert.toint32(dayofweek) == convert.toint32(date.dayofweek + 1))                                     {                                         lbl.id = "lbl" + j;                                         lbl.text = dtprice2.rows[j]["price"].tostring();                                         pricetotal += convert.todecimal(dtprice2.rows[j]["price"]);                                         placeholderprice.controls.add(lbl);                                         placeholderprice.controls.add(new literalcontrol("<br />"));                                      }                                 }                             }                         }                     }                 }                 lbldipositamount.text = pricetotal.tostring();                 // var amount = ((system.data.datarowview)(e.item.dataitem)).row.itemarray[3];                 int selectedvalue = convert.toint32(ddllist.selecteditem.text);                 if (selectedvalue != 0)                 {                     double totalamount = selectedvalue * convert.todouble(pricetotal);                     lbldipositamount.text = totalamount.tostring();                 }             }         }         catch (exception)         {             throw;         }     } 

on dynamically genereted dropdown selection event fired

in above add dropdown dynamically, when control's event called , further dynamic control adding per condition.

issue event remove dynamic other control other row of previous selection hidden or lost , retain dynamic control in post , event fire.

protected void ddlavailable_selectedindexchanged(object sender, eventargs e)     {         // if (usercontroltextboxchanged != null) dllodgingavailabledetails_itemdatabound(sender, e);         //dllodgingavailabledetails.itemdatabound += new datalistitemeventhandler(dllodgingavailabledetails_itemdatabound);         double amount = 0;         var ddllist = (dropdownlist)sender;         var row = (datalistitem)ddllist.namingcontainer;         //get id of row         dataset ds = new dataset();         int? id = convert.toint32(((hiddenfield)row.findcontrol("hdnitemtypeid")).value);         double? tamount = convert.todouble(((label)row.findcontrol("lbltotalamount")).text);         int? groupid = convert.toint32(ddllodginggroup.selectedvalue);         int selectedvalue = convert.toint32(ddllist.selecteditem.text);         datetime? startdate = convert.todatetime(txtfromdate.text);         datetime? enddate = convert.todatetime(txttodate.text);         ds = lodgingdata.selectlodgingitemtypedataset(startdate, enddate, groupid);         datatable dt = new datatable();         dataview dv = new dataview();         if (ds != null)         {             dt = ds.tables[0];             dv = dt.defaultview;             dv.rowfilter = "lodgingitemtypeid=" + id;         }         dt = dv.totable();         if (dt.rows.count > 0)         {             if (tamount != null)             {                 amount = convert.todouble(tamount);             }         }         //amount = convert.todouble(((label)row.findcontrol("lbltotalamount")).text);                     var placeholder1 = ((placeholder)row.findcontrol("placeholderadult"));         double totalamount = 0;         if (selectedvalue != 0)         {             totalamount = selectedvalue * convert.todouble(amount);             ((label)row.findcontrol("lbltotalamount")).text = totalamount.tostring();             label lbladult = new label();             lbladult.id = "lbladult";             lbladult.text = "adult";             lbladult.font.bold = true;             placeholder1.controls.add(lbladult);             placeholder1.controls.add(new literalcontrol("<br />"));         }         else         {             totalamount = amount;         }         (int j = 0; j < selectedvalue; j++)         {             dropdownlist combobox = new dropdownlist();             combobox.id = "combobox" + j;             combobox.autopostback = false;             combobox.attributes.add("runat", "server");             combobox.items.add(new listitem("0", "0"));             combobox.items.add(new listitem("1", "1"));             combobox.items.add(new listitem("2", "2"));             combobox.selectedindexchanged += new eventhandler(dynamic_method);             placeholder1.controls.add(combobox);             placeholder1.controls.add(new literalcontrol("<br />"));         }     } 

i'm not sure how solve you, here example of preserving row of data in gridview templatefield containing dynamically generated dropdownlist

i broke process 2 parts 1) save data in gridview session variable 2) recreate, source, , bind controls

here's saving values in gridview. use recursive find control formula found on site (but don't remember where) because controls generated , placed inside gridview row without unique names. ex. tbxa exists in row 1 different tbxa in row 2. may not apply - the key find controls want save values of.

private sub savevalues()     dim savedtable new datatable     savedtable.columns.add(new datacolumn("a"))     = 0 gridview1.rows.count - 1         dim existing(0) object         existing(0) = trycast(findcontrolrecursive(gridview1.rows(i), "ddla"), dropdownlist).selectedvalue         savedtable.rows.add(existing)     next     session("ghosttable") = savedtable end sub 

then in page_load under(when postback) set gridview datasource session variable, , databind it. trigger following code every row: keep in mind have datasource of dropdown list stored in session variable on page load. allows datasource , databind occur dropdown every time generated.

protected sub onrowdatabound(sender object, e gridviewroweventargs) handles gridview1.rowdatabound     'handles databinding of each gridview1 row ddl gridview templatefield     if e.row.rowtype = datacontrolrowtype.datarow         dim ddla new dropdownlist()         ddla.datasource = session("lengthlist")         ddla.databind()         ddla.id = "ddla"         ddla.selectedvalue = trycast(e.row.dataitem, datarowview).row.item("a").tostring()         e.row.cells(1).controls.add(ddla)     end if end sub 

the ddla.selectedvalue = trycast(e.row.dataitem, datarowview).row.item("a").tostring() preserves data after postback. determines row being bound, , repopulates control whatever was.

hope helps!

to make sure gridview populated every time, call savevalues in event handlers.

protected sub ddlempnumber_selectedindexchanged(sender object, e eventargs) handles ddlempnumber.selectedindexchanged      'do whatever on selected index change, following:      call savevalues()      gridview1.datasource = session("ghosttable")      gridview1.databind() end sub 

Comments

Popular posts from this blog

Email notification in google apps script -

c++ - Difference between pre and post decrement in recursive function argument -

javascript - IE11 incompatibility with jQuery's 'readonly'? -