Access placeholders in a loop - c#

I need to create the names of my placeholders dynamically in a loop in C# but I don't know how i can get the right name.
The placeholders are set in the aspx page and with currMaxValues is the max. number of Placeholders set.
My current markup:
const int currMaxValues = 6;
for (int i = 0; i < currMaxValues; i ++)
{
//new placeholdernames
string currPlaceholderTime = "placeholderTime" + i;
string currPlaceholderMore = "placeholderZusatz" + i;
string currPlaceholderIco = "placeholderIco" + i;
string currPlaceholderTemp = "placeholderTemp" + i;
//elements for placeholders
Label time = null;
Label more = null;
Image img = null;
Label temp = null;
//built the stuff for the placeholders
DateTime currTime = DateTime.Now;
int hour = currTime.Hour;
time.Text = hour.ToString();
//(PlaceHolder)currPlaceholderTime.Controls.add(time);
}
Is it possible to use the name of the Placholder that I created at the beginning of the loop to access the controls?
Thanks for any help!

You have to use FindControl function to find a control with dynamic id as below
FindControl("controlname")
In your case you need to change the code as below
for (int i = 0; i < currMaxValues; i ++)
{
//new placeholdernames
string currPlaceholderTime = "placeholderTime" + i;
string currPlaceholderMore = "placeholderZusatz" + i;
string currPlaceholderIco = "placeholderIco" + i;
string currPlaceholderTemp = "placeholderTemp" + i;
//elements for placeholders
Label time = null;
Label more = null;
Image img = null;
Label temp = null;
//built the stuff for the placeholders
DateTime currTime = DateTime.Now;
int hour = currTime.Hour;
time.Text = hour.ToString();
Placeholder placeHolderTime = FindControl(currPlaceholderTime) as PlaceHolder;
placeHolderTime.Controls.Add(time);
//(PlaceHolder)currPlaceholderTime.Controls.add(time);
}
However note that, the above code works only if your page not under master page or the placeholders are directly under the main page.
If you are not able find with the above code, you need to have a function like below, to find the control hierarchically.
private Control FindControl(Control rootControl, string controlID)
{
if (rootControl.ID == controlID) return rootControl;
foreach (Control controlToSearch in rootControl.Controls)
{
Control controlToReturn =
FindControl(controlToSearch, controlID);
if (controlToReturn != null) return controlToReturn;
}
return null;
}
Then you can call the above function using the following code to find the placeholders
Placeholder placeHolderTime = FindControl(this,currPlaceholderTime) as PlaceHolder;

Related

Access an object through its name as a string c#

I try to find out, how it is possible to access an object through a string which has the same name as the object name.
for example, I want to change the property of n times of Buttons using for loop
public static object GetObject(string ObjectName)
{
// this Method has to return an Object through his name
}
for (int i = 1; i < 4; i++)
{
GetObject(Convert.ToString("Button" +i) ).Text = Convert.ToString(i);
}
}
}
this code has the same function of this code
Button1.Text = "1";
Button2.Text = "2";
Button3.Text = "3";
You can develop different types of applications using C#. i.e. Web, WinForms, WPF. They have different types of Control and Type. I'm assuming that you are developing a WinForms application. In that case, you can use the Controls property of a WinForm to access all the Controls of a Form.
Please check the below code block for the implementation:
public object GetObject(string ObjectName)
{
// this Method has to return an Object through his name
Control myControl = Controls.Find(ObjectName, true).FirstOrDefault();
if (myControl != null)
{
// Do Stuff
return myControl;
}
else return null;
}
private void RenameButtons()
{
for (int i = 1; i < 4; i++)
{
//GetObject(Convert.ToString("Button" + i)).Text = Convert.ToString(i);
object btn = GetObject(Convert.ToString("Button" + i));
if (btn != null) ((Button)btn).Text = Convert.ToString(i);
}
}
You will find more details about the Controls property by following this link.
you can try this
foreach (Control control in Controls)
{
var btn = control as Button;
if ( btn != null && btn.Name.StartsWith("Button") )
{
var i= btn.Name.Substring(6, 1)
//if( i.Convert.ToInt32() <4 ) //optional
btn.Text = i;
}
}

How to edit a control content in an array inside of a list

I got the following:
List<TextBox[]> ListMonths = new List<TextBox[]>();
I use it for store the same textboxes for each month, I fill it like this
for (int i = 0; i <= 11; i++)
{
......
TextBox[] TBaux = new TextBox[18];
for (int o = 0; o <= 17; o++)
{
TBaux[o] = (TextBox)element.FindName("TB" + o + i);
}
ListMonths.Add(TBaux);
}
So that way I got the textboxes for each month in ListMonths.
How can I modify the Text property of one of the textbox (for instance textbox[2]) that is stored in one of the month lists (for instance ListMonths[1])?
ListMonths[1][2].Text = "blabla";
Which is the same as doing:
TextBox[] textBoxes = ListMonths[1];
TextBox textBox = textBoxes[2];
textBox.Text = "blabla";

AvalonEdit: Getting Syntax Highlighted Text

