Viewstate and Tab container - asp.net

I have the following code for a tab container and i am able to create a tab dynamically but as soon as i try to click to add another tab the previous tab disappears, i can't figure out how to keep viewstate, can someone please help me with this.
test5.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeFile="test5.aspx.cs" Inherits="test5" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<cc1:tabcontainer id="TabContainer1" visible="true" runat="server" Height="150px">
<cc1:TabPanel ID="Tab0" runat="server" HeaderText="Step 1">
<ContentTemplate>
Test
<asp:Button ID="add" Text="Add" OnClick="add_Click" runat="server" />
</ContentTemplate>
</cc1:TabPanel>
</cc1:tabcontainer>
</div>
</form>
</body>
</html>
test5.aspx.cs
using AjaxControlToolkit;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class test5 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void add_Click(object sender, EventArgs e)
{
int currentTab = TabContainer1.ActiveTabIndex;
int nextTab = currentTab + 1;
Button btn = new Button();
btn.ID = "Add" + nextTab.ToString();
btn.Text = "Add";
btn.Click += new EventHandler(add_Click);
TabPanel t = new TabPanel();
t.ID = "Tab" + nextTab;
t.HeaderText = "Tab:" + nextTab;
t.Controls.Add(btn);
TabContainer1.Tabs.Add(t);
}
}

Here's what I'd do:
Wrap the following code:
Button btn = new Button();
btn.ID = "Add" + nextTab.ToString();
btn.Text = "Add";
btn.Click += new EventHandler(add_Click);
TabPanel t = new TabPanel();
t.ID = "Tab" + nextTab;
t.HeaderText = "Tab:" + nextTab;
t.Controls.Add(btn);
TabContainer1.Tabs.Add(t);
Into its own method called RenderDynamicTabs(int nextTab)
At the end of add_Click, add this code:
if(null == ViewState["NumDynamicControls"])
{
ViewState["NumDynamicControls"] = 0;
}
var dynamicControlCount = int.Parse(ViewState["NumDynamicControls"]);
dynamicControlCount++;
In Page_Load, add the following:
if(null != ViewState["NumDynamicControls"])
{
// There are controls that need to be re-generated
var dynamicControlCount = int.Parse(ViewState["NumDynamicControls"]);
for(int i = 1; i <= dynamicControlCount; i++)
{
RenderDynamicTabs(i);
}
}
That should both store and re-render your controls after each PostBack.
Finally, to avoid duplication of code, in add_Click, replace the code you copy-pasted into RenderDynamicTabs with just a call to RenderDynamicTabs(nextTab);.

i removed the additions i added before, but here is what i got so far
using AjaxControlToolkit;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class test5 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (null != ViewState["NumDynamicControls"])
{
// There are controls that need to be re-generated
var dynamicControlCount = int.Parse(ViewState["NumDynamicControls"].ToString());
for (int i = 1; i <= dynamicControlCount; i++)
{
RenderDynamicTabs(i);
}
}
}
public void RenderDynamicTabs(int nextTab)
{
Button btn = new Button();
btn.ID = "Add" + nextTab.ToString();
btn.Text = "Add";
btn.Click += new EventHandler(add_Click);
TabPanel t = new TabPanel();
t.ID = "Tab" + nextTab;
t.HeaderText = "Tab:" + nextTab;
t.Controls.Add(btn);
TabContainer1.Tabs.Add(t);
}
protected void add_Click(object sender, EventArgs e)
{
int currentTab = TabContainer1.ActiveTabIndex;
int nextTab = currentTab + 1;
RenderDynamicTabs(nextTab);
if (null == ViewState["NumDynamicControls"])
{
ViewState["NumDynamicControls"] = 0;
}
var dynamicControlCount = int.Parse(ViewState["NumDynamicControls"].ToString());
dynamicControlCount = dynamicControlCount + 1;
}
}

Related

Creating dynamic button and its event handler

