Access to a Label on the Form by my Custom control - c#

I have created a WindowsFormControlLibrary porject. It works fine, I can drop it on the forms,call its methods,etc ...
but now as a property of it, I am passing the name of a Label to it. and I want this custom control to be able to use that label name and for example change its font to bold .
so the question is that if I have a WinForm and I have a Label on that form and my custom control on that form, then how can I tell my custom control to do something with that label which I am passing its name to it?

Instead of sending in the name of the label, send in a reference to the actual label and then the custom control can both read the name if it needs to and change the label's font and other properties.
Be careful though, it can quickly get messy to keep track of what's happening if various forms and controls change controls on other forms etc.
Edit: Added code to do what you ask for in the comments
Code isn't tested so it might not be completely correct, but something similar to this should work.
foreach (Control c in Parent.Controls)
{
if (c is Label)
{
Label l = (Label)c;
// do stuff to label l
}       
}

First, if you wish to access a Control from your UserControl, you will need to use the FindForm() method.
Second, you will be required to expose your TextBox control, for example, through a property of your form.
Then, you would need to know the type of this Form returned by this FindForm() method.
Once you know it, you need to type-cast this result to the correct type.
So, here a sample untested pseudo-code to give you the idea:
public partial class MyMainForm {
private TextBox textBox1;
public MyMainForm() {
textBox1 = new Textbox();
textBox1.Name = #"textBox1";
textBox1.Location = new Point(10, 10);
textBox1.Size = new Size(150, 23);
this.Controls.Add(textBox1);
}
public Font MyTextBoxFont {
get {
return textBox1.Font;
} set {
if (value == null) return;
textbox1.Font = value;
}
}
}
Then, assuming you have dropped your control on your form, your UserControl could have a property like so:
public partial class MyUserControl {
private Form GetContainerForm {
get {
return this.FindForm();
}
}
// And later on, where you need to set your TextBox's font:
private void SetContainerInputFieldFont(Font f) {
if (GetContainerForm == null) return; // Or throw, depending on what you need to do.
((MyMainForm)GetContainerForm).MyTextBoxFont = f
}
}

cool :) I just added a get set public property of type Label... it automatically lists all the label on the form.

Related

Can I use Tag property to store it is name?

I am using below method to validate data within textbox in groupbox
so for improvement of user Feedback for example
message text Please enter First Name
where First Name is the label for textbox, so I used Textbox.Tag to store the name of textbox to achieve it since there is no link between the Textbox and it is Label
I search and found that I can use the Tag property to store anything but I wan to be sure of using it by the I told you about
Is there any problem with that ?
public int ValidateData()
{
foreach (Control cont in GB_PatientInfo.Controls)
{
if (cont is TextBox)
{
if (string.IsNullOrWhiteSpace(cont.Text.Trim()))
{
MessageBox.Show("enter data " + cont.Tag, "Message", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, MessageBoxOptions.RtlReading);
cont.BackColor = Color.Red;
cont.Focus();
return -1;
}
}
}
return 1;
}
Thanks
As you have read, you can store any type that derives from object (i.e. everything) in the Control.Tag property so storing the name of a label is fine.
The use of the Tag property does not influence your application. You can store whatever you want in there with no problem.
As it's already mentioned in other answers, it's OK to use Tag property to store any kind of additional information about the control, including a display name.
But have you ever noticed how ToolTip lets you to set ToolTip for your control at design-time?
A ToolTip, ErrorProvider or HelpProvider are examples of extender provider components. They add some properties to the controls at design-time. You also can create such component for DisplayName by implementing IExtenderProvider.
Example
The following code shows you how easily you can create a component called DisplayNameExtender. When you drop an instance of this component on the form, then a new property will be added to design-time of controls, you can set the value to the property
at design-time: DisplayName on diaplayNameExtender1.
Then at run-time, whenever you want to get the value of DisplayName for a control, it's enough to find it this way:
var displayName = displayNameExtender1.GetDisplayName(control);
Here is the code for DisplayNameExtender component:
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
[ProvideProperty("DisplayName", typeof(Control))]
public class DisplayNameExtender : Component, IExtenderProvider
{
private Hashtable displayNameValues = new Hashtable();
public bool CanExtend(object extendee)
{
return (extendee is Control && !(extendee is Form));
}
public string GetDisplayName(Control control)
{
if (displayNameValues.ContainsKey(control))
return (string)displayNameValues[control];
return null;
}
public void SetDisplayName(Control control, string value)
{
if (string.IsNullOrEmpty(value))
displayNameValues.Remove(control);
else
displayNameValues[control] = value;
}
}

