how do i fetch the id of a dynamically created web control - c#

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.

Related

Gridview Footer Default Value Missing

I have a gridview which can searched by date.
In the gridview, i manually add in footer if the gridview for the date is empty.
It work fine then first load the page.
The problem is :
When load the gridview with data, the footer show default data. After that, select date where no data, default values are missing. If I select another date without data, the default value of footer come out again.
I put breakpoint and it went through the following function, the value is not null but it is no displayed on the Label of footer.
while (Dr.Read())
{
AttendbyFooter.Text = Dr.GetValue(1).ToString();
DepartmentFooter.Text = Dr.GetValue(4).ToString();
}
Gridview databound:
Label AttendbyFooter = GridView1.FooterRow.FindControl("AttendbyFooter") as Label;
//if the footer is null, do nothing. if the footer is not null, continue for other value
if (AttendbyFooter == null)
{
}
else
{
//set default name
AttendbyFooter.Attributes.Add("readonly", "readonly");
Label DepartmentFooter = GridView1.FooterRow.FindControl("DepartmentFooter") as Label;
DepartmentFooter.Attributes.Add("readonly", "readonly");
//create a connection to mssql server
var Cn = new System.Data.SqlClient.SqlConnection();
Cn.ConnectionString = ConfigurationManager.ConnectionStrings["CMOSConnectionString"].ConnectionString;
Cn.Open();
//create a command object from the connection
var Cm = Cn.CreateCommand();
//Check database using username(id number)
Cm.CommandText = string.Format(#"Select * From Employee WHERE PassNumber='{0}'", User.Identity.Name);
var Dr = Cm.ExecuteReader();
while (Dr.Read())
{
//Name
AttendbyFooter.Text = Dr.GetValue(1).ToString();
DepartmentFooter.Text = Dr.GetValue(4).ToString();
}
Cn.Close();
}
Generate footer(copy from website)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace YourNamespace
{
public class GridViewExtended : GridView
{
#region Public Properties
[Category("Behavior")]
[Themeable(true)]
[Bindable(BindableSupport.No)]
public bool ShowFooterWhenEmpty
{
get
{
if (this.ViewState["ShowFooterWhenEmpty"] == null)
{
this.ViewState["ShowFooterWhenEmpty"] = false;
}
return (bool)this.ViewState["ShowFooterWhenEmpty"];
}
set
{
this.ViewState["ShowFooterWhenEmpty"] = value;
}
}
#endregion
private GridViewRow _footerRow2;
public override GridViewRow FooterRow
{
get
{
GridViewRow f = base.FooterRow;
if (f != null)
return f;
else
return _footerRow2;
}
}
protected override int CreateChildControls(System.Collections.IEnumerable dataSource, bool dataBinding)
{
int rows = base.CreateChildControls(dataSource, dataBinding);
// no data rows created, create empty table if enabled
if (rows == 0 && (this.ShowFooterWhenEmpty))
{
// create the table
Table table = this.CreateChildTable();
DataControlField[] fields;
if (this.AutoGenerateColumns)
{
PagedDataSource source = new PagedDataSource();
source.DataSource = dataSource;
System.Collections.ICollection autoGeneratedColumns = this.CreateColumns(source, true);
fields = new DataControlField[autoGeneratedColumns.Count];
autoGeneratedColumns.CopyTo(fields, 0);
}
else
{
fields = new DataControlField[this.Columns.Count];
this.Columns.CopyTo(fields, 0);
}
if (this.ShowHeaderWhenEmpty)
{
// create a new header row
GridViewRow headerRow = base.CreateRow(-1, -1, DataControlRowType.Header, DataControlRowState.Normal);
this.InitializeRow(headerRow, fields);
// add the header row to the table
table.Rows.Add(headerRow);
}
// create the empty row
GridViewRow emptyRow = new GridViewRow(-1, -1, DataControlRowType.EmptyDataRow, DataControlRowState.Normal);
TableCell cell = new TableCell();
cell.ColumnSpan = fields.Length;
cell.Width = Unit.Percentage(100);
// respect the precedence order if both EmptyDataTemplate
// and EmptyDataText are both supplied ...
if (this.EmptyDataTemplate != null)
{
this.EmptyDataTemplate.InstantiateIn(cell);
}
else if (!string.IsNullOrEmpty(this.EmptyDataText))
{
cell.Controls.Add(new LiteralControl(EmptyDataText));
}
emptyRow.Cells.Add(cell);
table.Rows.Add(emptyRow);
if (this.ShowFooterWhenEmpty)
{
// create footer row
_footerRow2 = base.CreateRow(-1, -1, DataControlRowType.Footer, DataControlRowState.Normal);
this.InitializeRow(_footerRow2, fields);
// add the footer to the table
table.Rows.Add(_footerRow2);
}
this.Controls.Clear();
this.Controls.Add(table);
}
return rows;
}
}
}
Try clearing the date textbox after pageload.

How to add Repeater control dynamically from code behind?

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; }
}
}

Telerik report showing same data for all columns created dynamically