I am trying to use dynamics buttons and events. When I clicked static button and I showed dynamic button. But When I clicked dynamic button I didn't work dinamikButon_Click event. What is my wrong? Sorry my language. Thx in advance.
Default.aspx.cs is below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace TestWebApplication
{
public partial class _Default : Page
{
int i = 1;
Button dinamikButon;
protected void Page_Load( object sender, EventArgs e )
{
}
protected void btnStatik_Click( object sender, EventArgs e )
{
dinamikButon = new Button
{
Text = "Dinamik" + i,
ID = "btnDinamik" + i,
CommandArgument = "commandArgument",
CommandName = "commandName"
};
dinamikButon.Click += dinamikButon_Click;
panel1.Controls.Add( dinamikButon );
i++;
}
void dinamikButon_Click( object sender, EventArgs e )
{
Label1.Text = "Merhaba dinamik butondan geliyorum.";
}
}
}
that's because when the page posts back the button doesn't exist. You have to create the buttons on page Load or PreInit. Microsoft suggests PreInit You can dynamically set a master page or a theme for the requested page, and create dynamic controls.
int i = 1;
Button dinamikButon;
private void Page_PreInit(object sender, EventArgs e)
{
if(Page.IsPostBack)
{
CreateButton();
}
}
protected void btnStatik_Click( object sender, EventArgs e )
{
CreateButton();
}
private void CreateButton()
{
dinamikButon = new Button
{
Text = "Dinamik" + i,
ID = "btnDinamik" + i,
CommandArgument = "commandArgument",
CommandName = "commandName"
};
dinamikButon.Click += dinamikButon_Click;
panel1.Controls.Add( dinamikButon );
i++;
}
Update:
Do do what you've asked now we have to specify that the button has been created using either viewstate, querystring or session.
In this example I'll use a session:
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
if (Page.IsPostBack)
{
if (Session["Created"] != null)
{
CreateButton();
}
}
}
private void CreateButton()
{
dinamikButon = new Button
{
Text = "Dinamik" + i,
ID = "btnDinamik" + i,
CommandArgument = "commandArgument",
CommandName = "commandName"
};
Panel1.Controls.Add(dinamikButon);
dinamikButon.Click += dinamikButon_Click;
i++;
Session["Created"] = "true";
}
private void dinamikButon_Click(object sender, EventArgs e)
{
//your action here
}
To fill value in "Label1" control using dynamic button
Default.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="DynamicCtrl._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" language="javascript">
function dynamicevnt() {
document.getElementById("Label1").innerHTML = "Merhaba dinamik butondan geliyorum.";
return false;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="btnStatik" runat="server" Text="Click" OnClick="btnStatik_Click" />
<asp:Label ID="Label1" runat="server"></asp:Label>
<asp:Panel ID="panel1" runat="server">
</asp:Panel>
</div>
</form>
</body>
</html>
Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace DynamicCtrl
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnStatik_Click(object sender, EventArgs e)
{
CreateButton();
}
private void CreateButton()
{
int i = 1;
Button dinamikButon = new Button();
dinamikButon.Text = "Dinamik" + i;
dinamikButon.ID = "btnDinamik" + i;
dinamikButon.OnClientClick = "return dynamicevnt();";
dinamikButon.Click += new EventHandler(dinamikButon_Click);
panel1.Controls.Add(dinamikButon);
i++;
}
protected void dinamikButon_Click(object sender, EventArgs e)
{
Label1.Text = "Merhaba dinamik butondan geliyorum.";
}
}
}

iTextSharp - corrupt PDF and document close error