I'm registering syntax highlighting with AvalonEdit with:
PythonPrompt.SyntaxHighlighting = pythonHighlighting;
Text can then be input by the user throughout the course of the program. Is there a way to take the formatted text and move it to a TextBlock without loosing the formatting?
As this formatted text will not be edited again I presume it is more efficient to create a TextBlock rather than creating a TextEditor on the fly.
I managed to get something that works. Its based off the latest code for AvalonEdit (HighlightedLine and RichTextModel)
TextBlock Item = new TextBlock();
Code = Code.Replace("\t", new String(' ', Editor.Options.IndentationSize));
TextDocument Document = new TextDocument(Code);
IHighlightingDefinition HighlightDefinition = Editor.SyntaxHighlighting;
IHighlighter Highlighter = new DocumentHighlighter(Document, HighlightDefinition.MainRuleSet);
int LineCount = Document.LineCount;
for (int LineNumber = 1; LineNumber <= Document.LineCount; LineNumber++)
{
HighlightedLine Line = Highlighter.HighlightLine(LineNumber);
string LineText = Document.GetText(Line.DocumentLine);
int Offset = Line.DocumentLine.Offset;
int SectionCount = Line.Sections.Count;
for (int SectionNumber = 0; SectionNumber < SectionCount; SectionNumber++)
{
HighlightedSection Section = Line.Sections[SectionNumber];
//Deal with previous text
if (Section.Offset > Offset)
{
Item.Inlines.Add(
new Run(Document.GetText(Offset, Section.Offset - Offset))
);
}
Run RunItem = new Run(Document.GetText(Section));
if (RunItem.Foreground != null)
{
RunItem.Foreground = Section.Color.Foreground.GetBrush(null);
}
if (Section.Color.FontWeight != null)
{
RunItem.FontWeight = Section.Color.FontWeight.Value;
}
Item.Inlines.Add(RunItem);
Offset = Section.Offset + Section.Length;
}
//Deal with stuff at end of line
int LineEnd = Line.DocumentLine.Offset + LineText.Length;
if (LineEnd > Offset)
{
Item.Inlines.Add(
new Run(Document.GetText(Offset, LineEnd-Offset))
);
}
//If not last line add a new line
if (LineNumber < LineCount)
{
Item.Inlines.Add(new Run("\n"));
}
}

HTML elements in C#

HtmlAnchor[] anchorToConvert = new HtmlAnchor[]{
clickHere,
leavePage};
Button[] buttonToConvert = new Button[]{
login,
register};
i = 0;
for (i = 0; i < anchorToConvert.Length; i++)
{
DataRow[] result = ds.Tables[0].Select("htmlControl LIKE '" + anchorToConvert[i].ID.ToString() + "'");
if (result.Length > 0)
{
anchorToConvert[i].InnerHtml = result[0]["phrase"].ToString();
}
}
i = 0;
for (i = 0; i < buttonToConvert.Length; i++)
{
DataRow[] result = ds.Tables[0].Select("htmlControl LIKE '" + buttonToConvert[i].ID.ToString() + "'");
if (result.Length > 0)
{
buttonToConvert[i].Text = result[0]["phrase"].ToString();
}
}
I have two arrays of html elements i need to loop through, and use the elements id attribute to select content from a database. Rather than having to create two arrays and loop through them individually, is there someway i can make a more generic array that can contain both buttons and anchors?
You could use a list and check the type of the control in the list when you're looping through:
List<Control> ctrl = new List<Control>();
HtmlAnchor anchor = new HtmlAnchor();
anchor.ID = "myAnchor";
ctrl.Add(anchor);
Button btn = new Button();
btn.ID = "MyBtn";
ctrl.Add(btn);
foreach (Control c in ctrl.ToList())
{
if (c is Button)
{
// Do Something
}
}
Both HtmlAnchor and Button inherit from Web.UI.Control (though not directly).
If that is the type of the array, both of these types (HtmlAnchor and Button) can be assign to the array.

How to dynamically set a control using variables C#

How do you dynamically call a control and set it property at runtime?
// Declare and set queue servers
string[] queueservers = new string[] { "SERVER1", "SERVER2", "SERVER3", "SERVER4" };
int y;
for (y = 0; y <= queueservers.Length - 1; y++)
{
string queueanswer = GetMailQueueSize(queueservers[y]);
if (queueanswer == "alarm")
{
phxQueueImg + queueservers + .ImageUrl = "~/images/Small-Down.gif";
}
else
{
phxQueueImg + queueservers + .ImageUrl = "~/images/Small-Up.gif";
}
queueanswer = "";
}
See here about asking good questions .
I'm going to assume you pasted the wrong code since it doesn't seem to have anything to do with the question afaik. Plus could edit your question and tag if this is winform, wpf or web?
Here I dynamically create the control at runtime:
Textbox c = new Textbox();
Set its text, eg
string s = "Please paste code that relates to your question";
c.Text = s;
Or here I dynamically set my textbox controls property using variables:
propertyInfo = c.GetType().GetProperty(property);
if (propertyInfo != null)
{
propertyInfo.SetValue(c, value, null);
}
try FindControl("controlID") and then cast the result of this call to the required control type and set the needed property.
(SomeParentControl.FindControl("IDOfControlToFind") AS LinkButton).PostBackUrl = "~/someresource.aspx";

Categories

Resources