i have a custom control that renders a number of literalcontrols in the createchildcontrols method. as below (there are other lines of literalcontrols being added that i have not uncluded here)
this.Controls.Add(new LiteralControl(string.Format("<input type=\"text\" style=\"display:none\" value=\"{0}\" id=\"{1}\" name=\"{1}\" />", MediaId.ToString(), this.UniqueID)));
i am then trying to validate this textbox via adding the [ValidationProperty("myprop")] at the top of the class.
basically i need to validate against the value entered into the textbox. the myprop property is as follows
public string myprop
{
get
{
Control ctrl = this.FindControl(this.UniqueID);
string txt = ((TextBox)ctrl).Text;
try
{
MediaId = Convert.ToInt32(txt);
}
catch { MediaId = 0; }
return txt;
}
}
unfortunately the findcontrol does not find the textbox at all, i presume because as far as .net is concerned its a literalcontrol, not a textbox at all
now for sure i could change the createchildcontrols to do this
TextBox tb = new TextBox();
tb.Text = this.MediaId.ToString();
tb.ID = this.UniqueID;
this.Controls.Add(tb);
but because of other limitations of what i am doing i would have to change a great deal more stuff in other places..
is there anyway of getting findcontrol to find the textbox rendered inside the literal, or another method?
thanks
nat
unfortunately the findcontrol does not
find the textbox at all, i presume
because as far as .net is concerned
its a literalcontrol, not a textbox at
all
That is correct. You have to use some other control like a textbox.
Related
foreach (Control c in this.Controls)
{
if (c is TextBox && c.Text.Length==0)
{
// [Associatedlabel].ForeColor = System.Drawing.Color.Red;
err = true;
}
instead of [Associatedlabel], I want to associate each textbox to label, so eventually all labels near the textbox that are empty will be red, how it can be done?
Thanks.
There is no fantastic way to find the label control back from the textbox. Using the form's GetChildAtPoint() method is something you can make easily work but are going to regret some day. Naming helps, like FooBarLabel matches FooBarTextBox. Now you can simply use the Controls collection to find the label back:
var label = (Label)this.Controls[box.Name.Replace("TextBox", "Label")];
But Winforms solves many problems by simple inheritance. Add a new class to your project and paste this code:
using System;
using System.Windows.Forms;
class LabeledTextBox : TextBox {
public Label Label { get; set; }
}
Compile and drop the new control from the top of the toolbox. Set the Label property in the designer, just pick it from the dropdown list. Boomshakalaka.
You can first manually set your TextBox's Tag property to these labels. Tag is meant to contain user-defined data, so you can place any object there. Then you can do simply:
foreach (Control c in this.Controls)
{
if (c is TextBox && c.Text.Length==0 && c.Tag is Label)
{
((Label)c.Tag).ForeColor = System.Drawing.Color.Red;
err = true;
}
}
This is the simplest solution, but a few more sophisticated exists though.
Creating a custom composite control consisting of a label, textbox and custom behavior;
Creating a control deriving from a textbox, which stores information about label it is connected with (as Hans Passant suggests)
Creating a Dictionary<TextBox, Label> or Dictionary<Control, Label>, which allows resolving such matters in runtime (variation on Steve's idea).
I suppose that you are using WinForms. In this environment you don't have any built-in functionality that associate a label to a textbox. So you need to build your own association.
This could be done creating a dictionary in the constructor of your code
public class MyForm : Form
{
private Dictionary<string, Label> assoc = new Dictionary<string, Label>();
public MyForm()
{
// Key=Name of the TextBox, Value=Label associated with that textbox
assoc.Add("textbox1", Label1);
assoc.Add("textbox2", Label2);
assoc.Add("textbox3", Label3);
}
}
.....
foreach (TextBox t in this.Controls.OfType<TextBox>())
{
if(t.Text.Length == 0)
{
assoc[t.Name].ForeColor = System.Drawing.Color.Red;
err = true;
}
else
assoc[t.Name].ForeColor = ??? system forecolor ???
}
I have a MasterPage that contains a hidden field control. I want to get the current value of the hidden field and set the value of it from pages that use the MasterPage.
I have the following code so far: (in one of the pages)
//Get the textbox and set it's value
TextBox txt1 = new TextBox();
txt1 = (TextBox)this.Master.FindControl("txtHiddenField");
txt1 .Text = "true";
The above code does not seem to work. What code would I need to get the hidden field control and set it's value? (and get it's value)
I would recommend to provide a public property/method in your MasterPage, that you can use to set/get the HiddenField's value.
in your Master(assuming it's type is called SiteMaster):
public String HiddenValue {
get{return txtHiddenField.Value;}
set{txtHiddenField.Value = value;}
}
In your page:
SiteMaster master = (SiteMaster)Page.Master;
master.HiddenValue = "true";
This approach is straight-forward, less prone to errors and easily readable. You could even change the control in your master without needing to change the pages(f.e. if you want to replace the hidden-field with a TextBox).
Assuming that your "true" value indicates that you actually want to store a boolean, i would recommend to use a bool as data-type for the property and a self-explanatory name. Then you can store it in the hiddenfield but the client(the page) does not need to know.
HiddenField sets its text as VALUE, while TextBox has a TEXT property. Of course casting one to the other and setting text property won't help.
Do this instead:
HiddenField hiddenField = (HiddenField)Master.FindControl("txtHiddenField");
hiddenField.Value = "true";
Assuming you have added hidden field control like this ->>
<input type="hidden" ID="hiddenFieldID" runat="server" />
you can access it like -->>
HtmlInputHidden hiddenfield = (HtmlInputHidden)this.Master.FindControl(
May be you are missing ContentPlaceHolder
Try something like this
ContentPlaceHolder mpContentPlaceHolder;
TextBox mpTextBox;
mpContentPlaceHolder =
(ContentPlaceHolder)Master.FindControl("ContentPlaceHolder1");
if(mpContentPlaceHolder != null)
{
mpTextBox =
(TextBox) mpContentPlaceHolder.FindControl("TextBox1");
if(mpTextBox != null)
{
mpTextBox.Text = "TextBox found!";
}
}
Read more about Reference ASP.NET Master Page Content
I did this in C# -
foreach (Control ctl in this.groupBox3.Controls)
{
if ((ctl is Textbox) && (ctl.Name.Substring(0, 1) != "l"))
{
Textbox tmp= (Textbox)ctl;
tmp.text = "whatever";
Im trying to do something similar in WPF but this time i want to find the textbox based on a string.
So I tried
TextBox temp = (TextBox).Findcontrol("txtboxNumbers");
but it complaints that the "(Textbox)" is a type but its used like a variable and it cant find the Findcontrol method :'(
Ofcource you cannot. Doing this
(TextBox).Findcontrol("txtboxNumbers");
You try to invoke method Findcontrol on Type. Instead try (in window or control *.cs file):
TextBox oTextBox = FindName("txtboxNumbers") as TextBox;
You can find the control with this.FindControl:
TextBox txt = this.FindControl("txtboxNumbers") as TextBox;
// check if the control was found
if(txt != null)
{
txt.Text = "whatever you want";
}
i have the name of a control in a string and I want to manipulate the control, how do i turn the string into the current form instance of that control in c#?
e.g.
string controlName = "Button1";
What goes here?
button1.text = "Changed";
Thanks
Button button1 = (Button)this.Controls[controlName];
You need to look up the control in the controls collections, then cast it to the correct type. Is this in WPF , WinForms or ASP.Net?
Inside the form, you could write (c#)
this.Controls["Button1"].Text = "Changed";
I suppose, this could be the syntax in vb.net
Me.Controls("Button1").Text = "Changed"
EDIT: I don't know, if that would compile. #Binary Worrier is right
Button btn1 = this.Controls["Button1"] as Button;
btn1.Text = "Changed";
I have a dynamically created (runtime creation) textbox whose name is available as a string.What i want to do is access this textbox like we do as normal textboxes .Can any one tell me how to cast it as textbox or any other solution
If you know the name of the textbox and its parent controls, you can do like this:
TextBox tb = (TextBox )parent.Controls["name"];
In addition to Iordan's answer, if you don't know exactly where on your form the textbox is, then this extension method should help alot. Note, Form's inherit from Control somewhere down the track too, so you can call it from that, or any control on your form.
public static class ExtensionMethods
{
public static Control FindControl(this Control root, string name)
{
foreach (Control c in root.Controls)
{
// Check this control
if (c.Name == name) return c;
// Check this controls subcontrols
Control tmp = c.FindControl(name);
if (tmp != null) return tmp;
}
return null;
}
}
If this still isn't flexible enough for you, then you can iterate over System.Windows.Forms.Application.OpenForms
Since you seem to have control over the creation process, put a reference to it in a dictionary.
TextBox txt = DynamicCreate(name);
map[name] = txt;
this.Controls.Add(txt);
All you have to do is look it up in your dictionary, instead of loop through all the controls on the form.
TextBox txt = map["name"];