This is very close to working. Not sure why I am getting an error at document.Close() or why I am getting a corrupt pdf when I delete document.Close().
It seems to not be posting any info to the pdf.
The code:
Main page with the button the user clicks:
<%# Control Language="C#" AutoEventWireup="true" CodeFile="EventList.ascx.cs"
Inherits="Objects_EventList" %>
<asp:ListView runat="server" ID="lstvwEvents"
OnItemDataBound="lstvwEvents_OnItemDataBound">
<LayoutTemplate>
<asp:ImageButton BorderStyle="0" CssClass="submitbutton" runat="server" AlternateText="Get PDF" ID="LinkButton1" OnClick="btnGenerateReport" />
<div class="eventtease" style="width: 249px;border-bottom: 1px solid #c0c06b;padding-right: 10px;padding-top: 10px;height: 300px;overflow: auto;">
<asp:Literal runat="server" ID="itemPlaceholder" />
<div style="clear: both;"></div>
</div>
</LayoutTemplate>
<ItemTemplate>
<h3 style="clear: both;border-top: 1px solid #c0c06b;padding-top: 10px;"><asp:Literal runat="server" ID="ltrlShortDate" /><br /><%# Eval("EventName").ToString().ToUpper() %><br />(<asp:Literal runat="server" ID="ltrlTimes" />)</h3>
<p class="eventdescription" style="font: normal normal normal 7.5pt/normal Arial, Sans-Serif;margin-top: 3px;">
<%# Eval("Description") %>
</p>
<asp:HyperLink runat="server" ID="lnkLearnMore" Text="LEARN MORE" CssClass="learnmore" Visible="false" />
</ItemTemplate>
Here is the code behind:
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;
using System.IO;
public partial class Objects_EventList : System.Web.UI.UserControl
{
public string city;
public int showcount;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Load_Events();
};
}
protected void Load_Events()
{
EventsDataContext edc = new EventsDataContext();
var events = (from e in edc.tblEvents_Cafes
where e.EventDateTime >= DateTime.Now && e.VenueCity.Trim() == city.Trim() && (e.VenueName.Contains("Café") || e.VenueName.Contains("Cafe") )
orderby e.EventDateTime
select new
{
EventName = e.EventName,
EventDate = e.EventDate,
EventTime = e.EventTime,
Description = edc.tblEvents_Cafe_Descriptions.OrderBy(d => d.Priority).Where(d => d.Keywords.ToLower() == e.EventName.ToLower()).Select(d => d.Description).First(), // edc.tblEvents_Cafe_Descriptions.OrderBy(d => d.Priority).Where(d => d.Keywords.ToLower() == e.EventName.ToLower() || d.Keywords.ToLower().CompareTo(e.EventName.ToLower()) >= 0).Select(d => d.Description).First()
}).Take(showcount);
lstvwEvents.DataSource = events;
lstvwEvents.DataBind();
}
protected void lstvwEvents_OnItemDataBound(Object sender, ListViewItemEventArgs e)
{
ListViewDataItem dataItem = (ListViewDataItem)e.Item;
if (e.Item.ItemType == ListViewItemType.DataItem)
{
var tempevent = dataItem.DataItem;
Type t = tempevent.GetType();
DateTime tempdate;
if (DateTime.TryParse((t.GetProperty("EventDate").GetValue(tempevent, null)).ToString(), out tempdate))
{
Literal ltrlShortDate = new Literal();
ltrlShortDate = (Literal)e.Item.FindControl("ltrlShortDate");
ltrlShortDate.Text = tempdate.ToString("MM/dd/yyyy");
}
if (DateTime.TryParse((t.GetProperty("EventTime").GetValue(tempevent, null)).ToString(), out tempdate))
{
Literal ltrlTimes = new Literal();
ltrlTimes = (Literal)e.Item.FindControl("ltrlTimes");
ltrlTimes.Text = tempdate.ToString("hh:mm tt");
}
}
}
private void GeneratePDF(string path, string fileName, bool download, string text)
{
var document = new Document();
try {
if (download) {
PdfWriter.GetInstance(document, Response.OutputStream);
} else {
PdfWriter.GetInstance(document, new FileStream(path + fileName, FileMode.Create));
}
StringBuilder strB = new StringBuilder();
document.Open();
if (text.Length.Equals(0)) {
lstvwEvents.DataBind();
using (StringWriter sWriter = new StringWriter(strB)) {
using (HtmlTextWriter htWriter = new HtmlTextWriter(sWriter)) {
ListView lv1 = lstvwEvents;
lv1.RenderControl(htWriter);
}
}
} else {
strB.Append(text);
}
using (TextReader sReader = new StringReader(strB.ToString())) {
List<IElement> list = HTMLWorker.ParseToList(sReader, new StyleSheet());
foreach (IElement elm in list) {
document.Add(elm);
}
}
} catch (Exception ee) {
ee.ToString();
} finally {
document.Close();
}
}
protected void btnGenerateReport(object sender, EventArgs e)
{
string fileName = "Calendar.pdf";
GeneratePDF("", fileName, true, "");
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
Response.Flush();
Response.End();
}
}

