I have a repeater control, and I want to put an unknown number of <asp:Hyperlink>s into the template, for example if you start with this:
<asp:Repeater runat="server" ID="PetsRepeater">
<ItemTemplate>
<%#DataBinder.Eval(Container.DataItem, "Owner")%>
<%#this.ListPets(Container.DataItem)%>
</ItemTemplate>
</asp:Repeater>
and in code behind:
public partial class test1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
PetOwner p = new PetOwner() {
Owner = "Jimmy",
PetNames = new List<String>() { "Nemo", "Dory" }
};
List<PetOwner> PetOwners = new List<PetOwner>() { p };
PetsRepeater.DataSource = PetOwners;
PetsRepeater.DataBind();
}
}
protected String ListPets(Object PetOwner)
{
StringBuilder sb = new StringBuilder();
foreach (String Name in ((PetOwner)PetOwner).PetNames)
{
if (sb.Length > 0) sb.Append(", ");
sb.Append(Name);
}
return sb.ToString();
}
}
class PetOwner
{
public String Owner;
public List<String> PetNames;
}
Now suppose instead of having the string "Nemo, Dory" in my repeater, I want something like this:
<asp:HyperLink runat=server Text="Nemo" NavigateUrl="Pet.aspx?Name=Nemo" />,
<asp:HyperLink runat=server Text="Dory" NavigateUrl="Pet.aspx?Name=Dory" />
How can I do that? I tried putting a foreach inline in the aspx page, but I get the error Invalid expression term 'foreach'.
If you need to have an asp:Hyperlink control, and not just a simple tag, you should use a nested repeater.
http://msdn.microsoft.com/en-us/library/aa478959.aspx
Related
I have the following class (UCNewWorkFlow) which calls a cache database and retrieves rows and adds it to a string array:
public partial class UCNewWorkflow : System.Web.UI.Page
{
private string Connectioncacha = "";
public UCNewWorkflow()
{
int temp;
if (IsItWorkDay(DateTime.Now))
{
temp = 21;
}
else
{
temp = 17;
}
try
{
CacheConnection CacheConnect = new CacheConnection();
CacheConnect.ConnectionString = Connectioncacha;
CacheConnect.Open();
String SQLtext = #"";
DataTable table = new DataTable();
CacheCommand Command = new CacheCommand(SQLtext, CacheConnect);
CacheDataReader Reader = Command.ExecuteReader();
string[] inArr = new string[4];
int k = 0;
if (Reader.HasRows)
{
while (Reader.Read())
{
inArr[k] = Reader["NotYetSeen"].ToString();
returnTime(Convert.ToInt32(inArr[k]));
k++;
}
}
}
catch (Exception ce)
{
}
}
public string returnTime(int inHowMany)
{
string strTime = "";
double future = 0;
DateTime dt = DateTime.Now;
if (inHowMany / 2.0 <= 1)
{
strTime = "15 mins";
}
else if (inHowMany == 0)
{
strTime = "<15 mins";
}
else if (inHowMany / 2.0 > 1)
{
future = Math.Ceiling((inHowMany / 2.0)) * 15;
DateTime tempdate = dt.AddMinutes(future);
TimeSpan result = tempdate - DateTime.Now;
strTime = ToReadableString(result);
}
return strTime;
}
}
The result of the SQL query:
I have the following labels in my ASP.net page:
<asp:Label ID="lblFirstRow" runat="server" Text="Label"></asp:Label>
<asp:Label ID="lblSecondRow" runat="server" Text="Label"></asp:Label>
<asp:Label ID="lblThirdRow" runat="server" Text="Label"></asp:Label>
<asp:Label ID="lblFourthRow" runat="server" Text="Label"></asp:Label>
The code-behind for the ASP.net page:
protected void Page_Load(object sender, EventArgs e)
{
UCNewWorkflow uc = new UCNewWorkflow();
}
At the moment, I can't access the label from the class file.
How can I modify the code so, I have to call the class once and it will populate all four labels.
You are trying to perform this database query during the page's constructor, so it is too early in the ASP.NET Web Forms page lifecycle to have access to those arrays. Those labels do not exist when your constructor is called; they are created during the page initialization event.
As NicoTek suggested, using the Page_Load event handler is a good way of updating these labels. However, if you do it his way, I do not see a reason why your class is inheriting from System.Web.UI.Page, I would recommend refactoring your code so that this and any other database operations exist in another class. This will allow you to reuse code and prevent clutter and repetition in your code-behind files.
It looks to me that you want to return the string array inArr as a property of your UCNewWorkflow class and then bind this to a repeater on the Page_Load of your code-behind as suggested by #NicoTek.
Your Repeater definition on the code-in-front should contain just one Label definition and then as data is bound to the Repeater a new instance of the label is created for each element in your string array.
More details on repeaters can be found at
http://www.w3schools.com/aspnet/aspnet_repeater.asp
you could do
protected void Page_Load(object sender, EventArgs e)
{
UCNewWorkflow uc = new UCNewWorkflow();
lblFirstRow.Text = "someString"
}
I am trying to get my HTML method below, to encode the string and display it on label, but I keep getting a blank page, on the client-side.
I have checked the viewsource and it shows no HTML output their also.
public partial class About : Page
{
protected void Page_Load(object sender, EventArgs e, string data)
{
if (!IsPostBack)
{
string a = createXMLPub(data);
// Label1.Text = HttpUtility.HtmlEncode(a);
Label1.Text = Server.HtmlEncode(a);
}
}
public static string createXMLPub(string data )
{
XElement xeRoot = new XElement("pub");
XElement xeName = new XElement("name", "###");
xeRoot.Add(xeName);
XElement xeCategory = new XElement("category", "#####");
xeRoot.Add(xeCategory);
XDocument xDoc = new XDocument(xeRoot);
data = xDoc.ToString();
return data;
}
HTML
<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</asp:Content>
Please advice, to where I may be going wrong with this code. Many thanks
Your Page_Load isn't fired - re: the extra string data param doesn't match the signature for the event delegate
So:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string a = createXMLPub();
Label1.Text = Server.HtmlEncode(a);
}
}
public static string createXMLPub()
{
XElement xeRoot = new XElement("pub");
XElement xeName = new XElement("name", "###");
xeRoot.Add(xeName);
XElement xeCategory = new XElement("category", "#####");
xeRoot.Add(xeCategory);
XDocument xDoc = new XDocument(xeRoot);
return xDoc.ToString();
}
Hth...
I'm working on a website where there will be embedded a lot of YouTube videos. I want to make it a little easier to embed them into the articles of the page.
When writing this:
[youtube]SOMETHING[/youtube]
the page should automatically create this:
<iframe src="//www.youtube.com/embed/SOMETHING"
frameborder="0" allowfullscreen></iframe>
So - how do I do that? I've been searching around but haven't been able to find a right solution. Please throw your examples in ASP.NET / C#.
Creating shortcodes in ASP.NET is easy as a custom solution. Before you output your article do
String html = "[YOUTUBE]Something[\\YOUTUBE]";
String replacementHtml = "<iframe src=\"//www.youtube.com/embed/$1\" frameborder=\"0\" allowfullscreen></iframe>";
Regex shortcodeRegex = new Regex(#"\[YOUTUBE\]([^\[\\]+)\[\\YOUTUBE\]");
String result = shortcodeRegex.Replace(html, replacementHtml);
Take note of the $1 in the replacementHtml. This is what is replaced by what is internal to the match.
Then output the result to the page.
Wordpress style short code application. It replaces the value [short code /] in the content coming from the database or in the variable in the variable with the user control content.
App_Code--> modul_islemler.cs
public class modul_islemler
{
public static string modul_olustur(string data){
string aranan = #"\[(.*?)\/\]";
Regex objRegex = new Regex(aranan);
MatchCollection objCol = objRegex.Matches(data);
foreach (Match item in objCol)
{data = data.Replace(item.Groups[0].Value, modul_yaz(item.Groups[1].Value.ToString()));
}
return data;
}
public static string modul_yaz(string sayfa)
{
string[] ayir = sayfa.Split(' ');
ArrayList myAL = new ArrayList();
foreach (string a in ayir)
{
myAL.Add(a);
}
if (myAL.Count < 2) myAL.Add("");
return LoadControl("~/plugins/" + myAL[0] + "/" + myAL[0] + ".ascx");
}
public static string LoadControl(string UserControlPath)
{
FormlessPage page = new FormlessPage();
page.EnableViewState = false;
// Create instance of the user control
UserControl userControl = (UserControl)page.LoadControl(UserControlPath);
page.Controls.Add(userControl);
//Write the control Html to text writer
StringWriter textWriter = new StringWriter();
//execute page on server
HttpContext.Current.Server.Execute(page, textWriter, false);
// Clean up code and return html
return textWriter.ToString();
}
public class FormlessPage : Page
{
public override void VerifyRenderingInServerForm(Control control)
{
}
}
page.aspx
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<div class="detail">
<div class="container">
<asp:Literal ID="icerikLtrl" runat="server"></asp:Literal>
</div>
</div>
</asp:Content>
page.aspx.cs --> [slide_plugins /] shortcodes
public partial class page : System.Web.UI.Page
{
protected void Page_Init(object sender, EventArgs e)
{
string txt="<div>blala [slide_plugins /] blabla</div>";
icerikLtrl.Text = modul_islemler.modul_olustur(txt);
}
plugins/slide_plugins/slide_plugins.ascx
<asp:TextBox runat="server" ID="Txt1"></asp:TextBox>
<asp:Button runat="server" ID="btn1" OnClick="btn1_Click" Text="Submit"></asp:Button>
plugins/slide_plugins/slide_plugins.ascx.cs
protected override void OnLoad(EventArgs e)
{
//kontrol yüklendiğinde çalışacak kodlar
base.OnLoad(e);
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
InitializeComponent();
}
private void InitializeComponent()
{
btn1.Click += new EventHandler(btn1_Click);
}
protected void btn1_Click(object sender, EventArgs e)// not working....
{
Txt1.Text = "Example"; // not working....
}
This is what i use to handle youtube shortcodes
<Extension> Public Function ConvertYouTubeShortCode(text As String) As String
Dim regex__1 As String = "\[youtube:.*?\]"
Dim matches As MatchCollection = Regex.Matches(text, regex__1)
If matches.Count = 0 Then
Return text
End If
Dim width As Int32 = 620
Dim height As Int32 = 349
Dim BaseURL As String = "http://www.youtube.com/v/"
For i As Integer = 0 To matches.Count - 1
Dim length As Int32 = "[youtube:".Length
Dim mediaFile As String = matches(i).Value.Substring(length, matches(i).Value.Length - length - 1)
Dim player As String = "<div class=""video-container""><iframe width=""{2}"" height=""{3}"" src=""{4}{1}"" frameborder=""0"" allowfullscreen></iframe></div>"
Return text.Replace(matches(i).Value, [String].Format(player, i, mediaFile, width, height, BaseURL))
Next
End Function
I have a TabContainer in my aspx page as follows
<asp:TabContainer ID="tabcontainer" runat="server" ActiveTabIndex="0">
</asp:TabContainer>
am creating the tabs for the above containter using C# code on Oninit event of the page
protected override void OnInit(EventArgs e)
{
lstCategories = Service.GetCategories();
numberOfCategories = lstCategories.Count;
CreateTabs();
base.OnInit(e);
}
protected void CreateTabs()
{
try
{
for (int i = 0; i < numberOfCategories; i++)
{
TabPanel asptab = new TabPanel();
asptab.ID = lstCategories[i].Id.ToString();
asptab.HeaderText = lstCategories[i].Name;
MyCustomTemplate obj = new MyCustomTemplate(lstCategories[i].Id);
asptab.ContentTemplate = obj;
tabcontainer.Tabs.Add(asptab);
}
}
catch (Exception ex)
{
}
}
public class MyCustomTemplate : ITemplate
{
public Table tbl;
public TextBox tbxQuantity;
public Image img;
public int countOfItemsPerRow = 2;
public MyCustomTemplate(int paramCategoryID)
{
categoryID = paramCategoryID;
}
public void InstantiateIn(Control container)
{
InitialiseTheProperties();
container.Controls.Add(tblHardware);
}
public Table InitialiseTheProperties()
{
//Intialize the Mater Table
tbl = new Table();
//Create Row for the mater Table
TableRow row = new TableRow();
TableCell cell = new TableCell();
img = new Image();
img.ImageUrl = HttpRuntime.AppDomainAppVirtualPath +"/Images/"+"1.jpg";
cell.Controls.Add(img);
tblHardware.Rows.cells.add(cell);
tbxQuantity = new TextBox();
tbxQuantity.ID ="TbxQuantity";
cell.Controls.Add(tbxQuantity);
tblHardware.Rows.cells.add(cell);
tblHardware.Rows.Add(row);
//return tbl;
}
}
}
now am trying to this on a btnclickevent
public void btnSave_Click(object sender, EventArgs e)
{
try
{
Control cntrl = Page.FindControl("TbxQuantity");
}
catch (Exception ex)
{
}
}
it just returns null. Am i doing something wrong? Kindly Help
As i found the answer to the above question posted by myself, I would like to help fellow folks who encounter the same or similar problem.
string strQuantity=((System.Web.UI.WebControls.TextBox)(((AjaxControlToolkit.TabContainer)(BTN.Parent.FindControl("tabcontainer"))).Tabs[0].FindControl("TbxQuantity"))).Text
Thank you "Stackoverflow" for maintaining the site and I also thank the members who help developers like me.
Your issue isn't with the dynamically added controls, but that the FindControl method doesn't propogate and check all the way down the children stack.
I made a quick helper method below that checks the children until it finds the right control. It was a quick build, so it probably can be improved upon, I haven't tried but you could probably extend the control so you don't have to pass in an initial control. I tested it, however for some reason I couldn't get it to work passing in the Page object, I had to pass in the initial panel I used, but it should get the point across.
Control Finder
public static class ControlFinder
{
public static Control Find(Control currentControl, string controlName)
{
if (currentControl.HasControls() == false) { return null; }
else
{
Control ReturnControl = currentControl.FindControl(controlName);
if (ReturnControl != null) { return ReturnControl; }
else
{
foreach (Control ctrl in currentControl.Controls)
{
ReturnControl = Find(ctrl, controlName);
if (ReturnControl != null) { break; }
}
}
return ReturnControl;
}
}
}
HTML Page
<asp:Panel ID="pnl1" runat="server">
<asp:TextBox ID="pnl1_txt1" runat="server" />
<asp:TextBox ID="pnl1_txt2" runat="server" />
<asp:Panel ID="pnl2" runat="server">
<asp:TextBox ID="pnl2_txt1" runat="server" />
<asp:TextBox ID="pnl2_txt2" runat="server" />
<asp:Panel ID="pnl3" runat="server">
<asp:TextBox ID="pnl3_txt1" runat="server" />
<asp:TextBox ID="pnl3_txt2" runat="server" />
</asp:Panel>
</asp:Panel>
</asp:Panel>
<asp:Button ID="btnGo" Text="Go" OnClick="btnGo_Click" runat="server" />
<asp:Panel ID="pnlResults" runat="server">
<div>pnl1_txt1: <asp:Label ID="lblpnl1txt1" runat="server" /></div>
<div>pnl1_txt2: <asp:Label ID="lblpnl1txt2" runat="server" /></div>
<div>pnl2_txt1: <asp:Label ID="lblpnl2txt1" runat="server" /></div>
<div>pnl2_txt2: <asp:Label ID="lblpnl2txt2" runat="server" /></div>
<div>pnl3_txt1: <asp:Label ID="lblpnl3txt1" runat="server" /></div>
<div>pnl3_txt2: <asp:Label ID="lblpnl3txt2" runat="server" /></div>
<div>unknown: <asp:Label ID="lblUnknown" runat="server" /></div>
</asp:Panel>
Button Click event
protected void btnGo_Click(object sender, EventArgs e)
{
Control p1t1 = ControlFinder.Find(pnl1, "pnl1_txt1");
Control p1t2 = ControlFinder.Find(pnl1, "pnl1_txt2");
Control p2t1 = ControlFinder.Find(pnl1, "pnl2_txt1");
Control p2t2 = ControlFinder.Find(pnl1, "pnl2_txt2");
Control p3t1 = ControlFinder.Find(pnl1, "pnl3_txt1");
Control p3t2 = ControlFinder.Find(pnl1, "pnl3_txt2");
Control doesntexist = ControlFinder.Find(pnl1, "asdasd");
lblpnl1txt1.Text = p1t1 != null ? "Found: " + p1t1.ID : "Not found";
lblpnl1txt2.Text = p1t2 != null ? "Found: " + p1t2.ID : "Not found";
lblpnl2txt1.Text = p2t1 != null ? "Found: " + p2t1.ID : "Not found";
lblpnl2txt2.Text = p2t2 != null ? "Found: " + p2t2.ID : "Not found";
lblpnl3txt1.Text = p3t1 != null ? "Found: " + p3t1.ID : "Not found";
lblpnl3txt2.Text = p3t2 != null ? "Found: " + p3t2.ID : "Not found";
lblUnknown.Text = doesntexist != null ? "Found: " + doesntexist.ID : "Not found";
}
I have two repeaters on my page. The first repeater has a LinkButton in it, with a commandname and commandarguement. When the linkbutton is clicked the value of commandarguement is supposed to be stored in a Session containing List. Then I use the value of Session List to bind the second repeater.
I am having two problems:
1) I am binding the second repeater in the OnInit event. The event handler that is executed when the LinkButton in the first repeater is executed AFTER the init event - therefore when data binding takes place the new value has not been added to the session yet. I can't bind the data any later than the init event because the controls within the second repeater need to be maintained using viewstate (or other).
2) In the second repeater there are two dropdownlists. Both are databound in the repeaters itemdatabound event. When the first DDL is changed, I need to filter the values in the second DDL. But this just isnt happening.
For the purposes of a clearer example, I have stripped the code out of my application and created a very simple aspx page - all of the code is below. Thanks to Bobby who has already helped with this.
Really hope someone can help as I am stumped!
Markup:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Repeater-Viewstate.aspx.cs" Inherits="test_Repeater_Viewstate" ViewStateMode="Enabled" %>
<!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>
<h1>Repeater Test</h1>
<h2>Repeater 1</h2>
<asp:Repeater runat="server" Visible="true" ID="rptListItems">
<ItemTemplate>
Image ID: <asp:Literal ID="ImageID" runat="server" />
<asp:LinkButton runat="server" CommandName="SelectImage" Text="Add to list" ID="AddToListCommand" />
<hr />
</ItemTemplate>
</asp:Repeater>
<h2>Repeater 2</h2>
<asp:Repeater runat="server" Visible="true" ID="rptSelectedItems" ViewStateMode="Enabled">
<ItemTemplate>
The value of the item you selected is: <asp:TextBox runat="server" ID="ImageIDInput"/>
<asp:DropDownList runat="server" ID="OptionsInput" AppendDataBoundItems="true" AutoPostBack="true" >
<asp:ListItem Text="Please choose..." Value="0" />
</asp:DropDownList>
<asp:DropDownList runat="server" ID="AttributesInput" runat="server" AppendDataBoundItems="true">
<asp:ListItem Text="Please choose..." Value="0" />
</asp:DropDownList>
<hr style="clear: both;" />
</ItemTemplate>
</asp:Repeater>
<asp:Button runat="server" Text="Postback" />
</div>
</form>
</body>
</html>
Code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class test_Repeater_Viewstate : System.Web.UI.Page
{
//DUMMY Data for 1st Repeater
public class MyRepeaterDataSource {
public int ID { get; set; }
public string Title { get; set; }
}
private List<MyRepeaterDataSource> _items;
public List<MyRepeaterDataSource> Items {
get {
if (_items == null)
_items = new List<MyRepeaterDataSource>();
return _items;
}
set {
_items = value;
}
}
//END dummy data
//DUMMY data for 1st dropdownlist in second repeater
public class FirstDDLClass {
public int ID { get; set; }
public string Title { get; set; }
}
private List<FirstDDLClass> _firstDDLItems;
public List<FirstDDLClass> FirstDDLItems {
get {
if (_firstDDLItems == null)
_firstDDLItems = new List<FirstDDLClass>();
return _firstDDLItems;
}
set {
_firstDDLItems = value;
}
}
//DUMMY data for 2nd dropdownlist in second repeater
public class SecondDDLClass {
public int ID { get; set; }
public int ForeignKey { get; set; }
public string Title { get; set; }
}
private List<SecondDDLClass> _secondDDLItems;
public List<SecondDDLClass> SecondDDLItems {
get {
if (_secondDDLItems == null)
_secondDDLItems = new List<SecondDDLClass>();
return _secondDDLItems;
}
set {
_secondDDLItems = value;
}
}
public List<string> SelectedItems {
get {
if (Session["SelectedItems"] == null)
Session["SelectedItems"] = new List<string>();
return (List<string>)(Session["SelectedItems"]);
}
set {
Session["SelectedItems"] = value;
}
}
protected override void OnInit(EventArgs e) {
//register events
this.rptListItems.ItemDataBound += new RepeaterItemEventHandler(rptListItems_ItemDataBound);
this.rptListItems.ItemCommand += new RepeaterCommandEventHandler(rptListItems_ItemCommand);
this.rptSelectedItems.ItemDataBound += new RepeaterItemEventHandler(rptSelectedItems_ItemDataBound);
//create a dummy list to populate first repeater
MyRepeaterDataSource dataSource1 = new MyRepeaterDataSource();
dataSource1.ID = 1;
dataSource1.Title = "Item 1";
Items.Add(dataSource1);
MyRepeaterDataSource dataSource2 = new MyRepeaterDataSource();
dataSource2.ID = 2;
dataSource2.Title = "Item 2";
Items.Add(dataSource2);
MyRepeaterDataSource dataSource3 = new MyRepeaterDataSource();
dataSource3.ID = 3;
dataSource3.Title = "Item 3";
Items.Add(dataSource3);
MyRepeaterDataSource dataSource4 = new MyRepeaterDataSource();
dataSource4.ID = 4;
dataSource4.Title = "Item 4";
Items.Add(dataSource4);
//create a dummy list to populate the first dropdownlist in the second repeater
FirstDDLClass class1 = new FirstDDLClass();
class1.ID = 1;
class1.Title = "Option 1";
FirstDDLItems.Add(class1);
FirstDDLClass class2 = new FirstDDLClass();
class2.ID = 2;
class2.Title = "Option 2";
FirstDDLItems.Add(class2);
//create a dummy list to populate the second dropdownlist in the second repeater
SecondDDLClass class3 = new SecondDDLClass();
class3.ID = 1;
class3.ForeignKey = 1;
class3.Title = "Attribute 1";
SecondDDLItems.Add(class3);
SecondDDLClass class4 = new SecondDDLClass();
class4.ID = 1;
class4.ForeignKey = 1;
class4.Title = "Attribute 2";
SecondDDLItems.Add(class4);
SecondDDLClass class5 = new SecondDDLClass();
class5.ID = 1;
class5.ForeignKey = 2;
class5.Title = "Attribute 3";
SecondDDLItems.Add(class5);
if (!this.Page.IsPostBack) {
//bind 1st repeater
this.rptListItems.DataSource = Items;
this.rptListItems.DataBind();
}
//bind second repeater
this.rptSelectedItems.DataSource = SelectedItems;
this.rptSelectedItems.DataBind();
base.OnInit(e);
}
protected void Page_Load(object sender, EventArgs e)
{
}
void rptListItems_ItemDataBound(object sender, RepeaterItemEventArgs e) {
Literal imageIDLiteral = e.Item.FindControl("ImageID") as Literal;
if (imageIDLiteral is Literal) {
imageIDLiteral.Text = DataBinder.Eval(e.Item.DataItem, "ID").ToString();
}
LinkButton linkButton = e.Item.FindControl("AddToListCommand") as LinkButton;
if (linkButton is LinkButton) {
linkButton.CommandArgument = DataBinder.Eval(e.Item.DataItem, "ID").ToString();
}
}
void rptListItems_ItemCommand(object source, RepeaterCommandEventArgs e) {
switch (e.CommandName) {
case "SelectImage":
this.SelectedItems.Add(e.CommandArgument.ToString());
break;
}
}
void rptSelectedItems_ItemDataBound(object sender, RepeaterItemEventArgs e) {
switch (e.Item.ItemType) {
case ListItemType.AlternatingItem:
case ListItemType.Item:
TextBox textBox = e.Item.FindControl("ImageIDInput") as TextBox;
if (textBox is TextBox) {
textBox.Text = e.Item.DataItem.ToString();
}
DropDownList ddl1 = e.Item.FindControl("OptionsInput") as DropDownList;
if (ddl1 is DropDownList) {
ddl1.DataValueField = "ID";
ddl1.DataTextField = "Title";
ddl1.DataSource = this.FirstDDLItems;
ddl1.DataBind();
}
DropDownList ddl2 = e.Item.FindControl("AttributesInput") as DropDownList;
if (ddl2 is DropDownList) {
ddl2.DataValueField = "ID";
ddl2.DataTextField = "Title";
if (ddl1.SelectedIndex != 0) {
ddl2.DataSource = this.SecondDDLItems.Where(f => f.ForeignKey == Convert.ToInt32(ddl1.SelectedValue));
ddl2.DataBind();
}
}
break;
}
}
}
Thanks in advance guys
Al
If you add the following code:
protected void OptionsInput_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList optionsInput = sender as DropDownList;
DropDownList ddl2 = optionsInput.Parent.FindControl("AttributesInput") as DropDownList;
if (ddl2 is DropDownList)
{
ddl2.DataValueField = "ID";
ddl2.DataTextField = "Title";
if (optionsInput.SelectedIndex != 0)
{
ddl2.DataSource = this.SecondDDLItems.Where(f => f.ForeignKey == Convert.ToInt32(optionsInput.SelectedValue));
ddl2.DataBind();
}
}
}
And the following markup:
<asp:DropDownList runat="server" ID="OptionsInput" AppendDataBoundItems="true" AutoPostBack="true" OnSelectedIndexChanged="OptionsInput_SelectedIndexChanged" >
(Specifically, adding the OnSelectedIndexChanged="OptionsInput_SelectedIndexChanged")
It worked for me.