I have a method that creates table and then creates a repeater right after, the table gets rendered but the repeater just does not get rendered. The method below simply creates a table first, filling it with information then dynamically constructs a repeater which works fine, but then it just does not render the repeater onto the aspx page. I have tried using the stringbuilder to return it as a string but still doesn't work. here is the code below. Thanks
private void CreateUserExperienceTable(List<UserExperience> experiences)
{
foreach (UserExperience experience in experiences)
{
HtmlGenericControl Header = new HtmlGenericControl("h3");
Header.InnerHtml = experience.Company;
dvUserExperience.Controls.Add(Header);
Table experienceTable = new Table();
TableRow experienceRoleRow = new TableRow();
TableRow experienceDescriptionRow = new TableRow();
TableRow experiencePeriodFromRow = new TableRow();
TableRow experiencePeriodToRow = new TableRow();
TableCell experienceRoleTitleCell = new TableCell();
TableCell experienceRoleValueCell = new TableCell();
TableCell experienceDescriptionTitleCell = new TableCell();
TableCell experienceDescriptionValueCell = new TableCell();
TableCell experiencePeriodFromTitleCell = new TableCell();
TableCell experiencePeriodFromValueCell = new TableCell();
TableCell experiencePeriodToTitleCell = new TableCell();
TableCell experiencePeriodToValueCell = new TableCell();
experienceRoleTitleCell.Text = "Role:";
experienceRoleValueCell.Text = experience.Role;
experienceDescriptionTitleCell.Text = "Description:";
experienceDescriptionValueCell.Text = experience.CompanyDescription;
experiencePeriodFromTitleCell.Text = "Period From: ";
experiencePeriodFromValueCell.Text = experience.PeriodFrom.ToString("yy-mm-dd");
experiencePeriodToTitleCell.Text = "Period To:";
experiencePeriodToValueCell.Text = experience.PeriodTo == null
? "Present"
: experience.PeriodTo.ToString();
experienceRoleRow.Cells.Add(experienceRoleTitleCell);
experienceRoleRow.Cells.Add(experienceRoleValueCell);
experienceDescriptionRow.Cells.Add(experienceDescriptionTitleCell);
experienceDescriptionRow.Cells.Add(experienceDescriptionValueCell);
experiencePeriodFromRow.Cells.Add(experiencePeriodFromTitleCell);
experiencePeriodFromRow.Cells.Add(experiencePeriodFromValueCell);
experiencePeriodToRow.Cells.Add(experiencePeriodToTitleCell);
experiencePeriodToRow.Cells.Add(experiencePeriodToValueCell);
experienceTable.Rows.Add(experienceRoleRow);
experienceTable.Rows.Add(experienceDescriptionRow);
experienceTable.Rows.Add(experiencePeriodFromRow);
experienceTable.Rows.Add(experiencePeriodToRow);
dvUserExperience.Controls.Add(experienceTable);
String rptDuties = updatePageWithDuties(experience.Duties);
//dvUserExperience.Controls.Add(rptDuties);
}
}
private string updatePageWithDuties(List<ExperienceDuties> list)
{
Repeater rptDuties = new Repeater();
rptDuties.DataSource = list;
rptDuties.DataBind();
foreach (RepeaterItem rptItem in rptDuties.Items)
{
if (rptItem.ItemIndex == 0)
{
RepeaterItem headerTemplate = new RepeaterItem(rptItem.ItemIndex, ListItemType.Header);
HtmlGenericControl h4Tag = new HtmlGenericControl("h4");
h4Tag.InnerHtml = "Duties";
headerTemplate.Controls.Add(h4Tag);
}
RepeaterItem itemTemplate = new RepeaterItem(rptItem.ItemIndex, ListItemType.Item);
Label dutyLabel = new Label();
ExperienceDuties expDuties = ((IList<ExperienceDuties>)rptDuties.DataSource)[rptItem.ItemIndex];
dutyLabel.Text = expDuties.Description;
itemTemplate.Controls.Add(dutyLabel);
RepeaterItem seperatorItem = new RepeaterItem(rptItem.ItemIndex, ListItemType.Separator);
LiteralControl ltrHR = new LiteralControl();
ltrHR.Text = "<hr />";
seperatorItem.Controls.Add(ltrHR);
}
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
HtmlTextWriter writer = new HtmlTextWriter(sw);
rptDuties.RenderControl(writer);
return sb.ToString();
}
You cannot render Repeater control as a string. Instead, you need to add the Repeater to dvUserExperience as a control.
private void CreateUserExperienceTable(List<UserExperience> experiences)
{
foreach (UserExperience experience in experiences)
{
...
dvUserExperience.Controls.Add(experienceTable);
// Add as a server control
Repeater rptDuties = updatePageWithDuties(experience.Duties);
dvUserExperience.Controls.Add(rptDuties);
}
}
private Repeater updatePageWithDuties(List<ExperienceDuties> list)
{
Repeater rptDuties = new Repeater();
...
return rptDuties;
}
Updated:
You need to add controls to RepeaterItem which is rptItem.
See the arrows <===== in the following code.
private Repeater updatePageWithDuties(List<ExperienceDuties> list)
{
Repeater rptDuties = new Repeater();
rptDuties.DataSource = list;
rptDuties.DataBind();
foreach (RepeaterItem rptItem in rptDuties.Items)
{
if (rptItem.ItemIndex == 0)
{
var h4Tag = new HtmlGenericControl("h4");
h4Tag.InnerHtml = "Duties";
rptItem.Controls.Add(h4Tag); <=====
}
var dutyLabel = new Label();
ExperienceDuties expDuties =
((IList<ExperienceDuties>) rptDuties.DataSource)[rptItem.ItemIndex];
dutyLabel.Text = expDuties.Description;
rptItem.Controls.Add(dutyLabel); <=====
var ltrHR = new LiteralControl();
ltrHR.Text = "<hr />";
rptItem.Controls.Add(ltrHR); <=====
}
return rptDuties;
}
Your repeater is not in the Form's Controls collection. It should be there for the form to display it. Instead of returning a StringBuilder object you must add the repeater to the form's controls collection by using this.Controls.Add(rptDuties); This should render your repeater.
UPDATE - With working samle
Here's a working sample if you'd like to see where to change.
NOTE: #Win's answer is valid. You should do that and add your repeaters to you place holder, i.e the dvUserExperience DIV in this case.
Markup code
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="TestRepeater.aspx.cs" Inherits="ExcelUpload.TestRepeater" %>
<!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>
</head>
<body>
<form id="form1" runat="server">
<div id="dvUserExperience" runat="server">
</div>
</form>
</body>
</html>
Code behind
using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
namespace ExcelUpload
{
public partial class TestRepeater : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
CreateUserExperienceTable(LoadData());
}
private List<UserExperience> LoadData()
{
List<UserExperience> experiences = new List<UserExperience>();
for (int i = 0; i < 5; i++)
{
UserExperience newExp = new UserExperience();
newExp.Company = "Company " + i;
newExp.Role = "Role " + i;
newExp.CompanyDescription = "CompanyDescription " + i;
newExp.PeriodFrom = DateTime.Now.AddDays(i);
newExp.PeriodTo = DateTime.Now.AddDays(i + 5);
for (int j = 0; j < 2; j++)
{
ExperienceDuties newDuty = new ExperienceDuties();
newDuty.Description = "Duty Description " + j;
newExp.Duties.Add(newDuty);
}
experiences.Add(newExp);
}
return experiences;
}
private void CreateUserExperienceTable(List<UserExperience> experiences)
{
foreach (UserExperience experience in experiences)
{
HtmlGenericControl Header = new HtmlGenericControl("h3");
Header.InnerHtml = experience.Company;
dvUserExperience.Controls.Add(Header);
Table experienceTable = new Table();
TableRow experienceRoleRow = new TableRow();
TableRow experienceDescriptionRow = new TableRow();
TableRow experiencePeriodFromRow = new TableRow();
TableRow experiencePeriodToRow = new TableRow();
TableCell experienceRoleTitleCell = new TableCell();
TableCell experienceRoleValueCell = new TableCell();
TableCell experienceDescriptionTitleCell = new TableCell();
TableCell experienceDescriptionValueCell = new TableCell();
TableCell experiencePeriodFromTitleCell = new TableCell();
TableCell experiencePeriodFromValueCell = new TableCell();
TableCell experiencePeriodToTitleCell = new TableCell();
TableCell experiencePeriodToValueCell = new TableCell();
experienceRoleTitleCell.Text = "Role:";
experienceRoleValueCell.Text = experience.Role;
experienceDescriptionTitleCell.Text = "Description:";
experienceDescriptionValueCell.Text = experience.CompanyDescription;
experiencePeriodFromTitleCell.Text = "Period From: ";
experiencePeriodFromValueCell.Text = experience.PeriodFrom.ToString("yy-mm-dd");
experiencePeriodToTitleCell.Text = "Period To:";
experiencePeriodToValueCell.Text = experience.PeriodTo == null
? "Present"
: experience.PeriodTo.ToString();
experienceRoleRow.Cells.Add(experienceRoleTitleCell);
experienceRoleRow.Cells.Add(experienceRoleValueCell);
experienceDescriptionRow.Cells.Add(experienceDescriptionTitleCell);
experienceDescriptionRow.Cells.Add(experienceDescriptionValueCell);
experiencePeriodFromRow.Cells.Add(experiencePeriodFromTitleCell);
experiencePeriodFromRow.Cells.Add(experiencePeriodFromValueCell);
experiencePeriodToRow.Cells.Add(experiencePeriodToTitleCell);
experiencePeriodToRow.Cells.Add(experiencePeriodToValueCell);
experienceTable.Rows.Add(experienceRoleRow);
experienceTable.Rows.Add(experienceDescriptionRow);
experienceTable.Rows.Add(experiencePeriodFromRow);
experienceTable.Rows.Add(experiencePeriodToRow);
dvUserExperience.Controls.Add(experienceTable);
updatePageWithDuties(experience.Duties);
}
}
private void updatePageWithDuties(List<ExperienceDuties> list)
{
Repeater rptDuties = new Repeater();
rptDuties.ID = "rptDuties";
rptDuties.DataSource = list;
rptDuties.DataBind();
foreach (RepeaterItem rptItem in rptDuties.Items)
{
if (rptItem.ItemIndex == 0)
{
RepeaterItem headerTemplate = new RepeaterItem(rptItem.ItemIndex, ListItemType.Header);
HtmlGenericControl h4Tag = new HtmlGenericControl("h4");
h4Tag.InnerHtml = "Duties";
rptItem.Controls.Add(h4Tag);
}
RepeaterItem itemTemplate = new RepeaterItem(rptItem.ItemIndex, ListItemType.Item);
Label dutyLabel = new Label();
ExperienceDuties expDuties = ((IList<ExperienceDuties>)rptDuties.DataSource)[rptItem.ItemIndex];
dutyLabel.Text = expDuties.Description;
rptItem.Controls.Add(dutyLabel);
RepeaterItem seperatorItem = new RepeaterItem(rptItem.ItemIndex, ListItemType.Separator);
LiteralControl ltrHR = new LiteralControl();
ltrHR.Text = "<hr />";
rptItem.Controls.Add(ltrHR);
}
dvUserExperience.Controls.Add(rptDuties);
}
}
public class UserExperience {
public List<ExperienceDuties> Duties = new List<ExperienceDuties>();
public string Company { get; set; }
public string Role { get; set; }
public string CompanyDescription { get; set; }
public DateTime PeriodFrom { get; set; }
public DateTime PeriodTo { get; set; }
}
public class ExperienceDuties {
public string Description { get; set; }
}
}
Related
I am using c# asp.net and building a SharePoint visual webpart. I have this method which is adding some controls to the page:
private string RSSFile = #"http://www.myCompany.com/xml_feed.xml";
protected override void CreateChildControls()
{
base.CreateChildControls();
// introductionText
HtmlGenericControl introductionText = new HtmlGenericControl("p");
introductionText.InnerHtml = "De volgende vacatures staan momenteel open:";
this.Controls.Add(introductionText);
// table
HtmlGenericControl mainTable = new HtmlGenericControl("table");
mainTable.Attributes.Add("cellpadding", "10");
HtmlGenericControl tr1 = new HtmlGenericControl("tr");
Controls.Add(mainTable);
mainTable.Controls.Add(tr1);
// header columns
tr1.InnerHtml = "<th style=\"text-align:left;\">Vacature</th><th style=\"text-align:left;\">Standplaats</th><th style=\"text-align:left;\">Uren</th>";
// load xml file
// TODO load from webpart property
var xmlSource = XElement.Load(RSSFile);
// get all file elements
IEnumerable<XElement> q =
(from c in xmlSource.Descendants("vacature")
select c).ToArray();
// TODO filter on date
//where (string)c.Element("publish") == "True"
//orderby c.Element("name").Value, c.Element("version").Value
// loop into each file element and get values
foreach (XElement c in q)
{
HtmlGenericControl tr2 = new HtmlGenericControl("tr");
mainTable.Controls.Add(tr2);
// title with hyperlink
HtmlGenericControl td1 = new HtmlGenericControl("td");
td1.Style.Add("vertical-align", "top");
td1.InnerHtml = string.Format("{1}", c.Element("vacaturenr").Value, c.Element("titel").Value);
tr2.Controls.Add(td1);
// location
HtmlGenericControl td2 = new HtmlGenericControl("td");
td2.Style.Add("vertical-align", "top");
td2.InnerHtml = c.Element("regios").Value;
tr2.Controls.Add(td2);
// uren
HtmlGenericControl td3 = new HtmlGenericControl("td");
td3.Style.Add("vertical-align", "top");
td3.InnerHtml = string.Concat(c.Element("min_uren").Value, " - ", c.Element("max_uren").Value);
tr2.Controls.Add(td3);
}
this.Controls.Add(new LiteralControl("<br/>"));
}
Like you see I have an ahref which is referenced to the same page and adds a querystring "vacatureNr". In the pageload I check if this "vacatureNr" is filled. If it is filled I would like to add extra controls to my page. It workds, but the controls are added before the controls which are added in the method "CreateChildControls". How can I add these controls after the controls which are already added in the method "CreateChildControls"?
protected void Page_Load(object sender, EventArgs e)
{
string vacatureNr = Request.QueryString["vacatureNr"];
if(!string.IsNullOrEmpty(vacatureNr))
{
this.Controls.Clear();
HtmlGenericControl table = new HtmlGenericControl("table");
HtmlGenericControl tr1 = new HtmlGenericControl("tr");
HtmlGenericControl td1 = new HtmlGenericControl("td");
HtmlGenericControl td2 = new HtmlGenericControl("td");
td1.InnerHtml = "<strong>Inzet in uren:</strong>";
td2.InnerHtml = "24-32";
tr1.Controls.Add(td1);
tr1.Controls.Add(td2);
table.Controls.Add(tr1);
HtmlGenericControl tr2 = new HtmlGenericControl("tr");
HtmlGenericControl td3 = new HtmlGenericControl("td");
HtmlGenericControl td4 = new HtmlGenericControl("td");
td3.InnerHtml = "<strong>Standplaats:</strong>";
td4.InnerHtml = "Egmond aan Zee";
tr2.Controls.Add(td3);
tr2.Controls.Add(td4);
table.Controls.Add(tr2);
HtmlGenericControl tr3 = new HtmlGenericControl("tr");
HtmlGenericControl td5 = new HtmlGenericControl("td");
HtmlGenericControl td6 = new HtmlGenericControl("td");
td5.InnerHtml = "<strong>Aard van dienstverband:</strong>";
td6.InnerHtml = "Bepaalde tijd";
tr3.Controls.Add(td5);
tr3.Controls.Add(td6);
table.Controls.Add(tr3);
this.Controls.Add(table);
}
}
The CreateChildControls method will always be fired before the Page Load event. Instead, try moving your logic from CreateChildControls into a new method and call this method at the end of Page_Load.
maybe it's possible to add the controls with the OnPreRender method protected override void OnPreRender(EventArgs e). This method should run after the CreateChildControls i guess.
[Edit]-> You can overwrite OnPreRender on the same class as CreateChildControls...
Greetz
I have been trying to fetch ids of dynamically created dropdownlists(during Page_Load) ,which are in a table, and then find the selected values in those dropdownlists and store these values a table or GridView on button click.This is how i assigned id's(in Page_Load event)
drd.ID = "dbaseid" + rowctr;
drd1id[rowctr]=drd1.ID;
rowctr is the index variable to assign unique id to each dropdown.
How do i fetch the ids from Page_Load . I tried storing the id in an array and then using session variable:
drdid[rowctr]=drd.ID;
drd1id[rowctr]=drd1.ID;
Session["drditem"]=drditem;
Session["drd1item"]=drd1item;
and then tried to fetch the ids in buttonclick event function:
drdid=(string[])Session["drdid"];
drd1id=(string[])Session["drd1id"];
string[] a =new string [50];
for(int i =0;i<noodropdowns;i++)
{
a=drd1id[i];
a.selectedindex//doesnt work !!
}
Is there a way to get the real ids and then work on them ?
I m new to asp.net , My apologies if it sounds noob ish ..
thanks in advance.
Hey if you are trying to loop over all the drop down list in the GridView and get the drop down list ?
//Add the drop down as following in page load
drd.ID = "dbaseid"; //do not add dynamic id other wise you will not able to find it.
//It client id would be different based upon its position in DOM
//loop over gridview row and get the control as following
foreach (GridViewRow row in grid.Rows)
{
var ddl = row.FindControl("dbaseid") as DropDown;
//do what ever with the drop down
}
Found success ,found the dropdowns and saved the selected values in a table .Every time a value from a drop down is selected it is changed in the table as well.Here is the code..
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Collections;
using System.Web.Security;
using System.Text;
using System.Configuration;
using System.Web.SessionState;
using System.Windows;
public partial class Default2 : System.Web.UI.Page
{
Table tblRecipients = new Table();
DropDownList drd = new DropDownList();
DropDownList drd1 = new DropDownList();
protected void Page_Init(object sender, EventArgs e)
{
DataTable dtt = (DataTable)Session["griddata"];
int n = dtt.Columns.Count;
string[] drd1item = new string[n];
string[] excel = new string[n];
for (int i = 0; i < dtt.Columns.Count; i++)
{
excel[i] = dtt.Columns[i].ColumnName;
}
Session["exceldata"] = excel;
////saving sql database column names in an array variable
DataTable dtt1 = (DataTable)Session["dbasecolumns"];
int l = dtt1.Columns.Count;
string[] drditem = new string[l];
string[] sqlcolumn = new string[l];
for (int j = 0; j < dtt1.Columns.Count; j++)
{
sqlcolumn[j] = dtt1.Columns[j].ColumnName;
}
Session["sqlcolumn"] = sqlcolumn;
Session["l"] = l;
//Table Creation
Table mytable = new Table();
mytable.Visible = true;
mytable.GridLines = GridLines.Both;
TableHeaderRow th = new TableHeaderRow();
TableHeaderCell thc = new TableHeaderCell();
TableHeaderCell thc1 = new TableHeaderCell();
mytable.Rows.Add(th);
Label lbl1 = new Label();
Label lbl2 = new Label();
lbl1.Text = "Database";
lbl2.Text = "Excel";
thc.Controls.Add(lbl1);
thc1.Controls.Add(lbl2);
th.Cells.Add(thc);
th.Cells.Add(thc1);
for (int rowctr = 0; rowctr < sqlcolumn.Length; rowctr++)
{
TableCell mycell = new TableCell();
TableCell mycell1 = new TableCell();
for (int cellctr = 0; cellctr < 1; cellctr++)
{
//dropdown with database columns
DropDownList drd = new DropDownList();
drd.Items.Insert(0, new ListItem("--Select--", "0"));
drd.ID = "dbaseid" + rowctr;
for (int i = 0; i < sqlcolumn.Length; i++)
{
drd.Items.Add(sqlcolumn[i]);
drditem[i] = sqlcolumn[i];
}
// drd.SelectedIndexChanged+=new EventHandler(drd1_SelectedIndexChanged);
//dropdown with excel columns
DropDownList drd1 = new DropDownList();
drd1.ID = "excelid" + rowctr;
for (int j = 0; j < excel.Length; j++)
{
drd1.Items.Add(excel[j]);
drd1item[j] = excel[j];
}
// drd1.SelectedIndexChanged +=new EventHandler (drd1_SelectedIndexChanged);
//session variable to store dropdown elements in an array
//Table cells and rows addition
TableRow myrow = new TableRow();
mycell.Controls.Add(drd);
mycell1.Controls.Add(drd1);
myrow.Cells.Add(mycell);
myrow.Cells.Add(mycell1);
mytable.Rows.Add(myrow);
mytable.BorderStyle = BorderStyle.Solid;
}
}
DynamicControlsHolder.Controls.Add(mytable);
}
protected void Button1_Click(object sender, EventArgs e)
{
Table mytable = new Table();
mytable.GridLines = GridLines.Both;
string s;
foreach (Control ctl in DynamicControlsHolder.Controls)
{
if (ctl is Table)
{
Table tblnew = ctl as Table;
{
foreach (Control ctrl in tblnew.Controls)
{
if (ctrl is TableRow)
{
TableRow trow = new TableRow();
TableRow tblrow = ctrl as TableRow;
{
foreach (Control cntrl in tblrow.Controls)
{
if (cntrl is TableCell)
{
TableCell tcell = new TableCell();
TableCell tblcell = cntrl as TableCell;
{
foreach (Control cntrol in tblcell.Controls)
{
if (cntrol is DropDownList)
{
DropDownList myddr = cntrol as DropDownList;
if (cntrol != null)
{
s = myddr.SelectedItem.Text;
tcell.Text = s;
}
}
}
}
trow.Cells.Add(tcell);
}
}
}
mytable.Rows.Add(trow);
}
}
}
}
}
DynamicControlsHolder.Controls.Add(mytable);
}
}
You mentioned that the dynamically created dropdownlists are in a table. I think Anand was referring to that table, not to the GridView you wish to populate with the values of the dropdownlists. So, you could try to loop over the rows of the table and get the dropdownlist ids.
I'm trying to do these:
access my site's contents and read theme from my database
dynamically create a table without using grid-view and dynamically generate Image Buttons in
it to edit and delete my contents.
I Succeed to define a Post Back URL for one of my image buttons and post it to a new page with my content ID to edit it but I failed to define an event and fire it for delete my content without going to a new page.
Here is my code :
var cn = new SqlConnection();
var cmd = new SqlCommand();
int i=0;
try
{
using (cn = new SqlConnection(ConfigurationManager.ConnectionStrings["cnString"].ToString()))
{
cn.Open();
using (cmd = new SqlCommand("ContentArchiveCategory", cn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#CatID", txtCategories.SelectedValue);
var dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
while (dr.Read())
{
i++;
if (i % 2 != 0)
{
var tr = new TableRow();
tr.CssClass = "ADACLTOdd".ToString();
var no = new TableCell();
no.Text = i.ToString();
no.CssClass = "ADACLTNoColumn".ToString();
tr.Cells.Add(no);
var date = new TableCell();
date.Text = dr["DateCreated"].ToString();
date.CssClass = "ADACLTDateColumn".ToString();
tr.Cells.Add(date);
var title = new TableCell();
title.Text = dr["Title"].ToString();
title.CssClass = "ADACLTTitleColumn".ToString();
tr.Cells.Add(title);
var edit = new TableCell();
edit.CssClass = "ADACLTEditColumn".ToString();
var ice = new ImageButton();
ice.ImageUrl = "~/Images/ICSEdit.png".ToString();
ice.PostBackUrl = "ContentEdit.aspx?id=" + dr["ContentID"].ToString();
ice.ToolTip = "ویرایش".ToString();
edit.Controls.Add(ice);
tr.Cells.Add(edit);
var delete = new TableCell();
delete.CssClass = "ADACLTDeleteColumn".ToString();
var icd = new ImageButton();
icd.ImageUrl = "~/Images/ICSDelete.png".ToString();
icd.ToolTip = "پاک".ToString();
icd.ID = dr["ContentID"].ToString();
icd.Click += new ImageClickEventHandler(icd_Click);
delete.Controls.Add(icd);
tr.Cells.Add(delete);
ContentListTable.Rows.Add(tr);
}
else
{
var tr = new TableRow();
tr.CssClass = "ADACLTEven".ToString();
var no = new TableCell();
no.Text = i.ToString();
no.CssClass = "ADACLTNoColumn".ToString();
tr.Cells.Add(no);
var date = new TableCell();
date.Text = dr["DateCreated"].ToString();
date.CssClass = "ADACLTDateColumn".ToString();
tr.Cells.Add(date);
var title = new TableCell();
title.Text = dr["Title"].ToString();
title.CssClass = "ADACLTTitleColumn".ToString();
tr.Cells.Add(title);
var edit = new TableCell();
edit.CssClass = "ADACLTEditColumn".ToString();
var ice = new ImageButton();
ice.ImageUrl = "~/Images/ICSEdit.png".ToString();
ice.PostBackUrl = "ContentEdit.aspx?id=" + dr["ContentID"].ToString();
ice.ToolTip = "ویرایش".ToString();
edit.Controls.Add(ice);
tr.Cells.Add(edit);
var delete = new TableCell();
delete.CssClass = "ADACLTDeleteColumn".ToString();
var icd = new ImageButton();
icd.ImageUrl = "~/Images/ICSDelete.png".ToString();
icd.ToolTip = "پاک".ToString();
icd.ID = dr["ContentID"].ToString();
icd.Click += icd_Click;
delete.Controls.Add(icd);
tr.Cells.Add(delete);
ContentListTable.Rows.Add(tr);
}
ContentListTable.Visible = true;
}
}
}
}
catch
{
CatMessage.Visible = true;
CatMessage.BorderColor = System.Drawing.ColorTranslator.FromHtml("#930000");
CatMessage.BackColor = System.Drawing.ColorTranslator.FromHtml("#F4B7B7");
CatMsg1.Text = string.Format("{0} عزیز! متاسفانه در برقراری ارتباط با سرور مشکلی پیش آمده، لطفاً این مورد را به مدیریت سایت گزارش کنید", Session["FirstName"]);
}
}
}
protected void icd_Click(object sender, EventArgs e)
{
ImageButton icd = sender as ImageButton;
CatMessage.Visible = true;
CatMessage.BorderColor = System.Drawing.ColorTranslator.FromHtml("#930000");
CatMessage.BackColor = System.Drawing.ColorTranslator.FromHtml("#F4B7B7");
CatMsg1.Text = string.Format("{0}",icd.ID);
}
I tried both ways icd.Click += icd_Click; and icd.Click += new ImageClickEventHandler(icd_Click); to fire my event but it didn't work at all.
I have created a composite control that changes the controls in it based on the value of one of it's properties called "Type".
The intent is that once this "Type" property is set, it is not changed again for the life of the control, so the controls rendered as a result of the value of the "Type" property should not change.
I have overridden the LoadViewState and SaveViewState methods as recommended on by many internet posts, but I am still getting an error about "Failed to Load ViewState". The control will render appropriately on the first load, but once any postback is made, it generates the "Failed to Load ViewState" error.
Here is part of the code for the composite control:
[Serializable]
internal enum SearchPanelControlType
{
Label,
DropDownList,
TextBox
}
[Serializable]
internal class SearchGridViewStateObject<T> where T : Bll.BaseCriteria
{
public T mySearchCriteria { get; set; }
public SearchGridType myType { get; set; }
public int myNumberOfChildrenPerRow { get; set; }
public object myBaseViewState { get; set; }
public SearchGridViewStateObject(T searchCriteria, SearchGridType type, int numberOfChildrenPerRow, object baseViewState)
{
mySearchCriteria = searchCriteria;
myType = type;
myNumberOfChildrenPerRow = numberOfChildrenPerRow;
myBaseViewState = baseViewState;
}
}
[Themeable(true)]
[Serializable]
public class SearchGrid<T> : CompositeControl
where T : Bll.BaseCriteria
{
#region Constructor
public SearchGrid()
{
}
#endregion
#region Private Fields
private MyCompanygridview myGridView;
private ObjectDataSource myObjectDataSource;
private Panel mySearchParametersPanel;
private Button mySearchButton;
private Button myClearSearchCriteriaButton;
private T mySearchCriteria;
//private SearchGridType myType = SearchGridType.Account;
private SearchGridType myType;
private int myNumberOfChildrenPerRow = 2;
private MyCompanygridviewSelectionType mySelectionType = MyCompanygridviewSelectionType.None;
private int mySelectColumnIndex = 0;
private int myPageSize = 10;
private int myPageIndex = 0;
private string myGridViewCssClass;
private string myCustomPagerButtonCssClass;
private string myCustomPagerTextBoxCssClass;
private string myRowCssClass;
private string myEmptyDataRowCssClass;
private string myPagerCssClass;
private string mySelectedRowCssClass;
private string myHeaderCssClass;
private string myAlternatingRowCssClass;
private string myDisabledRowCssClass;
private List<Guid> myGridViewDisabledValues = new List<Guid>();
private List<Guid> myGridViewSelectedValues = new List<Guid>();
private GridLines myGridLines = GridLines.None;
private string mySearchPanelButtonCssClass;
private string mySearchPanelTextBoxCssClass;
private string mySearchPanelDropDownListCssClass;
private string mySearchPanelLabelCssClass;
#endregion
#region Public Properties
/// <summary>
/// Gets or sets the search criteria.
/// </summary>
/// <value>The search criteria.</value>
public T SearchCriteria
{
get
{
return mySearchCriteria;
}
set
{
if (value != mySearchCriteria)
{
mySearchCriteria = value;
this.ChildControlsCreated = false;
this.EnsureChildControls();
}
}
}
/// <summary>
/// Gets or sets the type of items that should be shown in the gridview.
/// </summary>
/// <summary>
/// Gets or sets the type of items that should be shown in the gridview.
/// </summary>
[Category("SearchGrid"),
Description("Gets or sets the type of items that should be shown in the grid view."),
DefaultValue(null)]
public SearchGridType Type
{
get
{
return myType;
}
set
{
if (value != myType)
{
myType = value;
this.ChildControlsCreated = false;
this.EnsureChildControls();
}
}
}
[DefaultValue(MyCompanygridviewSelectionType.None),
Category("SearchGrid"),
Description("Indicates whether to use multiselection mode, single selection mode, or no selection mode.")]
public MyCompanygridviewSelectionType SelectionType
{
get
{
return mySelectionType;
}
set
{
mySelectionType = value;
}
}
#endregion
#region Overridden Methods
protected override void LoadViewState(object savedState)
{
SearchGridViewStateObject<T> vsObject = savedState as SearchGridViewStateObject<T>;
mySearchCriteria = vsObject.mySearchCriteria;
myType = vsObject.myType;
myNumberOfChildrenPerRow = vsObject.myNumberOfChildrenPerRow;
ClearChildViewState();
this.ChildControlsCreated = false;
this.EnsureChildControls();
base.LoadViewState(vsObject.myBaseViewState);
}
protected override object SaveViewState()
{
SearchGridViewStateObject<T> vsObject = new SearchGridViewStateObject<T>(mySearchCriteria, myType, myNumberOfChildrenPerRow, base.SaveViewState());
return vsObject;
}
protected override void RecreateChildControls()
{
EnsureChildControls();
}
protected override void CreateChildControls()
{
SearchGridParser parser = SearchGridParserFactory.GetParser(this.myType);
Controls.Clear();
//Define the Search Parameters Panel
mySearchParametersPanel = new Panel();
mySearchParametersPanel.ID = "spp" + Enum.GetName(typeof(SearchGridType), this.myType);
mySearchParametersPanel.DefaultButton = "btnSearch";
mySearchParametersPanel.ScrollBars = ScrollBars.None;
parser.CreateSearchPanelControls(ref mySearchParametersPanel, CreateSearchPanelStyleDictionary());
//Define Buttons
mySearchButton = new Button();
mySearchButton.ID = "btnSearch";
mySearchButton.Text = "Search";
mySearchButton.CausesValidation = false;
mySearchButton.UseSubmitBehavior = false;
mySearchButton.Click += new EventHandler(mySearchButton_Click);
if (!string.IsNullOrEmpty(mySearchPanelButtonCssClass))
{
mySearchButton.CssClass = mySearchPanelButtonCssClass;
}
myClearSearchCriteriaButton = new Button();
myClearSearchCriteriaButton.ID = "btnClearSearchCriteria";
myClearSearchCriteriaButton.Text = "Clear Search Criteria";
myClearSearchCriteriaButton.CausesValidation = false;
myClearSearchCriteriaButton.UseSubmitBehavior = false;
myClearSearchCriteriaButton.Click += new EventHandler(myClearSearchCriteriaButton_Click);
if (!string.IsNullOrEmpty(mySearchPanelButtonCssClass))
{
myClearSearchCriteriaButton.CssClass = mySearchPanelButtonCssClass;
}
mySearchParametersPanel.Controls.Add(mySearchButton);
mySearchParametersPanel.Controls.Add(myClearSearchCriteriaButton);
// Define the GridView
myGridView = new MyCompanygridview();
myGridView.ID = "gv" + Enum.GetName(typeof(SearchGridType), this.myType);
myGridView.AutoGenerateColumns = false;
myGridView.DataKeyNames = new string[] { "ID" };
myGridView.DataSourceID = "ods" + Enum.GetName(typeof(SearchGridType), this.myType);
myGridView.AllowSorting = true;
myGridView.Width = new System.Web.UI.WebControls.Unit("100%");
myGridView.AllowPaging = true;
myGridView.EnableCustomPager = true;
myGridView.Sorted += new EventHandler(myGridView_Sorted);
myGridView.PageIndexChanged += new EventHandler(myGridView_PageIndexChanged);
myGridView.PageSizeChanged += new EventHandler(myGridView_PageSizeChanged);
myGridView.PageSizeChanging += new EventHandler(myGridView_PageSizeChanging);
myGridView.SelectionType = this.mySelectionType;
myGridView.SelectColumnIndex = this.mySelectColumnIndex;
myGridView.PageSize = this.myPageSize;
myGridView.PageIndex = this.myPageIndex;
myGridView.CssClass = this.myGridViewCssClass;
myGridView.CustomPagerButtonCssStyle = this.myCustomPagerButtonCssClass;
myGridView.CustomPagerTextBoxCssStyle = this.myCustomPagerTextBoxCssClass;
myGridView.RowStyle.CssClass = this.myRowCssClass;
myGridView.EmptyDataRowStyle.CssClass = this.myEmptyDataRowCssClass;
myGridView.PagerStyle.CssClass = this.myPagerCssClass;
myGridView.SelectedRowStyle.CssClass = this.mySelectedRowCssClass;
myGridView.HeaderStyle.CssClass = this.myHeaderCssClass;
myGridView.AlternatingRowStyle.CssClass = this.myAlternatingRowCssClass;
myGridView.DisabledRowCssClass = this.myDisabledRowCssClass;
myGridView.DisabledValues = this.myGridViewDisabledValues;
myGridView.SelectedValues = this.myGridViewSelectedValues;
myGridView.GridLines = this.myGridLines;
parser.CreateGridViewColumns(ref myGridView);
// Define the object data source
myObjectDataSource = new ObjectDataSource();
myObjectDataSource.ID = "ods" + Enum.GetName(typeof(SearchGridType), this.myType);
myObjectDataSource.OldValuesParameterFormatString = "original_{0}";
myObjectDataSource.SelectMethod = "GetList";
myObjectDataSource.SelectCountMethod = "SelectCountForGetList";
myObjectDataSource.TypeName = "MyCompany.DCO.MyProject.Bll." + Enum.GetName(typeof(SearchGridType), this.myType) + "Manager";
myObjectDataSource.EnablePaging = true;
myObjectDataSource.StartRowIndexParameterName = "startRowIndex";
myObjectDataSource.MaximumRowsParameterName = "maximumRows";
myObjectDataSource.SortParameterName = "SortExpression";
myObjectDataSource.Selecting += new ObjectDataSourceSelectingEventHandler(myObjectDataSource_Selecting);
myObjectDataSource.Selected += new ObjectDataSourceStatusEventHandler(myObjectDataSource_Selected);
// Add the defined controls
this.Controls.Add(myObjectDataSource);
this.Controls.Add(myGridView);
this.Controls.Add(mySearchParametersPanel);
parser.SetSearchPanelControls<T>(this.mySearchCriteria, ref mySearchParametersPanel);
}
protected override void Render(HtmlTextWriter writer)
{
AddAttributesToRender(writer);
writer.RenderBeginTag(HtmlTextWriterTag.Div);
mySearchParametersPanel.RenderControl(writer);
writer.RenderBeginTag(HtmlTextWriterTag.Br);
writer.RenderEndTag();
myGridView.RenderControl(writer);
writer.RenderBeginTag(HtmlTextWriterTag.Br);
writer.RenderEndTag();
myObjectDataSource.RenderControl(writer);
writer.RenderEndTag();
}
#endregion
}
Here is the code for the "parser" file that creates the custom controls:
class SearchGridParser_ApplicationFunction : SearchGridParser
{
internal override void CreateGridViewColumns(ref MyCompanygridview myGridView)
{
// Link Column
HyperLinkField linkColumn = new HyperLinkField();
linkColumn.Text = "Edit";
linkColumn.HeaderText = "ID";
linkColumn.DataNavigateUrlFields = new string[] { "ID" };
linkColumn.DataNavigateUrlFormatString = "~/AddEdit/ApplicationFunction/default.aspx?Action=Edit&ID={0}";
myGridView.Columns.Add(linkColumn);
// Name Column
BoundField nameColumn = new BoundField();
nameColumn.DataField = "Name";
nameColumn.HeaderText = "Name";
nameColumn.SortExpression = "Name";
myGridView.Columns.Add(nameColumn);
// Description Column
BoundField descriptionColumn = new BoundField();
descriptionColumn.DataField = "Description";
descriptionColumn.HeaderText = "Description";
descriptionColumn.SortExpression = "Description";
myGridView.Columns.Add(descriptionColumn);
// Business Criticality Column
TemplateField businessCriticalityColumn = new TemplateField();
businessCriticalityColumn.SortExpression = "BusinessCriticality";
businessCriticalityColumn.HeaderText = "Criticality";
businessCriticalityColumn.ItemTemplate = new LabelColumnGridViewTemplate(ListItemType.Item, "BusinessCriticality", "Name");
myGridView.Columns.Add(businessCriticalityColumn);
// Disabled Column
CheckBoxField disabledColumn = new CheckBoxField();
disabledColumn.DataField = "DisabledFlg";
disabledColumn.HeaderText = "Disabled";
disabledColumn.SortExpression = "DisabledFlg";
myGridView.Columns.Add(disabledColumn);
// Agencies Column
TemplateField agenciesColumn = new TemplateField();
agenciesColumn.HeaderText = "Agencies";
agenciesColumn.ItemTemplate = new ChildObjectsGridViewTemplate(ListItemType.Item, 2, "Agencies", "Agency.Abbreviation");
myGridView.Columns.Add(agenciesColumn);
// Applications Column
TemplateField applicationsColumn = new TemplateField();
applicationsColumn.HeaderText = "Applications";
applicationsColumn.ItemTemplate = new ChildObjectsGridViewTemplate(ListItemType.Item, 2, "Applications", "Application.Name");
myGridView.Columns.Add(applicationsColumn);
}
internal override void CreateSearchPanelControls(ref Panel myPanel, Dictionary<SearchPanelControlType, string> myStyleDictionary)
{
if (myStyleDictionary == null)
{
myStyleDictionary = new Dictionary<SearchPanelControlType, string>();
}
// Title
Literal myTitleStart = new Literal();
myTitleStart.Text = "<h4>";
Label myTitle = new Label();
myTitle.Text = "Application Function:";
myTitle.ID = "lblTitle";
Literal myTitleEnd = new Literal();
myTitleEnd.Text = "</h4>";
// Begin Table
Table myTable = new Table();
myTable.ID = "myTable";
// Create First Row
TableRow myTableRow1 = new TableRow();
myTableRow1.ID = "myTableRow1";
// Search by Name
TableCell myNameLabelTableCell = new TableCell();
myNameLabelTableCell.ID = "myNameLabelTableCell";
Label myNameLabel = new Label();
myNameLabel.ID = "lblName";
myNameLabel.Text = "Name:";
myNameLabel.AssociatedControlID = "txtName";
if (myStyleDictionary.ContainsKey(SearchPanelControlType.Label))
{
myNameLabel.CssClass = myStyleDictionary[SearchPanelControlType.Label];
}
myNameLabelTableCell.Controls.Add(myNameLabel);
myTableRow1.Cells.Add(myNameLabelTableCell);
TableCell myNameUserInputTableCell = new TableCell();
myNameUserInputTableCell.ID = "myNameUserInputTableCell";
TextBox myNameTextBox = new TextBox();
myNameTextBox.ID = "txtName";
if (myStyleDictionary.ContainsKey(SearchPanelControlType.TextBox))
{
myNameTextBox.CssClass = myStyleDictionary[SearchPanelControlType.TextBox];
}
myNameUserInputTableCell.Controls.Add(myNameTextBox);
myTableRow1.Cells.Add(myNameUserInputTableCell);
// Search by Agency
TableCell myAgencyLabelTableCell = new TableCell();
myAgencyLabelTableCell.ID = "myAgencyLabelTableCell";
Label myAgencyLabel = new Label();
myAgencyLabel.ID = "lblAgency";
myAgencyLabel.Text = "Agency:";
myAgencyLabel.AssociatedControlID = "ddlAgency";
if (myStyleDictionary.ContainsKey(SearchPanelControlType.Label))
{
myAgencyLabel.CssClass = myStyleDictionary[SearchPanelControlType.Label];
}
myAgencyLabelTableCell.Controls.Add(myAgencyLabel);
myTableRow1.Cells.Add(myAgencyLabelTableCell);
TableCell myAgencyUserInputTableCell = new TableCell();
myAgencyUserInputTableCell.ID = "myAgencyUserInputTableCell";
DropDownList<AgencyCriteria> myAgencyDDL = new DropDownList<AgencyCriteria>();
myAgencyDDL.Type = DropDownListType.Agency;
myAgencyDDL.ID = "ddlAgency";
if (myStyleDictionary.ContainsKey(SearchPanelControlType.DropDownList))
{
myAgencyDDL.CssClass = myStyleDictionary[SearchPanelControlType.DropDownList];
}
myAgencyDDL.DisplayDisabled = true;
myAgencyDDL.EnableAnyOption = true;
myAgencyDDL.DataBind();
myAgencyUserInputTableCell.Controls.Add(myAgencyDDL);
myTableRow1.Cells.Add(myAgencyUserInputTableCell);
myTable.Rows.Add(myTableRow1);
// Create Second row
TableRow myTableRow2 = new TableRow();
myTableRow2.ID = "myTableRow2";
// Search by BusinessCriticality
TableCell myBusinessCriticalityLabelTableCell = new TableCell();
myBusinessCriticalityLabelTableCell.ID = "myBusinessCriticalityLabelTableCell";
Label myBusinessCriticalityLabel = new Label();
myBusinessCriticalityLabel.ID = "lblBusinessCriticality";
myBusinessCriticalityLabel.Text = "Criticality:";
myBusinessCriticalityLabel.AssociatedControlID = "ddlBusinessCriticality";
if (myStyleDictionary.ContainsKey(SearchPanelControlType.Label))
{
myBusinessCriticalityLabel.CssClass = myStyleDictionary[SearchPanelControlType.Label];
}
myBusinessCriticalityLabelTableCell.Controls.Add(myBusinessCriticalityLabel);
myTableRow2.Cells.Add(myBusinessCriticalityLabelTableCell);
TableCell myBusinessCriticalityUserInputTableCell = new TableCell();
myBusinessCriticalityUserInputTableCell.ID = "myBusinessCriticalityUserInputTableCell";
DropDownList<LookupCodeCriteria> myBusinessCriticalityDDL = new DropDownList<LookupCodeCriteria>();
myBusinessCriticalityDDL.Type = DropDownListType.LookupCode;
myBusinessCriticalityDDL.ID = "ddlBusinessCriticality";
if (myStyleDictionary.ContainsKey(SearchPanelControlType.DropDownList))
{
myBusinessCriticalityDDL.CssClass = myStyleDictionary[SearchPanelControlType.DropDownList];
}
myBusinessCriticalityDDL.DisplayDisabled = true;
myBusinessCriticalityDDL.EnableAnyOption = true;
LookupCodeCriteria myBusinessCriticalityCriteria = new LookupCodeCriteria();
myBusinessCriticalityCriteria.Type = LookupCodeType.BusinessCriticality;
myBusinessCriticalityDDL.OtherCriteria = myBusinessCriticalityCriteria;
myBusinessCriticalityDDL.DataBind();
myBusinessCriticalityUserInputTableCell.Controls.Add(myBusinessCriticalityDDL);
myTableRow2.Cells.Add(myBusinessCriticalityUserInputTableCell);
// Search by DisabledFlg
TableCell myDisabledFlgLabelTableCell = new TableCell();
myDisabledFlgLabelTableCell.ID = "myDisabledFlgLabelTableCell";
Label myDisabledFlgLabel = new Label();
myDisabledFlgLabel.ID = "lblDisabledFlg";
myDisabledFlgLabel.Text = "Disabled:";
myDisabledFlgLabel.AssociatedControlID = "ddlDisabledFlg";
if (myStyleDictionary.ContainsKey(SearchPanelControlType.Label))
{
myDisabledFlgLabel.CssClass = myStyleDictionary[SearchPanelControlType.Label];
}
myDisabledFlgLabelTableCell.Controls.Add(myDisabledFlgLabel);
myTableRow2.Cells.Add(myDisabledFlgLabelTableCell);
TableCell myDisabledFlgUserInputTableCell = new TableCell();
myDisabledFlgUserInputTableCell.ID = "myDisabledFlgUserInputTableCell";
YesNoAnyDropDownList myDisabledFlgDDL = new YesNoAnyDropDownList();
myDisabledFlgDDL.ID = "ddlDisabledFlg";
if (myStyleDictionary.ContainsKey(SearchPanelControlType.DropDownList))
{
myDisabledFlgDDL.CssClass = myStyleDictionary[SearchPanelControlType.DropDownList];
}
myDisabledFlgDDL.DataBind();
myDisabledFlgUserInputTableCell.Controls.Add(myDisabledFlgDDL);
myTableRow2.Cells.Add(myDisabledFlgUserInputTableCell);
myTable.Rows.Add(myTableRow2);
myPanel.Controls.Add(myTitleStart);
myPanel.Controls.Add(myTitle);
myPanel.Controls.Add(myTitleEnd);
myPanel.Controls.Add(myTable);
}
internal override void FillSearchCriteria<T>(T myCriteria, ref Panel myPanel)
{
ApplicationFunctionCriteria derivedCriteria = new ApplicationFunctionCriteria();
if (myCriteria != null)
{
derivedCriteria = myCriteria as ApplicationFunctionCriteria;
}
// Name
TextBox myNameTextBox = (TextBox)myPanel.FindControl("myTable").FindControl("myTableRow1").FindControl("myNameUserInputTableCell").FindControl("txtName");
if (!string.IsNullOrEmpty(myNameTextBox.Text.Trim()))
{
derivedCriteria.Name = myNameTextBox.Text.Trim();
}
else
{
derivedCriteria.Name = string.Empty;
}
// AgencyID
DropDownList<AgencyCriteria> myAgencyDDL = (DropDownList<AgencyCriteria>)myPanel.FindControl("myTable").FindControl("myTableRow1").FindControl("myAgencyUserInputTableCell").FindControl("ddlAgency");
Guid myAgencyID;
if (myAgencyDDL.SelectedValue.TryParseGuid(out myAgencyID))
{
derivedCriteria.AgencyID = myAgencyID;
}
else
{
derivedCriteria.AgencyID = null;
}
// BusinessCriticalityID
DropDownList<LookupCodeCriteria> myBusinessCriticalityDDL = (DropDownList<LookupCodeCriteria>)myPanel.FindControl("myTable").FindControl("myTableRow2").FindControl("myBusinessCriticalityUserInputTableCell").FindControl("ddlBusinessCriticality");
Guid myBusinessCriticalityID;
if (myBusinessCriticalityDDL.SelectedValue.TryParseGuid(out myBusinessCriticalityID))
{
derivedCriteria.BusinessCriticalityID = myBusinessCriticalityID;
}
else
{
derivedCriteria.BusinessCriticalityID = null;
}
// DisabledFlg
YesNoAnyDropDownList myDisabledFlgDDL = (YesNoAnyDropDownList)myPanel.FindControl("myTable").FindControl("myTableRow2").FindControl("myDisabledFlgUserInputTableCell").FindControl("ddlDisabledFlg");
bool myDisabledFlg;
if (bool.TryParse(myDisabledFlgDDL.SelectedValue, out myDisabledFlg))
{
derivedCriteria.DisabledFlg = myDisabledFlg;
}
else
{
derivedCriteria.DisabledFlg = null;
}
}
internal override void SetSearchPanelControls<T>(T myCriteria, ref Panel myPanel)
{
ApplicationFunctionCriteria derivedCriteria = new ApplicationFunctionCriteria();
if (myCriteria != null)
{
derivedCriteria = myCriteria as ApplicationFunctionCriteria;
}
// Name
TextBox myNameTextBox = (TextBox)myPanel.FindControl("myTable").FindControl("myTableRow1").FindControl("myNameUserInputTableCell").FindControl("txtName");
myNameTextBox.Text = derivedCriteria.Name;
// AgencyID
DropDownList<AgencyCriteria> myAgencyDDL = (DropDownList<AgencyCriteria>)myPanel.FindControl("myTable").FindControl("myTableRow1").FindControl("myAgencyUserInputTableCell").FindControl("ddlAgency");
if (derivedCriteria.AgencyID.HasValue)
{
myAgencyDDL.SelectedValue = derivedCriteria.AgencyID.ToString();
}
else
{
myAgencyDDL.SelectedValue = "0";
}
// BusinessCriticalityID
DropDownList<LookupCodeCriteria> myBusinessCriticalityDDL = (DropDownList<LookupCodeCriteria>)myPanel.FindControl("myTable").FindControl("myTableRow2").FindControl("myBusinessCriticalityUserInputTableCell").FindControl("ddlBusinessCriticality");
if (derivedCriteria.BusinessCriticalityID.HasValue)
{
myBusinessCriticalityDDL.SelectedValue = derivedCriteria.BusinessCriticalityID.ToString();
}
else
{
myBusinessCriticalityDDL.SelectedValue = "0";
}
// DisabledFlg
YesNoAnyDropDownList myDisabledFlgDDL = (YesNoAnyDropDownList)myPanel.FindControl("myTable").FindControl("myTableRow2").FindControl("myDisabledFlgUserInputTableCell").FindControl("ddlDisabledFlg");
if (derivedCriteria.DisabledFlg.HasValue)
{
myDisabledFlgDDL.SelectedValue = derivedCriteria.DisabledFlg.ToString();
}
else
{
myDisabledFlgDDL.SelectedValue = "any";
}
}
}
Here is the code on the aspx page I am using to test the control:
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
</div>
</form>
</body>
</html>
And the codebehind:
public partial class test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
CustomWebControls.SearchGrid<AccountCriteria> myAppFuncGrid = new MyCompany.DCO.MyProject.CustomWebControls.SearchGrid<AccountCriteria>();
myAppFuncGrid.Type = MyCompany.DCO.MyProject.CustomWebControls.SearchGridType.Account;
myAppFuncGrid.SelectionType = MyCompany.DCO.Library.WebControls.MyCompanygridviewSelectionType.Multiple;
myAppFuncGrid.PageSize = 3;
PlaceHolder1.Controls.Add(myAppFuncGrid);
}
}
I've tried only putting the control in if (!Page.IsPostBack) as well, but then it just doesn't even display the control at all on Postback. What am I doing wrong?
UPDATE:
So I added this to the composite control:
protected override void OnInit(EventArgs e)
{
this.CreateChildControls(); base.OnInit(e);
}
And now I no longer get the "failed to load viewstate" error, but it seems that the viewstate of the child controls is not saved across postbacks. One of the controls in my composite control is a gridview with paging enabled and when clicking on next page it will go to page two, but never to page 3 or 4 or so on. But it will go to "last page", "first page" without a problem. But Next Page and Previous Page do no work correctly, but it doesn't throw an error either. Ideas?
When adding your control dynamically to your page, try overriding OnInit or CreateChildControls and doing it in there.
Viewstate is loaded in the pre-load stage and therefore it cannot load viewstate for your controls as they dont yet exist...
I've asked this before, but sadly I'm still having issues and the issue wasn't resolved. Basically, I'm dynamically creating a LinkButton for each row of a table I am generating, and that button has the task of deleting the row with the corresponding ID from the database. To do this, I seemingly need to assign the LinkButton a Command so it'll go into the event when it is clicked. Problem is, when the button's clicked the program never goes into the command - I've put breakpoints in there and it never goes into them. Here's my code:
protected void Page_Init(object sender, EventArgs e)
{
if (Request.QueryString["id"] != null)
{
ColorConverter conv = new ColorConverter();
string connection = ConfigurationManager.ConnectionStrings["TPRTestConnectionString"].ConnectionString;
TPRDBDataContext dc = new TPRDBDataContext();
DataContext db = new DataContext(connection);
Table<SageAccount> SageAccount = db.GetTable<SageAccount>();
Table<InvoiceItem> InvoiceItem = db.GetTable<InvoiceItem>();
Table<Invoice> Invoice = db.GetTable<Invoice>();
Boolean alloweditting = (from s in dc.Invoices where s.id.ToString() == Request.QueryString["id"] select s.alloweditting).Single();
if (alloweditting == false)
{
dtlsInsert.Visible = false;
modalPanel.Visible = false;
}
int sagepk = (from s in dc.Invoices where s.id.ToString() == Request.QueryString["id"] select s.sageaccount).Single();
lblSageID.Text = (from s in dc.SageAccounts where s.ID == sagepk select s.SageID).Single();
lblDate.Text = DateTime.Now.ToShortDateString();
Table table = new Table();
table.Width = Unit.Percentage(100);
table.GridLines = (GridLines)3;
TableHeaderRow header = new TableHeaderRow();
header.BackColor = (System.Drawing.Color)conv.ConvertFromString("#EDEDED");
foreach (string header2 in new string[] { "", "Quantity", "Rate", "Description", "Nominal Code", "Subtotal" })
{
TableCell cell = new TableCell();
cell.Text = header2;
header.Cells.Add(cell);
}
table.Rows.Add(header);
var data = (from s in dc.InvoiceItems where s.invoiceid.ToString() == Request.QueryString["id"].ToString() select s);
foreach (var x in data)
{
TableRow row = new TableRow();
if (x.invoicetext == null)
{
decimal total;
try
{
total = (decimal)x.rate * (decimal)x.quantity;
}
catch
{
total = 0;
}
int i = 0;
foreach (string columnData in new string[] { x.id.ToString(), x.quantity.ToString(), x.rate.ToString(), x.description, x.nominalcode, total.ToString("N2") })
{
TableCell cell = new TableCell();
{
if (i == 0)
{
LinkButton lnkdel = new LinkButton();
lnkdel.Text = "Delete";
lnkdel.ID = "lnkDel" + Guid.NewGuid();
if (alloweditting == false)
{
lnkdel.Enabled = false;
}
lnkdel.Font.Bold = false;
lnkdel.CommandArgument = x.id.ToString();
//lnkdel.Command += lnkdel_Command;
//lnkdel.Command += new CommandEventHandler(this.lnkdel);
cell.Controls.Add(lnkdel);
i++;
}
else
{
cell.Text = columnData;
}
}
row.Cells.Add(cell);
}
runningtotal = runningtotal + total;
}
else
{
int i = 0;
foreach (string columnData in new string[] { x.id.ToString(), x.invoicetext })
{
TableCell cell = new TableCell();
if (i == 0)
{
LinkButton lnkdel = new LinkButton();
lnkdel.Text = "Delete";
lnkdel.ID = "lnkDel" + Guid.NewGuid();
if (alloweditting == false)
{
lnkdel.Enabled = false;
}
lnkdel.Font.Bold = false;
//lnkdel.Command += lnkdel_Command;
//lnkdel.Command += new CommandEventHandler(this.lnkdel);
lnkdel.CommandArgument = x.id.ToString();
cell.Controls.Add(lnkdel);
i++;
}
else
{
cell.Text = columnData;
cell.ColumnSpan = 5;
}
row.Cells.Add(cell);
}
}
switch (x.formatoptions)
{
case 1:
row.ForeColor = (System.Drawing.Color)conv.ConvertFromString("black");
row.Font.Bold = false;
break;
case 2:
row.ForeColor = (System.Drawing.Color)conv.ConvertFromString("black");
row.Font.Bold = true;
break;
case 3:
row.ForeColor = (System.Drawing.Color)conv.ConvertFromString("red");
row.Font.Bold = false;
break;
case 4:
row.ForeColor = (System.Drawing.Color)conv.ConvertFromString("red");
row.Font.Bold = true;
break;
}
table.Rows.Add(row);
}
TableFooterRow row2 = new TableFooterRow();
TableCell cell2 = new TableCell();
cell2.Text = "<span style\"text-align: right; width: 100%;\">Total = <b>" + runningtotal.ToString("N2") + "</b></span>";
cell2.ColumnSpan = 6;
row2.Cells.Add(cell2);
table.Rows.Add(row2);
var update = (from s in dc.Invoices where s.id.ToString() == Request.QueryString["id"] select s).Single();
update.total = runningtotal;
dc.SubmitChanges();
datatable.Controls.Clear();
datatable.Controls.Add(table);
}
else
{
Response.Redirect("Invoices.aspx");
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void lnkdel_Command(object sender, CommandEventArgs e)
{
string connection = ConfigurationManager.ConnectionStrings["TPRTestConnectionString"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connection))
{
SqlCommand comm = new SqlCommand("DELETE FROM InvoiceItem WHERE id = #id", conn);
comm.Parameters.AddWithValue("#id", e.CommandArgument.ToString());
conn.Open();
try
{
comm.ExecuteNonQuery();
}
catch (Exception ex)
{
Response.Write(ex);
}
}
}
Note I've commented out 2 of the crucial lines for posting here, just to point out that I've tried both of the lines that's commented out, and neither work :(
You need to add the controls on every postback. You appear to be only creating them on the initial get (that query string check). On the post back, those controls never get recreated so no event fires.
It's notoriously counter-intuitive, but while ASP.NET bends over backwards to make you think that the instance of your page class is the same between two HTTP requests, the reality is that they are not the same. A new instance is created each time. It looks like you are trying to avoid adding the dynamically generated controls multiple times -- thinking you don't want duplicates. The reality is that you will never get duplicates when adding dynamically generated controls in a life-cycle method such as OnInit() since it's always a new instance of the page class, and thus those dynamically generated controls are gone.
The reason this is usually transparent to developers is that all the controls in the code-front are automatically re-generated for you on both the initial request and every single post-back. For your dynamically created controls, you happen to have this line:
if (Request.QueryString["id"] != null) { ... }
Unless you're doing something special, that "id" attribute will not be in the query string on the postback. This means that none of the code in the if block will be run on the post back (when your event actually fires.) This means that your if-check at the top should be removed altogether. All that code should run for each and every request (GET and POST).
Just saying I've created a workaround - simply creating a simple link to the page, along with a query string containing the id of the row to delete