ASP.NET Eventhandler Not working

I have a pretty straight forward dynamically generated asp page. This is my first time using dynamically generated asp controls. The table renders correctly, however when I click on the "Query" button I cannot get the event to connect to the "OnClick" method. I get a webpage error "'ButtonClick' is undefined". I have stripped and simplified the code down for brevity.
DeviceStatus.aspx
<%# Page Title="Device Status" Language="C#" MasterPageFile="Secure.master"
'AutoEventWireup="true" CodeFile="DeviceStatus.aspx.cs" Inherits="Devices" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent"></asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<div id="selectDiv" runat="server"></div>
</asp:Content>
DeviceStatus.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Devices : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e) {
int i, NumberOfDevices = 3;
string Contents;
string[] number = new string[] { "1", "2", "3"};
string[] name = new string[] {"mike", "bob", "cindy"};
string[] location = new string[] { "Austin", "Miami", "Atlanta" };
// Create event binding
PlaceHolder Placeholder1 = new PlaceHolder();
Button button = new Button();
button.Text = "Click";
button.Click += new System.EventHandler(ButtonClick);
Placeholder1.Controls.Add(button);
//Create Form and table header
Contents = "<form runat=\"server\"><table border=\"1\" >";
Contents += "<tr><th>Select</th><th>Number</th><th>Name</th><th>Status</tr>";
// Repeat for each table row
for (i = 0; i < NumberOfDevices; i++) {
// Creat each row
Contents += "<tr><td><asp:Button ID=\"row" + i + "\""
+ "runat=\"server\"OnClick=\"ButtonClick\" >Query</asp:Button></td>"
+ "<td>" + number[i] + "</td><td>" + name[i] + "</td><td>"
+ location[i] + "</td></tr>";
}
// Cleanup
Contents += "</table>";
Contents += "<asp:PlaceHolder ID=\"Placeholder1\" runat=\"server\"></asp:PlaceHolder>";
Contents += "</form>";
Contents += "</asp:Content>";
//Place dynamic asp controls in webpage
selectDiv.InnerHtml = Contents;
}
protected void ButtonClick(object sender, EventArgs e)
{
Response.Redirect("DataRendering.aspx");
}
}
I went with Garrison's suggestion. It took some time to get through the code to figure it out but once completed was the most straight forward solution. Thanks everyone for contributing.

Dynamic user control loses data while switching between views in multiview