I have created a telerik report using Visual Studio and set the Datasource from the DataTable. I am creating the columns dynamically at runtime using Telerik.Reporting.TableGroup. Now the problem I am having here is that the report showing the same data for all of the fields and when I debug it is setting different fields for different.
The code I am using is as follows:
private void Report4_NeedDataSource(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt = SalesReport.reportDataTable;
table1.DataSource = dt;
Telerik.Reporting.HtmlTextBox textboxGroup;
Telerik.Reporting.HtmlTextBox textBoxTable;
table1.ColumnGroups.Clear();
table1.Body.Columns.Clear();
table1.Body.Rows.Clear();
int ColCount = dt.Columns.Count;
for (int i = 0; i <= ColCount - 1; i++)
{
Telerik.Reporting.TableGroup tableGroupColumn = new Telerik.Reporting.TableGroup();
table1.ColumnGroups.Add(tableGroupColumn);
textboxGroup = new Telerik.Reporting.HtmlTextBox();
textboxGroup.Style.BorderColor.Default = Color.Black;
textboxGroup.Style.BorderStyle.Default = BorderType.Solid;
textboxGroup.Value = dt.Columns[i].ColumnName;
textboxGroup.Size = new SizeU(Unit.Inch(1.5), Unit.Inch(0.6));
tableGroupColumn.ReportItem = textboxGroup;
textBoxTable = new Telerik.Reporting.HtmlTextBox();
textBoxTable.Value = "=Fields." + dt.Columns[i].ColumnName;
textBoxTable.Size = new SizeU(Unit.Inch(1.1), Unit.Inch(0.3));
table1.Body.SetCellContent(0, i, textBoxTable);
table1.Items.AddRange(new ReportItemBase[] { textBoxTable, textboxGroup });
}
}
I suggest reading the following article. I found this same problem and my solution was to add unique names to the group column, label, and detail text boxes.
http://www.telerik.com/forums/incorrect-dynamic-table-columns
//Added
tableGroupColumn.Name = "group" + *something_uniquegoeshere*;
//Added
textboxGroup.Name = "label" + *something_uniquegoeshere*;
//Added
textBoxTable.Name = "data" + *something_uniquegoeshere*;
Not enough space in a comment unfortunately but here's my advice/suggestion. I'm not certain about your specific error, however in the past I have had issues when re-using variables. You declare your variable outside the for statement and it is possible that this is what is causing the problem.
private void Report4_NeedDataSource(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt = SalesReport.reportDataTable;
table1.DataSource = dt;
//Telerik.Reporting.HtmlTextBox textboxGroup;
//Telerik.Reporting.HtmlTextBox textBoxTable;
table1.ColumnGroups.Clear();
table1.Body.Columns.Clear();
table1.Body.Rows.Clear();
int ColCount = dt.Columns.Count;
for (int i = 0; i <= ColCount - 1; i++)
{
Telerik.Reporting.TableGroup tableGroupColumn = new Telerik.Reporting.TableGroup();
table1.ColumnGroups.Add(tableGroupColumn);
var textboxGroup = new Telerik.Reporting.HtmlTextBox();
textboxGroup.Style.BorderColor.Default = Color.Black;
textboxGroup.Style.BorderStyle.Default = BorderType.Solid;
textboxGroup.Value = dt.Columns[i].ColumnName;
textboxGroup.Size = new SizeU(Unit.Inch(1.5), Unit.Inch(0.6));
tableGroupColumn.ReportItem = textboxGroup;
var textBoxTable = new Telerik.Reporting.HtmlTextBox();
textBoxTable.Value = "=Fields." + dt.Columns[i].ColumnName;
textBoxTable.Size = new SizeU(Unit.Inch(1.1), Unit.Inch(0.3));
table1.Body.SetCellContent(0, i, textBoxTable);
table1.Items.AddRange(new ReportItemBase[] { textBoxTable, textboxGroup });
}
}

Find specific row attribute jQuery

On my asp.net form, within a table row I add cells and within those cells I add textboxes with an attribute like -
string residentId = (new GUID()).ToString();
string houseId = (new GUID()).ToString();
HtmlTableRow detailRow = new HtmlTableRow();
detailRow.Attributes.Add("residentId", residentId);
detailRow.Attributes.Add("houseId", houseId);
HtmlTableCell dataCell = new HtmlTableCell();
TextBox tb = new TextBox();
tb.Attributes.Add("componentname", "tbMoveInDate");
tb.Attributes.Add("onchange", "updateMoveInDate()";
cell.Controls.Add(tb);
detailRow.Cells.Add(dataCell);
with a possiblility of 100+ rows, all with distinct IDs of course.
within my javascript I have this function -
function updateMoveInDate() {
var MoveInDateEle = $("[componentname*='tbMoveInDate']");
}
at this point MoveInDateEle is a collection of all of those text boxes within the table and
var currentRow = $("[componentname*='tbMoveInDate']").parent().parent();
gives me all of the rows. but not my specific row.
How is it possible to get the specific text box I am working with and the specific resident Id and house Id associated with that control?
Modify the C# code like this:
tb.Attributes.Add("onchange", "updateMoveInDate(this)";
and the js function like:
// obj here refers to the current textbox in the scope
// on which the on-change event had occurred...
function updateMoveInDate(obj) {
var currentRow = $(obj).closest('tr');
}
You could do
tb.Attributes.Add("onchange", "updateMoveInDate(this)";
And
function updateMoveInDate(txt) {
var $txt = $(txt);
var $row = $txt.closest('tr');
var residentId = $row.attr('residentId');
var houseId = $row.attr('houseId');
}
Try this
tb.Attributes.Add("onchange", "updateMoveInDate(this)";
in code behind
string residentId = (new GUID()).ToString();
string houseId = (new GUID()).ToString();
HtmlTableRow detailRow = new HtmlTableRow();
detailRow.Attributes.Add("residentId", residentId);
detailRow.Attributes.Add("houseId", houseId);
HtmlTableCell dataCell = new HtmlTableCell();
TextBox tb = new TextBox();
tb.Attributes.Add("componentname", "tbMoveInDate");
tb.Attributes.Add("onchange", "updateMoveInDate(this)";
cell.Controls.Add(tb);
detailRow.Cells.Add(dataCell);
jQuery:
function updateMoveInDate(args) {
var MoveInDateEle = $(args).closest('tr');
}

Dynamically created LinkButton won't go into command event

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

Categories