I am appending rows using item template
<tr>
<td>
<asp:HyperLink ID="HyperLink1" NavigateUrl="bla" CssClass="display:inherit !important;" Text='<%# someFunction(School.Name,"Name") %>' runat="server" />
</td>
</tr>
the problem with the above one is if someFunction(School.Name,"Name") returns null it appends empty tr, so i want to append tr only if someFunction(School.Name,"Name")!=null
So i tried the below code by adding a if condition but it is not compiling !!
It says school.name is not defined
<% if(someFunction(School.Name,"Name")!=null){
<tr>
<td>
<asp:HyperLink ID="HyperLink1" NavigateUrl="bla" CssClass="display:inherit !important;" Text='<%# someFunction(School.Name,"Name") %>' runat="server" />
</td>
</tr>
} %>
You could take care of it from the code behind.
<td id="tdAppend" runat="server"> Content </td>
if(School.Name == null)
tdAppend.Visible = false;
UPDATED ANSWER:
currentItemIndex = -1;
listView.ItemDataBound += listView_ItemDataBound;
CheckQueryString();
//Hide or show the table header based on id
HtmlControl thControl = listView.FindControl("thAppend") as HtmlControl;
if (thControl != null)
{
if (obj.ID == 12)
{
thControl.Visible = true;
}
else
{
thControl.Visible = false;
for (int i = 0; i < listView.Items.Count; i++)
{
HtmlControl tdControl = listView.Items[i].FindControl("tdSchoolName") as HtmlControl;
if (tdControl != null)
{
tdControl.Visible = false;
}
}
}
}
For convenience:
void listView_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
currentItemIndex++;
ListViewDataItem dataitem = (ListViewDataItem)e.Item;
HtmlTableRow trControl = (HtmlTableRow)e.Item.FindControl("MainTableRow");
if (IsOdd(currentItemIndex))
trControl.BgColor = "DarkGray";
}
}
private bool IsOdd(int value)
{
return value % 2 != 0;
}
It's a pretty straight forward practice.. Handling the ListView.OnItemDataBinding event.
Markup
<%# Import Namespace="MyNamespace" %>
<asp:ListView ID="lview" runat="server" OnItemDataBound="lview_ItemDataBound" ItemPlaceholderID="Placeholder1">
<ItemTemplate>
<tr>
<td><%# ((School)Container.DataItem).Name %></td>
</tr>
</ItemTemplate>
<LayoutTemplate>
<table>
<div id="Placeholder1" runat="server"></div>
</table>
</LayoutTemplate>
</asp:ListView>
Code-Behind
namespace MyNamespace
{
public class Default : Page
{
IEnumerable<School> dataItems {get;set;}
protected void Page_Load(object sender, EventArgs e)
{
dataItems = new School[] { new School() { Name = "School 1" }, new School() { Name = "School 2" }, new School() { Name = null }, new School() { Name = "School 3" } }.AsEnumerable();
lview.DataSource = dataItems;
lview.DataBind();
}
protected void lview_ItemDataBound(object sender, ListViewItemEventArgs e)
{
ListView listview = (ListView)sender;
ListViewItem row = e.Item;
School dataItem = (School)e.Item.DataItem;
if (dataItem.Name == null)
{
row.Visible = false;
}
}
}
public class School
{
public string Name { get; set; }
}
}
personally, I don't usually use tables.. it's a fairly odd-looking layout template.
Related
I hope to explain my problem clearly.
I have a asp.net page (default.aspx) with a ScriptManager, an UpdatePanel containing a PlaceHolder (PlaceHolderUC) and two buttons (btnAddControl and btnRefreshPage) triggered to this UpdatePanel.
I have a Web User Control (UControl.ascx) with a table containing some html controls:
a textbox (txtOrder) where I store the order number of the control itself; it is useful for me to understand if the sorting works; then it will be replaced by a hidden control
a label (lblTest) where I write the name of the control (eg. Control #1)
a textbox (txtTest) where, when i run the project, I write some text to test persistence of the controls
a button (btnMoveDown) to move the control downwards
a button (btnMoveUp) to move the control upwards
a button (btnRemove) to remove the control
When I press button "btnAddControl", add a new UControl to the placeholder "PlaceHolderUC";
Everything works fine; even removing the control, when I press the "btnRemove" button, works.
Page after adding 4 UControl
The problem occurs when I want to move the controls by pressing the "btnMoveDown" and "btnMoveUp" buttons.
The logical move works, but the panel is not updated.
I pressed the "btnMoveDown" button on Control # 2; it updated the sort textbox (txtOrder) field but did not physically move the controls
To update the panel I have to press the "btnRefreshPage" button.
I tried adding the UPanel.Update(); command after the button is pressed, but that doesn't work either.
The list "UControlList" is used to keep data persistence.
I also tried moving component loading from Page_Load to other page events, but it still doesn't work
This is my code.
default.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="TestUpdatePanel._default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test Update Panel</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<p>
<asp:Button ID="btnAddControl" runat="server" Text="Add control" OnClick="btnAddControl_Click" />
</p>
<asp:ScriptManager ID="SManager" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UPanel" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:PlaceHolder ID="PlaceHolderUC" runat="server"></asp:PlaceHolder>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnAddControl" EventName="Click" />
<asp:AsyncPostBackTrigger ControlID="btnRefreshPage" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
<asp:Button ID="btnRefreshPage" runat="server" Text="Refresh Page" OnClick="btnRefreshPage_Click" />
</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 TestUpdatePanel
{
[Serializable]
public class UControlClass
{
public UControlClass()
{
}
public int ID { get; set; }
public int Order { get; set; }
public String Label { get; set; }
}
public partial class _default : System.Web.UI.Page
{
public List<UControlClass> UControlList
{
get
{
if (ViewState["UControlList"] == null)
ViewState["UControlList"] = new List<UControlClass>();
return (List<UControlClass>)ViewState["UControlList"];
}
set
{
ViewState["UControlList"] = value;
}
}
private void ReloadControls()
{
int i = 0;
foreach (var tmp in UControlList.OrderBy(x => x.Order))
{
i++;
var c = (UControl)LoadControl("UControl.ascx");
c.ID = "C_" + tmp.ID.ToString();
c.Label = tmp.Label;
c.IsFirst = (i == 1);
c.IsLast = (i == UControlList.Count);
c.BtnRemoveClickEvent += C_BtnRemoveClickEvent;
c.BtnMoveUpClickEvent += C_BtnMoveUpClickEvent;
c.BtnMoveDownClickEvent += C_BtnMoveDownClickEvent;
PlaceHolderUC.Controls.Add(c);
}
}
protected void Page_Load(object sender, EventArgs e)
{
ReloadControls();
}
private void RefreshSorting()
{
int i = 0;
foreach (var tmp in UControlList.OrderBy(x => x.Order))
{
i++;
var c = (UControl)PlaceHolderUC.FindControl("C_" + tmp.ID.ToString());
if (c == null)
return;
c.IsFirst = (i == 1);
c.IsLast = (i == UControlList.Count);
}
}
protected void btnAddControl_Click(object sender, EventArgs e)
{
UControlClass UClass = new UControlClass();
UClass.ID = UControlList.DefaultIfEmpty().Max(x => x == null ? 0 : x.ID) + 1;
UClass.Order = UControlList.DefaultIfEmpty().Max(x => x == null ? 0 : x.Order) + 1;
UClass.Label = "Control # " + UClass.ID.ToString();
var c = (UControl)LoadControl("UControl.ascx");
c.ID = "C_" + UClass.ID.ToString();
c.Order = UClass.Order;
c.Label = UClass.Label;
c.BtnRemoveClickEvent += C_BtnRemoveClickEvent;
c.BtnMoveUpClickEvent += C_BtnMoveUpClickEvent;
c.BtnMoveDownClickEvent += C_BtnMoveDownClickEvent;
c.IsFirst = (UControlList.Count == 0);
c.IsLast = true;
UControlList.Add(UClass);
PlaceHolderUC.Controls.Add(c);
RefreshSorting();
}
private void C_BtnMoveDownClickEvent(object sender, UControlEventArgs e)
{
try
{
var CurrentControl = (UControl)PlaceHolderUC.FindControl("C_" + e.ID.ToString());
var CurrentList = UControlList.Find(x => x.ID == e.ID);
if (CurrentControl == null || CurrentList == null || CurrentControl.Order != CurrentList.Order)
return;
var NextList = UControlList.OrderBy(x => x.Order).Reverse().TakeWhile(x => x.Order > CurrentControl.Order).LastOrDefault();
if (NextList == null)
return;
var NextControl = (UControl)PlaceHolderUC.FindControl("C_" + NextList.ID.ToString());
if (NextControl == null || NextControl.Order != NextList.Order)
return;
Int32 tmp = CurrentControl.Order;
CurrentControl.Order = NextControl.Order;
CurrentList.Order = NextControl.Order;
NextControl.Order = tmp;
NextList.Order = tmp;
RefreshSorting();
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
}
private void C_BtnMoveUpClickEvent(object sender, UControlEventArgs e)
{
try
{
var CurrentControl = (UControl)PlaceHolderUC.FindControl("C_" + e.ID.ToString());
var CurrentList = UControlList.Find(x => x.ID == e.ID);
if (CurrentControl == null || CurrentList == null || CurrentControl.Order != CurrentList.Order)
return;
var PreviousList = UControlList.OrderBy(x => x.Order).TakeWhile(x => x.Order < CurrentControl.Order).LastOrDefault();
if (PreviousList == null)
return;
var PreviousControl = (UControl)PlaceHolderUC.FindControl("C_" + PreviousList.ID.ToString());
if (PreviousControl == null || PreviousControl.Order != PreviousList.Order)
return;
Int32 tmp = CurrentControl.Order;
CurrentControl.Order = PreviousControl.Order;
CurrentList.Order = PreviousControl.Order;
PreviousControl.Order = tmp;
PreviousList.Order = tmp;
RefreshSorting();
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
}
private void C_BtnRemoveClickEvent(object sender, UControlEventArgs e)
{
try
{
var c = (UControl)PlaceHolderUC.FindControl("C_" + e.ID.ToString());
if (c == null)
return;
UControlList.RemoveAll(x => x.ID == e.ID);
PlaceHolderUC.Controls.Remove(c);
c.Dispose();
RefreshSorting();
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
}
protected void btnRefreshPage_Click(object sender, EventArgs e)
{
// Do nothing...
}
}
}
UControl.ascx
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="UControl.ascx.cs" Inherits="TestUpdatePanel.UControl" %>
<table border="0">
<tr>
<td>
<asp:TextBox ID="txtOrder" runat="server" Enabled="false"></asp:TextBox>
</td>
<td>
<asp:Label ID="lblTest" runat="server"></asp:Label>
</td>
<td>
<asp:TextBox ID="txtTest" runat="server"></asp:TextBox>
</td>
<td>
<asp:Button ID="btnMoveDown" runat="server" Text="Down" OnClick="btnMoveDown_Click" />
</td>
<td>
<asp:Button ID="btnMoveUp" runat="server" Text="Up" OnClick="btnMoveUp_Click" />
</td>
<td>
<asp:Button ID="btnRemove" runat="server" Text="Remove" OnClick="btnRemove_Click" />
</td>
</tr>
</table>
<hr />
UControl.ascx.cs
using System;
namespace TestUpdatePanel
{
public class UControlEventArgs : System.EventArgs
{
public Int32 ID { get; }
public UControlEventArgs(Int32 id)
{
ID = id;
}
}
public partial class UControl : System.Web.UI.UserControl
{
public String Label
{
get { return lblTest.Text; }
set { lblTest.Text = value; }
}
public Int32 Order
{
get { return Convert.ToInt32(txtOrder.Text); }
set { txtOrder.Text = value.ToString(); }
}
private Boolean _IsFirst;
public Boolean IsFirst
{
get { return _IsFirst; }
set
{
_IsFirst = value;
btnMoveUp.Enabled = !_IsFirst;
}
}
private Boolean _IsLast;
public Boolean IsLast
{
get { return _IsLast; }
set
{
_IsLast = value;
btnMoveDown.Enabled = !_IsLast;
}
}
public delegate void MyEventHandler(object sender, UControlEventArgs e);
public event MyEventHandler BtnRemoveClickEvent;
public event MyEventHandler BtnMoveUpClickEvent;
public event MyEventHandler BtnMoveDownClickEvent;
private void OnBtnRemoveClickEvent(int ID)
{
BtnRemoveClickEvent?.Invoke(this, new UControlEventArgs(ID));
}
protected void btnRemove_Click(object sender, EventArgs e)
{
OnBtnRemoveClickEvent(Convert.ToInt32(ID.Replace("C_", "")));
}
private void OnBtnMoveUpClickEvent(int ID)
{
BtnMoveUpClickEvent?.Invoke(this, new UControlEventArgs(ID));
}
protected void btnMoveUp_Click(object sender, EventArgs e)
{
OnBtnMoveUpClickEvent(Convert.ToInt32(ID.Replace("C_", "")));
}
private void OnBtnMoveDownClickEvent(int ID)
{
BtnMoveDownClickEvent?.Invoke(this, new UControlEventArgs(ID));
}
protected void btnMoveDown_Click(object sender, EventArgs e)
{
OnBtnMoveDownClickEvent(Convert.ToInt32(ID.Replace("C_", "")));
}
protected void Page_Load(object sender, EventArgs e)
{
}
}
}
Any suggestions, even for non-issue topics, are welcome.
Thanks to whoever answers me.
It would be very important for me to solve the problem because it is a work project.
I have created dynamic radio button/check box controls with help of a repeater. But the controls are getting lost after postback.
as an example, if i check the radion button which is i create using the repeater all the radio buttons will disappear
here is my aspx code
<asp:Repeater ID="myRepeater" runat="server" OnItemCommand="myRepeater_ItemCommand" OnItemDataBound="myRepeater_ItemDataBound">
<HeaderTemplate>
<table>
<tr class="">
<td>
</td>
<td>
Name
</td>
<td>
Address
</td>
<td>
Age
</td>
<td>
Year
</td>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<asp:Panel ID="pnlSelect" runat="server" EnableViewState="true"></asp:Panel>
</td>
<td>
<%#Eval("Name")%>
</td>
<td>
<%#Eval("Address")%>
</td>
<td>
<%#Eval("Age")%>
</td>
<td>
<%# Eval("Year")%>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
my .cs code
myRepeater.DataSource = *DataSource*;
myRepeater.DataBind();
protected void myRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
{
if (** condition 01 **)
{
if (** condition 02 **)
{
RadioButton rdoBtn = new RadioButton();
rdoBtn.ID = "rbtnID";
rdoBtn.EnableViewState = true;
rdoBtn.GroupName = "GroupName";
rdoBtn.AutoPostBack = true;
rdoBtn.CheckedChanged += new System.EventHandler(this.rdoBtnChecked_Changed);
string script = "SetUniqueRadioButton('myRepeater.*GroupName',this)";
rdoBtn.Attributes.Add("onclick", script);
Panel pnlRbtnSet = e.Item.FindControl("pnlSelect") as Panel;
pnlRbtnSet.Controls.Add(rdoBtn);
}
else
{
CheckBox chkBox = new CheckBox();
chkBox.ID = "chkBxID";
chkBox.Checked = true;
chkBox.EnableViewState = true;
Panel pnlChkBoxesSet = e.Item.FindControl("pnlSelect") as Panel;
pnlChkBoxesSet.Controls.Add(chkBox);
}
}
}
}
protected void rdoBtnChecked_Changed(Object sender, EventArgs e)
{
}
i have set enableViewState=true for both the drawing panel and each control which is creating dynamically. but it does not work. please help me...
If you need to create dynamic controls you have to recreate them on every postback. So ItemDataBound is inappropriate since it's only triggered when the repeater is getting databound. Use ItemCreated instead.
protected void myRepeater_ItemCreated(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
{
if (** condition 01 **)
{
if (** condition 02 **)
{
RadioButton rdoBtn = new RadioButton();
rdoBtn.ID = "rbtnID";
rdoBtn.EnableViewState = true;
rdoBtn.GroupName = "GroupName";
rdoBtn.AutoPostBack = true;
rdoBtn.CheckedChanged += new System.EventHandler(this.rdoBtnChecked_Changed);
string script = "SetUniqueRadioButton('myRepeater.*GroupName',this)";
rdoBtn.Attributes.Add("onclick", script);
Panel pnlRbtnSet = e.Item.FindControl("pnlSelect") as Panel;
pnlRbtnSet.Controls.Add(rdoBtn);
}
else
{
CheckBox chkBox = new CheckBox();
chkBox.ID = "chkBxID";
chkBox.Checked = true;
chkBox.EnableViewState = true;
Panel pnlChkBoxesSet = e.Item.FindControl("pnlSelect") as Panel;
pnlChkBoxesSet.Controls.Add(chkBox);
}
}
}
}
I have a 2 Dropdownlist outside a repeater (1st ddl will trigger and refresh the content of the repeater, 2nd ddl refresh its list after an item inside the repeater were executed) and a dropdownlist control inside the repeater.i don't have a problem with the 1st dropdownlist but the 2nd dropdownlist when triggered via selectedindexchanged, it also fires up the selectedindexchanged of the dropdownlist inside the repeater. I put up an UpdatePanel on the repeater and on the 2nd dropdownlist but still the error occurs.
How can i trace the step by step execution and also why the selectedindexchanged handler fires up?
Here is the code snippet:
CODE BEHIND:
public partial class NewStyleItem : System.Web.UI.Page
{
protected StyleTemplateManager styleTempMngr = new StyleTemplateManager();
protected StyleFabricationManager styleFabMngr = new StyleFabricationManager();
protected List<ComponentReferenceView> ReferenceLookUpList
{
get
{
return (List<ComponentReferenceView>)ViewState["ReferenceLookUpView"];
}
set
{
ViewState["ReferenceLookUpView"] = value;
}
}
protected List<ComponentReferenceView> ReferenceViewList
{
get
{
return (List<ComponentReferenceView>)ViewState["CompReferenceView"];
}
set
{
ViewState["CompReferenceView"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (this.IsPostBack == false)
{
LoadBrandList();
ddlGarmentList.Enabled = false;
//ReferenceLookUpList = new List<ComponentReferenceView>();
}
else
{
}
//rptStyleComponents.DataSource = ReferenceLookUpList;
//rptStyleComponents.DataBind();
}
protected void LoadBrandList()
{
BrandManager brandMngr = new BrandManager();
ddlBrandList.Items.Clear();
ddlBrandList.Items.Add(new ListItem { Text = "Select brand", Value = "" });
foreach (Brand item in brandMngr.Brands())
{
ddlBrandList.Items.Add(new ListItem
{
Text = item.BrandDescription,
Value = item.BrandCode
});
}
}
protected void LoadComponentInfo(string BrandCode)
{
if (styleTempMngr.FindTemplateByBrandCode(BrandCode) == true)
{
ReferenceLookUpList = (from StyleComponent i in styleFabMngr.ComponentList
join StyleFabReference x in styleTempMngr.ReferenceList on
i.SectionCode equals x.SectionCode
select new ComponentReferenceView
{
InOrder = x.SortOrder,
IsNeeded = x.IsRequired,
SCode = x.SeriesCode,
SecCode = x.SectionCode,
SecName = i.SectionName,
EntryValue = x.DataCharacter
}).OrderBy(p => p.InOrder).ToList();
ReferenceLookUpList.Where(row => row.SecCode == "BCODE").ToList()
.ForEach(refItem => refItem.EntryValue = ddlBrandList.SelectedValue);
var DistinctList = (from StyleFabReference x in styleTempMngr.ReferenceList.OrderBy(p => p.SortOrder).ToList()
where x.SectionCode != "SPCHAR" && x.SectionCode != "BCODE"
select x.SectionCode).Distinct().ToList();
ReferenceViewList = (from StyleComponent i in styleFabMngr.ComponentList
join x in DistinctList on
i.SectionCode equals x
select new ComponentReferenceView
{
SecCode = x,
SecName = i.SectionName
}).OrderBy(p => p.InOrder).ToList();
}
else
ReferenceViewList = new List<ComponentReferenceView>();
rptStyleComponents.DataSource = ReferenceViewList;
rptStyleComponents.DataBind();
}
protected void LoadGarments(string ApparelCode)
{
if (string.IsNullOrEmpty(ddlBrandList.SelectedValue) == true)
{
ddlGarmentList.SelectedIndex = 0;
ddlGarmentList.Enabled = false;
}
else
{
ddlGarmentList.Enabled = true;
GarmentManager gmMngr = new GarmentManager();
List<Garment> garmentList = new List<Garment>();
garmentList = gmMngr.GetGarmentsByBrand(ddlBrandList.SelectedValue, ApparelCode);
ddlGarmentList.Items.Clear();
ddlGarmentList.Items.Add(new ListItem { Text = "Select garment", Value = "" });
foreach (Garment item in garmentList)
{
ddlGarmentList.Items.Add(new ListItem { Text = item.GarmentDescription, Value = item.GarmentCode });
}
}
}
protected void ddlBrandList_SelectedIndexChanged(object sender, EventArgs e)
{
txtNewStyleNo.Text = string.Empty;
if (string.IsNullOrEmpty(ddlBrandList.SelectedValue) == false)
LoadComponentInfo(ddlBrandList.SelectedValue);
}
[Serializable]
public class ComponentReferenceView
{
public string SCode
{
get;
set;
}
public string SecCode
{
get;
set;
}
public string SecName
{
get;
set;
}
public int InOrder
{
get;
set;
}
public bool IsNeeded
{
get;
set;
}
public string EntryValue
{
get;
set;
}
}
protected void rptStyleComponents_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
}
protected void rptStyleComponents_ItemCreated(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
DropDownList ddlControl = (DropDownList)e.Item.FindControl("ddlDataSelection");
if (ddlControl != null)
{
ddlControl.AppendDataBoundItems = true;
ddlControl.Items.Add(new ListItem { Text = "Select " + ReferenceViewList[e.Item.ItemIndex].SecName.ToLowerInvariant(), Value = "" });
var itemlist = (from x in styleFabMngr.ComponentRowItems(ReferenceViewList[e.Item.ItemIndex].SecCode).AsEnumerable()
select new ListItem
{
Text = x.Field<string>("col_name"),
Value = x.Field<string>("col_value")
});
ddlControl.Items.AddRange(itemlist.ToArray<ListItem>());
ddlControl.EnableViewState = false;
ddlControl.AutoPostBack = true;
ddlControl.SelectedIndexChanged += new EventHandler(DropDownListSelectedIndexChanged);
}
}
}
protected virtual void DropDownListSelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddl = (DropDownList)sender;
RepeaterItem item = (RepeaterItem)ddl.NamingContainer;
ReferenceViewList[item.ItemIndex].EntryValue = ddl.SelectedValue;
ConstructStyleNo();
var Apparelfound = ReferenceViewList.Where(x => x.SecCode == "APCODE" &&
string.IsNullOrEmpty(x.EntryValue) == false).FirstOrDefault();
if (Apparelfound != null)
{
ddlGarmentList.Enabled = true;
LoadGarments(Apparelfound.EntryValue);
}
else
{
ddlGarmentList.Enabled = false;
}
}
private void ConstructStyleNo()
{
foreach (ComponentReferenceView item in ReferenceViewList)
{
ReferenceLookUpList.Where(row => row.SecCode == item.SecCode).ToList()
.ForEach(refItem => refItem.EntryValue = item.EntryValue);
}
string sResult = string.Empty;
var result = (from x in ReferenceLookUpList.OrderBy(y => y.InOrder)
select x.EntryValue);
txtNewStyleNo.Text = string.Empty;
if (result != null)
txtNewStyleNo.Text = String.Join("", result) + "0001";
}
private void ConstructStyleDescription()
{
txtStyleDescription.Text = ddlBrandList.SelectedItem.Text + "-" + ddlGarmentList.SelectedItem.Text;
}
protected void ddlGarmentList_SelectedIndexChanged(object sender, EventArgs e)
{
txtStyleDescription.Text = string.Empty;
if (string.IsNullOrEmpty(ddlGarmentList.SelectedValue) == false)
ConstructStyleDescription();
}
}
ASPX:
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<asp:UpdatePanel ID="upnlNewFabrication" runat="server">
<ContentTemplate>
<h1>
New Style Item
</h1>
<br />
<%--<usrCtrl:style_generation ID="stylegen_frm" runat="server">
</usrCtrl:style_generation>--%>
<table>
<tr>
<td>
Brand :
</td>
<td>
<asp:DropDownList ID="ddlBrandList" runat="server"
onselectedindexchanged="ddlBrandList_SelectedIndexChanged"
AutoPostBack="True">
</asp:DropDownList>
</td>
</tr>
<tr>
<td colspan="2">
</td>
</tr>
<tr>
<td>
Generated Style# :
</td>
<td>
<asp:TextBox ID="txtNewStyleNo" runat="server" ReadOnly="true"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Style Description :
</td>
<td>
<asp:TextBox ID="txtStyleDescription" runat="server" ReadOnly="true"></asp:TextBox>
</td>
</tr>
<asp:Repeater ID="rptStyleComponents" runat="server"
onitemdatabound="rptStyleComponents_ItemDataBound"
onitemcreated="rptStyleComponents_ItemCreated"
EnableViewState="True">
<ItemTemplate>
<asp:UpdatePanel ID="upnlComponent" runat="server">
<ContentTemplate>
<tr>
<td>
<asp:Label ID="lblSectionName" runat="server" Text='<%# Eval("SecName")%>' ></asp:Label>
</td>
<td>
<asp:DropDownList ID="ddlDataSelection" runat="server">
</asp:DropDownList>
</td>
</tr>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="ddlDataSelection" />
</Triggers>
</asp:UpdatePanel>
</ItemTemplate>
</asp:Repeater>
</table>
<br />
<table>
<tr>
<td colspan="2">Description Items</td>
</tr>
<tr>
<td colspan="4"></td>
</tr>
<tr>
<td>Garment Type:</td>
<td>
<asp:UpdatePanel ID="upGarment" runat="server" >
<ContentTemplate>
<asp:DropDownList ID="ddlGarmentList" runat="server"
AppendDataBoundItems="True" AutoPostBack="True"
onselectedindexchanged="ddlGarmentList_SelectedIndexChanged">
<asp:ListItem Text = "Select garment" Value = ""></asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ID="sdsGarment" runat="server"
ConnectionString="<%$ ConnectionStrings:IRMSConnectionString %>"
SelectCommand="Select * from Garments"></asp:SqlDataSource>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="ddlGarmentList" />
</Triggers>
</asp:UpdatePanel>
</td>
</tr>
<tr>
<td>Cost Price:</td>
<td>
<asp:TextBox ID="txtCostPrice" runat="server"></asp:TextBox></td>
<td>SRP :</td>
<td><asp:TextBox ID="txtSRP" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td>Quantity :</td>
<td><asp:TextBox ID="TextBox1" runat="server"></asp:TextBox></td>
<td>Week :</td>
<td><asp:TextBox ID="TextBox2" runat="server"></asp:TextBox></td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
Client:
<asp:Repeater ID="Repeater1" runat="server">
<HeaderTemplate>
<table id="Table_car">
<tr>
<th>Pos#</th>
<th>Model</th>
<th>Price</th>
<th>Image</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><%# Eval("Pos#") %></td>
<td><%# Eval("Model") %></td>
<td><%# Eval("Price") %></td>
<td><%# Eval("Image ") %></td>
</tr>
</ItemTemplate>
Server:
protected void Page_Load(object sender, EventArgs e) {
var table = new DataTable();
try
{
using (var conn = new SqlConnection(_connectionString))
{
using (var cmd = new SqlCommand("spFilterByContinent", conn))
{
using (var adapter = new SqlDataAdapter(cmd))
{
cmd.CommandType = CommandType.StoredProcedure;
adapter.Fill(table);
}
}
}
Repeater1.DataSource = table;
Repeater1.DataBind();
}
catch (Exception exception)
{
//TODO: write excepetion
}
}
public void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Header)
{
string header1 = string.Empty;
string header2 = string.Empty;
string header3 = string.Empty;
string header4 = string.Empty;
// Retrieve headers from database and assign to variables
SetHeaderValue(e.Item, "litHeader1", header1);
SetHeaderValue(e.Item, "litHeader2", header2);
SetHeaderValue(e.Item, "litHeader3", header3);
SetHeaderValue(e.Item, "litHeader4", header4);
}
}
private void SetHeaderValue(RepeaterItem item, string litId, string headerText)
{
var lit = item.FindControl(litId) as Literal;
if (lit != null)
lit.Text = headerText;
}
}
I am using a repeater for retrieving data from db,
my question is: How can I retrieve columns headers from db also, not just the data itself?
<# Eval("COLUMN HEADER")%> <---alike
Headers are not databound as the items of a repeater (see this question and its answers for details). But you can adjust the headers in the ItemCreated event of the Repeater. First, you'd need to place some literal controls in the headers and add a handler for the ItemCreated event:
<asp:Repeater ID="Repeater1" runat="server" OnItemCreated="Repeater1_ItemCreated">
<HeaderTemplate>
<table id="Table_car">
<tr>
<th><asp:Literal ID="litHeader1" runat="server" /></th>
<th><asp:Literal ID="litHeader2" runat="server" /></th>
<th><asp:Literal ID="litHeader3" runat="server" /></th>
<th><asp:Literal ID="litHeader4" runat="server" /></th>
</tr>
</HeaderTemplate>
</HeaderTemplate>
<!-- ... -->
</asp:Repeater>
Then you'd need to implement the event handler in the code behind file. Based on your question, this sample assumes that you want to use the column names of the data table that is assigned as the DataSource of the Repeater:
protected void Repeater1_ItemCreated(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Header)
{
var tbl = (DataTable)((Repeater)sender).DataSource;
SetHeaderValue(e.Item, "litHeader1", tbl, 0);
SetHeaderValue(e.Item, "litHeader2", tbl, 1);
SetHeaderValue(e.Item, "litHeader3", tbl, 2);
SetHeaderValue(e.Item, "litHeader4", tbl, 3);
}
}
private void SetHeaderValue(RepeaterItem item, string litId, DataTable tbl, int colIndex)
{
var lit = item.FindControl(litId) as Literal;
if (lit != null)
{
string headerText =
tbl.Columns.Count > colIndex ? tbl.Columns[colIndex].ColumnName : "Not set";
lit.Text = headerText;
}
}
I want to get values from user control
I tried but loop comes out
Code:
.aspx
<asp:Repeater ID="rpt1" runat="server">
<ItemTemplate>
</ItemTemplate>
</asp:Repeater>
<asp:Button ID="btnSaveVisa" Text="Save" runat="server" OnClick="btnSaveVisa_Click" />
AddVisaUserControl.ascx
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="AddVisaControl.ascx.cs" EnableViewState="false" Inherits="Pyramid.AddVisaControl" %>
<div id="divreg" runat="server">
<table id="tbl" runat="server">
<tr>
<td>
<asp:Label ID="lbl2" runat="server"></asp:Label>
</td>
</tr>
<tr>
<td> Visa Number:</td>
<td><asp:TextBox ID="txtUser" Width="160px" runat="server"/></td>
<td> Country Name:</td>
<td><asp:DropDownList ID="dropCountry" Width="165px" runat="server"></asp:DropDownList></td>
</tr>
<tr>
<td> Type of Visa:</td>
<td><asp:DropDownList ID="dropVisa" Width="165px" runat="server"></asp:DropDownList></td>
<td> Type of Entry:</td>
<td><asp:DropDownList ID="dropEntry" Width="165px" runat="server"></asp:DropDownList></td>
</tr>
<tr>
<td> Expiry Date</td>
<td>
</td>
</tr>
</table>
</div>
.aspx.cs
public void generateControls()
{
for (int i = 0; i < int.Parse(ViewState["ControlCount"].ToString()); i++)
{
Label lbl = new Label();
string count = Convert.ToString(i + 1);
lbl.Text = "Visa" + count;
rpt1.Controls.Add(lbl);
rpt1.Controls.Add(LoadControl("VisaUserControl.ascx"));
rpt1.Controls.Add(new LiteralControl("<BR>"));
}
}
protected void btnAddVisa_Click(object sender, EventArgs e)
{
ViewState["ControlCount"] = int.Parse(ViewState["ControlCount"].ToString()) + 1;
generateControls();
}
//Here is the problem when I read the values from control the loop comes out
private void saveData()
{
for (int i = 0; i < this.rpt1.Controls.Count; i++)
{
if (this.rpt1.Controls[i] is TextBox)
{
TextBox txtserial = (TextBox)this.rpt1.Controls[i];
string value = txtserial.Text;
}
}
}
protected void btnSaveVisa_Click(object sender, EventArgs e)
{
saveData();
}
Any ideas? Thanks in advance
public List<string> NoOfControls
{
get
{
return ViewState["NoOfControls"] == null ? new List<string>() : (List<string>)ViewState["NoOfControls"];
}
set
{
ViewState["NoOfControls"] = value;
}
}
protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);
GenerateControls();
}
private void GenerateControls()
{
foreach (string i in NoOfControls)
{
var ctrl = (AddVisaUserControl)LoadControl(#"AddVisaUserControl.ascx");
ctrl.ID = i;
this.AddVisaPlaceHolder.Controls.Add(ctrl); // Add in placeholder
}
}
//Adding controls to Place Holder
protected void AddButton_Click(object sender, EventArgs e)
{
List<string> temp = null;
var uc = (AddVisaUserControl)this.LoadControl(#"AddVisaUserControl.ascx");
string id = Guid.NewGuid().ToString();
uc.ID = id;
temp = NoOfControls;
temp.Add(id);
NoOfControls = temp;
AddVisaPlaceHolder.Controls.Add(uc);
}
//Save
protected void Save_Click(object sender, EventArgs e)
{
foreach (var control in AddVisaPlaceHolder.Controls)
{
var usercontrol = control as AddVisaUserControl;
//you can access properties from usercontrol
//Implement save logic here
}
}