I have a MultiView with two views (first one with form and second one to review data entered in first view). First view contains a TextBox and a PlaceHolder. The PlaceHolder is used to hold dynamically added add UserControl. UserControl contains DropDownList(s), TextBox, and CheckBox.
Working fine: Currently I can add new user control in the page through a Add button, which causes the page to PostBack but I do not lose any data in existing dynamic UserControl.
Issue: When I toggle between the views (using SetActiveView), I lose data in dynamically added user control but the data in the static TextBox remains intact.
Following I have the code snippet.
<%# Page Title="" Language="C#" MasterPageFile="~/M.master" AutoEventWireup="true" CodeFile="test.aspx.cs" Inherits="test" %>
<%# Reference Control="dynamic_uc.ascx" %>
<%# Register src="dynamic_uc.ascx" tagname="ucrange" tagprefix="uc1" %>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<div class="light_blue_background pad10 helvetica innerpad5">
<asp:MultiView ID="mv_main" runat="server" ActiveViewIndex="0">
<asp:View ID="vu_add" runat="server">
<table>
<tr style="border-bottom: 1px solid #ccc;">
<td>
Name:
</td>
<td>
<asp:TextBox ID="txt_Name" runat="server" Columns="50" MaxLength="35" />
</td>
</tr>
</table>
<asp:Panel ID="pnl_TempRange_" runat="server">
</asp:Panel>
<asp:PlaceHolder ID="pl_Range" runat="server"></asp:PlaceHolder>
</asp:View>
<asp:View ID="vu_review" runat="server">
review your data
</asp:View>
</asp:MultiView>
<asp:Button ID="btn_addRange" runat="server" Text="Add Range"
CausesValidation="False" onclick="btn_addRange_Click" />
<asp:Button ID="btn_submit" runat="server" Text="Submit"
onclick="btn_submit_Click" />
<asp:Button ID="btn_modify" runat="server" Text="Modify"
onclick="btn_modify_Click" Visible="false"/>
</div>
</asp:Content>
C# Code:
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
public partial class Test : System.Web.UI.Page
{
private static int ControlCount=0;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
ControlCount = 0;
}
AddControls();
foreach (Control c in pnl_TempRange.Controls)
{
DropDownList ddl_UpLimit = (DropDownList)c.FindControl("ddl_Uplimit");
PopulateDropdownRange(ddl_UpLimit, 0, 100);
DropDownList ddl_LowLimit = (DropDownList)c.FindControl("ddl_Lowlimit");
PopulateDropdownRange(ddl_LowLimit, 0, 100);
}
Response.Write(tests);
}
public static Control GetPostBackControl(Page page)
{
Control control = null;
string ctrlname = page.Request.Params.Get("__EVENTTARGET");
if (ctrlname != null && ctrlname != string.Empty)
{
control = page.FindControl(ctrlname);
}
else
{
foreach (string ctl in page.Request.Form)
{
Control c = page.FindControl(ctl);
if (c is System.Web.UI.WebControls.Button)
{
control = c;
break;
}
}
}
return control;
}
private void AddControls()
{
int ID = 0;
Control cd = GetPostBackControl(Page);
if ((c != null))
{
if (c.ID.ToString() == "btn_addRange")
{
dynamic_uc++;
}
}
pl_Range.Controls.Clear();
for (int i = 0; i <= tempControlCount; i++)
{
Range DynamicUserControl = (Range)Page.LoadControl("dynamic_uc.ascx");
while (IsInDeletedLog("uc" + ID) == true)
{
ID += 1;
}
DynamicUserControl.ID = "dyn_uc" + ID;
DynamicUserControl.RemoveTempControl += this.HandleRemoveTempRange;
pl_Range.Controls.Add(DynamicUserControl);
ID += 1;
}
}
protected void btn_addRange_Click(object sender, EventArgs e)
{
}
private void PopulateDropdownRange(DropDownList ddl, int rangeMin, int rangeMax)
{
ddl.Items.Clear();
ddl.Items.Add("--Select--");
for (int i = rangeMin; i <= rangeMax; i++)
{
ddl.Items.Add(new ListItem(i.ToString(),i.ToString()));
}
}
private void BindDDl(DropDownList ddl,string strQuery)
{
ddl.DataSource = GetDataFromQuery(strQuery);
ddl.DataValueField = "VALUE";
ddl.DataTextField = "NAME";
ddl.DataBind();
ddl.Items.Insert(0,"--Select--");
}
protected void btn_submit_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
mv_main.SetActiveView(vu_reviewCmpd);
btn_submitCompound.Visible = false;
btn_confirmCompound.Visible = true;
btn_modifyCompound.Visible = true;
}
}
protected void btn_modify_Click(object sender, EventArgs e)
{
mv_main.SetActiveView(vu_add);
btn_submit.Visible = true;
btn_confirm.Visible = false;
btn_modify.Visible = false;
}
Thanks for the help.

