I've seen a lot of chatter on this topic. Though the examples and desired outcomes are always very specific and specialized. Any direction on this is appreciated.
In my Code: I am dynamically generated image and image URL.And add this image control in panel.I want to Put Image url in argument of temp() but i dont understand how can i do this
<td align="center" colspan="2" style="height: 200px; ">
<asp:Panel ID="Panel_pic1" runat="server">
</asp:Panel>
</td>
Code Behind:
var lasToThirteenthUploaded = ds.Tables["title"].Rows[ds.Tables["title"].Rows.Count - 13]["id"].ToString();
int ID13 = Convert.ToInt16(lasToThirteenthUploaded);//row.Field<int>("video_id");
Image img13 = new Image();
img13.ID = "image" + ID13;
string title13 = ds.Tables["title"].Rows[ds.Tables["title"].Rows.Count - 13]["title"].ToString();//row.Field<string>("title");
img13.ImageUrl = ds.Tables["title"].Rows[ds.Tables["title"].Rows.Count - 13]["path"].ToString();// ("image_path");
Panel_pic13.Controls.Add(img13);
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
if (Session["Name"] == null)
{
}
else
{
temp();
}
}
protected void temp()
{
}
Pass value from here
else
{
temp(img13.ImageUrl);
}
and grab it in
void temp(string imageurl)
{
}
you could use protected void temp(string imageurl) also
Related
I have the following repeater wrapped in an Update Panel
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="DropDownList1" EventName="SelectedIndexChanged" />
</Triggers>
<ContentTemplate>
<asp:Repeater ID="skillTable" runat="server">
<ItemTemplate>
<table class="table table-hover">
<tr>
<td>
<asp:ImageButton runat="server" AutoPostBack="True" ID="skillButton" OnClick="skillButton_Click" CommandArgument="<%# Eval(DropDownList1.SelectedValue)%>" class="addText btn btn-success" ImageUrl="~/img/addbut.png" /></td>
<td><asp:Label runat="server" id="skillName" Text='<%# DataBinder.Eval(Container.DataItem, DropDownList1.SelectedValue) %>'></asp:Label></td>
</tr>
</table>
</ItemTemplate>
</asp:Repeater>
</ContentTemplate>
</asp:UpdatePanel>
It kicks out the information from my database perfectly, and it has a button right before the text in each row.
The problem that i have is that I need each button on each row to, when clicked, add the specific line of code in that row to a textbox.
foreach (RepeaterItem item in skillTable.Items)
{
string skill = item.DataItem.ToString();
string text = skillList.Text;
if (!string.IsNullOrEmpty(text))
{
if (!text.Contains(skill))
{
text += " | " + skill;
skillList.Text = text;
}
}
else
{
text = skill;
skillList.Text = text;
}
}
UpdatePanel2.Update();
I have also tried this way,
protected void skillTable_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
int d = 0;
if(DropDownList1.SelectedValue == "Business and Finance")
{
d = 1;
}
else if(DropDownList1.SelectedValue == "Computers and Technology")
{
d = 2;
}
else if (DropDownList1.SelectedValue == "Education")
{
d = 3;
}
else if (DropDownList1.SelectedValue == "Customer Service")
{
d = 4;
}
DataRowView drv = (DataRowView)e.Item.DataItem;
string skill = drv[d].ToString();
Session["Table"] = skill;
}
protected void skillButton_Click(object sender, System.Web.UI.ImageClickEventArgs e)
{
string skill = (string)(Session["Table"]);
string text = skillList.Text;
if (!string.IsNullOrEmpty(text))
{
if (!text.Contains(skill))
{
text += " | " + skill;
skillList.Text = text;
}
}
else
{
text = skill;
skillList.Text = text;
}
UpdatePanel2.Update();
}
but neither one of them seems to work correctly. Any advice? I havent really used repeaters before this, so If there is any other tool that would work better, I'm open for suggestions.
Thanks in advance!
So I figured it out. What I was missing was a way for my site to specifically narrow down what i needed. I added the code blow to my click method and got rid of the ItemDataBound method and it worked like a charm.
Button button = (sender as Button);
string commandArgument = button.CommandArgument;
RepeaterItem item = button.NamingContainer as RepeaterItem;
var workText = (Label)item.FindControl("workName1") as Label;
string work = workText.Text;
string text = workDetails1.Text;
if (text == " ")
text = "";
if (text == "")
{
if (!text.Contains(work))
{
text +="\u2022 " + work;
workDetails1.Text = text;
}
}
else if (!string.IsNullOrEmpty(work))
{
if (!text.Contains(work))
{
text += "\n\u2022 " + work;
workDetails1.Text = text;
}
else
{
workDetails1.Text = text;
}
}
UpdatePanel4.Update();
Hope this helps someone!
I have a somewhat complicated setup for an ASP.NET TextBox. It is inside of a user control that's inside a repeater that's inside a repeater.
I am able to load text into the TextBox and also get TextChanged to fire when text is changed to anything EXCEPT FOR blank/empty. The event doesn't fire when the user clears out the TextBox.
Does anyone know why ASP.NET might discriminate between text and blank?
I made a simplified version of my problem to separate it from possible other factors. I get the same results.
Below is my aspx markup:
<div>
<asp:Repeater runat="server" ID="rptRepeat" EnableViewState="False">
<ItemTemplate>
<asp:repeater runat="server" ID="rptChild" EnableViewState="False">
<ItemTemplate>
<uc:Things runat="server" ID="ucChild"></uc:Things>
</ItemTemplate>
</asp:repeater>
</ItemTemplate>
</asp:Repeater>
</div>
<asp:Button runat="server" ID="btnBtn" Text="click"/>
Below is my user control markup
<asp:TextBox runat="server" ID="txtText"></asp:TextBox>
Below is the aspx code behind
private List<List<TestObj>> data = null;
protected void Page_Init(object sender, EventArgs e)
{
this.rptRepeat.ItemCreated += rptRepeat_ItemCreated;
this.rptRepeat.ItemDataBound += rptRepeat_ItemDataBound;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
Session["data"] = data = new List<List<TestObj>>();
for (var x = 0; x < 5; x++)
{
data.Add(new List<TestObj>());
for (var y = 0; y < 5; y++)
{
data[0].Add(new TestObj
{
Text = x + "_" + y
});
}
}
}
else
{
data = (List<List<TestObj>>)Session["data"];
}
this.rptRepeat.DataSource = data;
this.rptRepeat.DataBind();
}
void rptRepeat_ItemCreated(object sender, RepeaterItemEventArgs e)
{
var rptChild = (Repeater)e.Item.FindControl("rptChild");
rptChild.ItemDataBound += rptChild_ItemDataBound;
}
void rptRepeat_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
var rptChild = (Repeater)e.Item.FindControl("rptChild");
var rowObj = (List<TestObj>)e.Item.DataItem;
rptChild.DataSource = rowObj;
rptChild.DataBind();
}
void rptChild_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
var ucChild = (WebUserControl1)e.Item.FindControl("ucChild");
var rowObj = (TestObj)e.Item.DataItem;
ucChild.data = rowObj;
}
Below is the user control code behind
public TestObj data = null;
protected void Page_Init(object sender, EventArgs e)
{
this.txtText.TextChanged += txtText_TextChanged;
}
protected void Page_PreRender(object sender, EventArgs e)
{
this.txtText.Text = data.Text;
}
void txtText_TextChanged(object sender, EventArgs e)
{
data.Text = this.txtText.Text;
}
You can download the whole project at https://www.dropbox.com/s/p6zkqqsw71fvuyw/textchangetest.zip?dl=0 if you want to try tinkering with stuff to get me an answer.
The databinding of the repeater was intentionally put in Page_Load because otherwise child controls' events don't fire.
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 WebBrowser in Windows Forms project. It navigates all links in a table element. It is working fine; however it uses break inside a loop. How to achieve this functionality without break statement?
Note: In my real scenario, all the links will redirect to a login page if we give a Navigate command with that link. So, storing all urls and doing a Navigate afterwards will not work for me, in my actual scenario.
C# Code
public partial class Form1 : Form
{
string websiteUrl = #"C:\Samples_L\MyTableTest.html";
List<string> visitedUrls = new List<string>();
string currentUrl = String.Empty;
private void ExerciseApp(object sender, EventArgs e)
{
Thread.Sleep(1000);
if (currentUrl != websiteUrl)
{
currentUrl = websiteUrl;
wb.Navigate(websiteUrl);
}
HtmlElement tableElement = wb.Document.GetElementById("four-grid");
if (tableElement != null)
{
foreach (HtmlElement e1 in tableElement.All)
{
string x = e1.TagName;
String idStr = e1.GetAttribute("id");
if (!String.IsNullOrWhiteSpace(idStr))
{
if (idStr.Contains("catalogEntry_img"))
{
string url = e1.GetAttribute("href");
if (!visitedUrls.Contains(url))
{
currentUrl = url;
visitedUrls.Add(url);
e1.InvokeMember("Click");
//Use break when the first match is found
break;
}
}
}
}
}
}
private System.Windows.Forms.WebBrowser wb = null;
private Button button1 = null;
private ListBox listBox1 = null;
public Form1()
{
// button1
button1 = new Button();
button1.Location = new Point(20, 430);
button1.Size = new Size(90, 23);
button1.Text = "Load and Test";
button1.Click += new EventHandler(this.button1_Click);
// listBox1
listBox1 = new ListBox();
listBox1.Location = new Point(10, 460);
listBox1.Size = new Size(460, 200);
// Web Browser
wb = new WebBrowser();
wb.Location = new Point(10, 10);
wb.Size = new Size(1000, 400);
//Subscribing for the Document Completed Event
wb.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(ExerciseApp);
// Form1
this.Text = "Web Browser Test";
this.Size = new Size(5000, 7100);
this.Controls.Add(wb);
this.Controls.Add(button1);
this.Controls.Add(listBox1);
currentUrl = websiteUrl;
}
private void button1_Click(object sender, EventArgs e)
{
listBox1.Items.Add("Loading Web app under test into WebBrowser control");
wb.Url = new Uri(websiteUrl);
}
}
HTML Used
<html>
<head>
<style type="text/css">
table {
border: 2px solid blue;
}
td {
border: 1px solid teal;
}
</style>
</head>
<body>
<table id="four-grid">
<tr>
<td>
<a href="https://stackoverflow.com/users/696627/lijo" id="catalogEntry_img63664" class="itemhover"
onfocus="showPopupButton('category_63664');"
onkeydown="shiftTabHidePopupButton('category_63664',event);">
<img src="ssss"
alt="G" width="70" />
</a>
</td>
<td>
<a href="http://msdn.microsoft.com/en-US/#fbid=zgGLygxrE84" id="catalogEntry_img63665" class="itemhover"
onfocus="showPopupButton('category_63665');"
onkeydown="shiftTabHidePopupButton('category_63665',event);">
<img src="ssss"
alt="Y" width="70" />
</a>
</td>
</tr>
<tr>
<td>
<a href="https://www.wikipedia.org/" id="catalogEntry_img63666" class="itemhover"
onfocus="showPopupButton('category_63666');"
onkeydown="shiftTabHidePopupButton('category_63666',event);">
<img src="ssss"
alt="B" width="70" />
</a>
</td>
<td>
<a href="http://www.keralatourism.org/" id="catalogEntry_img63667" class="itemhover"
onfocus="showPopupButton('category_63667');"
onkeydown="shiftTabHidePopupButton('category_63667',event);">
<img src="ssss"
alt="A" width="70" />
</a>
</td>
</tr>
</table>
</body>
</html>
Reference
Next using LINQ approach
You could refactor it into a query, making the intentions of the code somewhat clearer:
var nextElement = tableElement.All
.Where(element => element.GetAttribute("id") != null &&
element.GetAttribute("id").Contains("catalogEntry_img") &&
!visitedUrls.Contains(element.GetAttribute("href")))
.FirstOrDefault();
if(nextElement != null)
{
visitedUrls.Add(nextElement.GetAttribute("href"));
nextElement.InvokeMember("Click");
currentUrl = nextElement.GetAttribute("href");
}
I'd also suggest changing visitedUrls to a HashSet, rather than a list, as it is a more efficient data structure for simply determining if an item is in a set of items.
If you iterate over a range of values and want to exit as soon as you found one which satisfies a condition, it is common to use break:
foreach(var a in list) {
if(test(a)) {
// use a
break;
}
}
Sometimes it may be undesired and you can just use this:
bool found = false;
foreach(var a in list) {
if(found && test(a)) {
// use a
found = true;
}
}
or even:
bool found = false;
foreach(var a in list) {
if(test(a)) {
if(found) {
// use a
found = true;
}
}
}
The first version can skip iterating once a suitable element is found. The other two variants keep iterating or even checking all elements. In almost all cases this just wastes processing power. But have a look here for a case where you actually might want to use the third variant: http://en.wikipedia.org/wiki/Timing_attack
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";
}