Display Message in MDI Parent Status Bar from Child c#

This is simplest possible thing, but I cant update text on status bar. I just started working in c# but cannot find solution. I tried below code:
Mdiparent
public void StutasText(string text)
{
toolStripStatusLabel.Text = text;
}
Child form
MDIParent1 obj = new MDIParent1();
obj.StutasText("Hello world");
obj.Refresh();
Its not showing status text in the status bar.
Where did I go wrong?
In the MDI Parent form, I assume you have toolStripStatusLabel1. If you dont have, you can add this by clicking on the little black arrow in the menuStrip control.
Option 1
In your MDI Parent (let's assume, frmMain is the MDI Parent form) form where you have the StatusStrip, goto frmMain.Designer.cs file and find the place
private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel1;
make this,
public System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel1;
Then from your child pages you can access like below.
ToolStripStatusLabel statusStrip=((frmMain)(frmMdiChild.MdiParent)).toolStripStatusLabel1
Option 2
Declare a public property which will return the toolStripStatusLabel1 control or method where you can set the text property of the toolStripStatusLabel1 in the MDI Parent form. If you return the menuStrip1 itself then you have access to all the properties of that control. If you declare a method, which will set the text property of the toolStripStatusLabel1 then you can only set the text. Decide on what you want, based upon your requirement.
An implementation which returns the menuStrip1 control.
public ToolStripStatusLabel GetStatusBar
{
get
{
return this.toolStripStatusLabel1;
}
}
then from your child pages, you can use,
ToolStripStatusLabel statusStrip=((frmMain)(frmMdiChild.MdiParent)).GetStatusBar;
Option 3
To make it little bit more prettier, you can declare a method in a common class. Then you can reuse this in other child forms.
public void ShowStatusbarMessage(Form frmMdiChild, string message, NotifierType notificationType)
{
ToolStripStatusLabel statusStrip=((frmMain)(frmMdiChild.MdiParent)).GetStatusBar;
statusStrip.Text = message;
if (notificationType == NotifierType.SuccessInfo)
{
statusStrip.ForeColor = System.Drawing.Color.Green;
}
else if (notificationType == NotifierType.Warning)
{
statusStrip.ForeColor = System.Drawing.Color.Orange;
}
else
{
statusStrip.ForeColor = System.Drawing.Color.Red;
}
}
Here, NotifierType is an enum
((mdiMain)MdiParent).toolStripStatusLabel.Text = "My Text";
//but you must change the modifier property of toolStripStatusLabel to public etc
You're creating a new instance of MDIParent1, not using the instance that is shown/the instance your child form belongs to.
You could try using
this.MdiParent
instead of
new MDIParent1()
((frmMDI)this.MdiParent).yourcontrol.yourproperty=yourvalue;
frmMDI is unique name of MDI form.
First
In "mdi parent name".Designer.cs, change the type or member private to public
Second In your code add the next code
(("mdi parent name")MdiParent).toolStripStatusLabel.Text = "your text";

How to loop through all textBox controls and change associated label color

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 ???
}

How to expose a label in a user control with c#

I have made a user control with a pic box and a blank label. How do I expose the label so I can update the text value from my main .net application. I have not written any c# code in about 10 years, and was just thrown a project. All I have for code is:
namespace RHeader1
{
public partial class RHeader : UserControl
{
public RHeader()
{
InitializeComponent();
}
}
}
Please for give my stupidity. I know I need to do a get/set but?????
I presume you mean because controls are not public, the proper way to access them are via a property (which I agree with) - so you can just expose a property which updates the label directly - I'm presuming this is winforms
public string Label
{
get { return label1.Text; }
set { label1.Text = value; }
}
Use this:
Label lbl= (Label)myUserControl.FindName("yourlabelname");
This way you can find and update your label control settled in the UserControl.
You could change the Label's modifier property to public, this will result in the labels properties been visible from the UC's property window and also allow you to do something like
uc.label.Text = "foo";
if you haven't delclared the label:
label1 = new label();
then
label1.text = "some text";
where you can replace "Some text" with any string value.

How to access a dynamically created text box in C# whose name is available in string?

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"];

Categories

Resources