Duplicate Panel/List IDs upon recreating my List(s) of Controls

When I click my Remove button it is my intent to remove the Panel, then iterate through the remaining panels and give them a new ID from scratch I.E. if I removed Panel(3) from a list of 6 Panels I would iterate through and give them all new IDs Panels 0-5.
My issue is that I keep running into an error after I delete my panel where I have duplicate ID names. For the life of me I cannot see where I am going wrong so I am reaching out hoping I am just blind or for advice.
I was setting a breakpoint at my btnDelete function and step through it but I am not seeing my logic shortcoming in why I experience an issue with multiple Panels of the same ID.
ASPX:
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage/MasterPage.master" AutoEventWireup="true" CodeFile="Search.aspx.cs" Inherits="Search" EnableTheming="true" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
<link href="App_Themes/ui-lightness/jquery-ui-1.7.2.custom.css" rel="stylesheet"
type="text/css" />
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css"
rel="stylesheet" type="text/css" />
<script src="Includes/JavaScript/jquery-1.7.1.js" type="text/javascript"></script>
<script src="Includes/JavaScript/jquery.ui.datepicker.js" type="text/javascript"></script>
<script src="Includes/JavaScript/jquery.ui.widget.js" type="text/javascript"></script>
<script src="Includes/JavaScript/jquery.ui.core.js" type="text/javascript"></script>
<%--Script for the Dropdown Datepicker--%>
<script type="text/javascript">
$(function () {
$("input.datepicker").datepicker({ showOn: 'button', buttonImage: 'Includes/Images/calender.gif', buttonImageOnly: false, onSelect: function () { }
});
});
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder2" runat="Server">
<h1>
Search
<asp:HyperLink ID="HyperLink1" runat="server" ImageUrl="Includes/Images/action_help.gif"
NavigateUrl="~/user_manual.pdf" Target="_blank" ToolTip="Search Help"></asp:HyperLink></h1>
<table border="0" cellpadding="6" cellspacing="0">
<tr>
<td>
<asp:Button ID="btnAdd" runat="server" Text="Add Control" onclick="btnAdd_Click" />
<asp:Button ID="btnClear" runat="server" Text="Reset" onclick="btnClear_Click" />
<asp:Button ID="btnSearch" runat="server" Text="Search" OnClick="btnSearch_Click" />
</td>
<td>
<asp:TextBox ID="txtTitle" class="searchPage" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:PlaceHolder ID="myPlaceholder" runat="server"></asp:PlaceHolder>
</td>
Code behind:
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Runtime.Serialization;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
public partial class Search : BasePage
{
List<Users> userroles = new List<Users>();
//Panel that contains all our Dynamically added user controls.
List<Panel> persistControls = new List<Panel>();
public int userid = 0;
public byte IsActive = 1;
public int error = 0;
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
}
// Calls three functions responsible for pulling from the Database and binding the Datagrid.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetClustersFromDB(userid);
BindGrid();
BindState();
}
else
{
// Where I am recreating my controls.
DynamicQueryRecreateLogic();
}
}
protected void DynamicQueryRecreateLogic()
{
if (Session["persistControls"] != null)
{
// Local Value that contains the members of the current persistControls session, not yet pushed to the page.
persistControls = (List<Panel>)Session["persistControls"];
int count = 0;
foreach (Panel panel in persistControls)
{
//AddQuestionTypeDropDownList(count);
panel.ID = "panel" + "(" + count.ToString() + ")";
foreach (Control control in panel.Controls)
{
if (control.GetType() == typeof(DropDownList))
{
control.ID = "list" + "(" + count.ToString() + ")";
DropDownList list = (DropDownList)panel.FindControl(control.ID);
list.SelectedIndexChanged += new EventHandler(list_SelectedIndexChanged);
}
if (control.GetType() == typeof(TextBox))
{
control.ID = "txtBox" + "(" + count.ToString() + ")";
}
}
// Re-Adding our Remove Button
Button btnRemove = new Button();
btnRemove.Click += new EventHandler(btnDelete_Click);
btnRemove.Text = "Remove";
btnRemove.CommandArgument = count.ToString();
// Pushing to Placeholder
myPlaceholder.Controls.Add(panel);
myPlaceholder.Controls.Add(btnRemove);
count++;
}
}
}
private DropDownList AddQuestionTypeDropDownList()
{
DropDownList list = new DropDownList();
list.ID = "list" + "(" + persistControls.Count.ToString() + ")";
list.Items.Add(new ListItem("--Select One--", ""));
list.Items.Add(new ListItem("Title", "1"));
list.Items.Add(new ListItem("Contact", "2"));
list.Items.Add(new ListItem("Date Created", "3"));
list.SelectedIndexChanged += new EventHandler(list_SelectedIndexChanged);
list.AutoPostBack = true;
return list;
}
private TextBox AddFieldTypeTextBox(int count)
{
TextBox box = new TextBox();
box.ID = "txtBox" + "(" + count.ToString() + ")";
return box;
}
protected void btnAdd_Click(object sender, EventArgs e)
{
try
{
Panel panelContainer = new Panel();
panelContainer.ID = "panel" + "(" + persistControls.Count.ToString() + ")";
panelContainer.Controls.Add(AddQuestionTypeDropDownList());
Button btnRemove = new Button();
btnRemove.Click += new EventHandler(btnDelete_Click);
btnRemove.Text = "Remove";
btnRemove.CommandArgument = persistControls.Count.ToString();
persistControls.Add(panelContainer);
myPlaceholder.Controls.Add(panelContainer); // Pushes the Panel to the page.
myPlaceholder.Controls.Add(btnRemove); // Pushes our Button to the page.
Session["persistControls"] = persistControls; // put it in the session
}
catch
{
throw;
}
}
protected static string DecipherCountNumber(string IDHolder)
{
int start = IDHolder.IndexOf("(");
if (start == -1)
{
return IDHolder;
}
else
{
return IDHolder.Substring(start + 1).Replace(")", string.Empty);
}
}
protected void list_SelectedIndexChanged(object sender, EventArgs e)
{
//I need to fix the dynamic Add location. I need to track some type of enumeration or attributes of the panel for recreation.
try
{
DropDownList list = (DropDownList)sender;
string IDHolder = list.ID.ToString();
int count = Convert.ToInt32(DecipherCountNumber(IDHolder));
Panel panelContainer = persistControls.Find(delegate(Panel panel) { return panel.ID == "panel" + "(" + count.ToString() + ")"; });
if (list.SelectedIndex == 1)
{
//panelContainer.Controls.Add(AddFieldTypeTextBox(count));
}
if (list.SelectedIndex == 2)
{
//panelContainer.Controls.Remove(FindControl("txtBox" + "(" + count.ToString() + ")"));
}
if (list.SelectedIndex == 3)
{
//panelContainer.Controls.Remove(FindControl("txtBox" + "(" + count.ToString() + ")"));
}
Session["persistControls"] = persistControls;
}
catch
{
throw;
}
}
protected void btnClear_Click(object sender, EventArgs e)
{
try
{
Session["persistControls"] = null;
Response.Redirect(Request.Url.ToString());
}
catch
{
throw;
}
}
protected void btnDelete_Click(object sender, EventArgs e)
{
try
{
int deleteThisOne = int.Parse(((Button)sender).CommandArgument);
persistControls.Remove(persistControls[deleteThisOne]);
Session["persistControls"] = persistControls;
Response.Redirect(Request.Url.ToString(), false);
}
catch
{
throw;
}
}
I modified my DynamicQueryControls to do the recreation OnInit rather than at PageLoad. Quite a few issues arise from creating this at the PageLoad level.

Resources