change label text in usercontrol at run time - c#

hello
i m new to c# and im working on a project,in which i made a usercontrol1 as
*label textbox datepicker*now i wnt to change the label text,i m trying this code but it is not working
using System;
using System.Windows.Forms;
namespace library_system
{
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
}
// private string DateLabel
public string DateLabel
{
**get { return DateLabel.Text; }//error when i write dateLabel.Text
set
{
DateLabel.Text= value;//error datelabel.Text
}**
}
i m using this code in usercontrol for is it right to do this way??
and in the main form i m writing code as
userControl11.DateLabel="From Date";//on for load event??Is this Right
Thanks in advance!!

You are writing a property and setting itself.
If your label name is lbl you could simply use lbl.Text="what you want";
If you need a property to have a stronger check on text, you could write:
public string DateLabel
{
get { return lbl.Text; }
set { lbl.Text = value; }
}
So in main form you could write (suppose you have a control named uc)
uc.DateLabel = "hello";
EDITED
To be clear: suppose you have
one label named lbl in your UserControl1 user control
a UserControl1 control in your main form named uc
In your user control code you can write:
public string DateLabel
{
get { return lbl.Text; }
set { lbl.Text = value; }
}
In your main form you can then write:
uc.DateLabel = "what you want";

Try changing it to this (controlname is id you have given to your label)
public string DateLabel
{
get { return controlname.Text; }
set
{
controlname.Text= value;
}
}

Your Property is Called DateLabel, and you are trying to set it.
That doesnt make sense.
Try the following. You will need to drag a asp:Label onto you usercontrol and call it lblDateLabel.
public string DateLabel
{
get { return lblDateLabel.Text; }
set { lblDateLabel.Text= value; }
}

Related

Setting default size/text of custom control in c#

I am creating a custom control in my C# application in order to add a new property (MyProperty below). It is inheriting from Label. One thing I would like it to do, is display at a particular size when I drag it on to my form (200x132). I'd also like it to display no text. However, no matter how I try to do this, it doesn't seem to work. I am able to set BackColor and BorderStyle with no problem, however. I'm fairly new to C#, so maybe I'm missing something obvious.
Here is my code:
using System.Drawing;
using System.Windows.Forms;
namespace MyProgram
{
public enum MyEnum
{
Value1, Value2, Value3
}
public partial class MyControl : Label
{
public MyControl()
{
BackColor = Color.LightCoral;
BorderStyle = BorderStyle.FixedSingle;
AutoSize = false;
Size = new Size(200, 132);
Text = "";
InitializeComponent();
}
protected override void OnPaint(PaintEventArgs pe)
{
base.OnPaint(pe);
}
private MyEnum myProperty;
public MyEnum MyProperty
{
get { return myProperty; }
set { myPropery = value; }
}
}
}
The answer provided via Dispersia's link has a bug, in my opinion. The text reset should happen once and then whatever a user does after that shouldn't matter. In Dispersia's link you can't actually set the text back to the control name because it will keep blanking it out.
The answer provided by cramopy doesn't technically answer your question, it is a way to do it by using the defaults on a UserControl though. You'll also need to bind the Text property of the UserControl to the label's.
The following should work while inheriting from a Label and will only reset the Text property once.
public partial class MyControl : Label
{
#region fields
private IComponentChangeService _changeService;
private bool canResetText = false;
#endregion
#region properties
protected override Size DefaultSize
{
get { return new Size(200, 132); }
}
[Browsable(false)]
public override bool AutoSize
{
get { return false; }
set { base.AutoSize = false; }
}
public override ISite Site
{
get { return base.Site; }
set
{
base.Site = value;
if (!base.DesignMode)
return;
this._changeService = (IComponentChangeService)base.GetService(typeof(IComponentChangeService));
if (this._changeService != null)
this._changeService.ComponentChanged += new ComponentChangedEventHandler(this.OnComponentChanged);
}
}
#endregion
#region constructors
public MyControl()
{
base.BackColor = Color.LightCoral;
base.BorderStyle = BorderStyle.FixedSingle;
}
#endregion
#region methods
protected override void InitLayout()
{
base.InitLayout();
this.canResetText = true;
}
private void OnComponentChanged(object sender, ComponentChangedEventArgs ce)
{
if (ce.Component != null &&
ce.Component == this &&
ce.Member.Name == "Text" &&
base.DesignMode &&
this.canResetText)
{
((MyControl)ce.Component).Text = string.Empty;
this.canResetText = false;
if (this._changeService != null)
this._changeService.ComponentChanged -= new ComponentChangedEventHandler(this.OnComponentChanged);
}
}
#endregion
}
#Dispersia reply only answers the myControl1 thing. (deleted meanwhile)
Here comes a full guide for solving your problem:
Add a new UserControl named MyLabel
Change the following within Designer Mode:
BorderStyle:= FixedSingle
Size:= 200; 132
Now Drag&Drop a new Label onto the control
Edit those Label values (also within Designer Mode):
AutoSize:= false
BackColor:= LightCoral
Dock:= Fill
Text:= clear/empty this box!! (don't write this inside the box, you really have to clear it!)
TextAlign:= MiddleCenter
Just recompile your project && add a MyLabel control from the Toolbar.
Now it show up as you wanted!!

How do I pass values to user control? [duplicate]

This question already has answers here:
How to pass values to a user control in winforms c#
(2 answers)
Closed 8 years ago.
I have a windows form and I want to pass a value to a user control. I programmatically create the user control in the winform and set a value, but it doesn't get set. Here is the code where I create the user control:
namespace AddPanel
{
public partial class Form1 : Form
{
public Form1()
{
int a = db.CamTable1s.Count();
InitializeComponent();
DisplayImage(a);
}
private void DisplayImage(int rowNum)
{
test nt = new test();
nt.Location = new System.Drawing.Point(33, h);
nt.Name = "test1";
nt.usrID = "username";
nt.Size = new System.Drawing.Size(408, 266);
this.Controls.Add(nt);
}
}
}
I set a variable I made in test user control called nt.Name, then I just want to display it in a text box on the user control. Here is the code for the user control:
namespace AddPanel
{
public partial class test : UserControl
{
public string usrID { get; set; }
public test()
{
InitializeComponent();
//textBox1.Text = usrID;
}
public test(string Id)
{
InitializeComponent();
usrID = Id;
UCtextBox.Text = usrID;
}
}
}
Obviously, I don't know why this isn't working. Could someone help me out?
Even in WPF, where you have bindings, the UI will not automatically pick up a change to a property (without raising PropertyChanged). It definitely won't in the hard-coded land of WinForms.
So you have two problems:
You invoked the default constructor in your call, so no code ever sets the Text property of the textbox
Even if you had set the text, the subsequent change to the property would not propagate to the UI.
The simplest solution would be to just run the UI update in the setter:
private string usrID;
public string UserID //Correct style!
{
get { return usrID; }
set
{
usrID = value;
RCtextBox.Text = usrID;
}
}
You could also call a method from the setter, listen on INotifyPropertyChanged and a number of other things.
Another way would be to expose a method instead of a property:
public string UpdateUserID(string newId)
{
usrID = newId;
RCtextBox.Text = usrID;
}
You should put value passed into usrId property to the textbox.
public partial class test : UserControl
{
public string usrID
{
get{return _usrId;}
set
{
_usrId = value;
UCtextBox.Text = value;
}
}

How to create custom TextBox control?

I want to perform Trim() method on each TexBox control on my page, before value is returned. I dont' want to hard-code the same code for each TexBox control, I want to do it in more elegant way.
I've found made the following class
namespace System.Web.UI.WebControls
{
public partial class TrimmedTextBuox : TextBox
{
private string text;
public override string Text
{
get { return string.IsNullOrEmpty(text) ? text : text.Trim(); }
set { text = value; }
}
}
}
but it fails, while debuggind the compiler doesn't get inside get{} and set{}.
After that, I created a UserControl item, but it must be deriverd from System.Web.UI.UserControl, not System.Web.UI.WebControls.TextBox to get it work (there's an exception which points to that)
So, how can I do that ?
First you have to register your control in your .aspx page like that:
<%# Register TagPrefix="customControls" Namespace="WebApplication.Custom.Controls" Assembly="WebApplication"%>
Then you can call it using the markup
<customControls:TrimmedTextBuox ID="txtTrim" runat="server"/>
Plus you don't have to create another "text" property in your custom TextBox. Instead, it can be done like that:
namespace WebApplication.Custom.Controls
{
public class TrimmedTextBuox : TextBox
{
public override string Text
{
get
{
return base.Text;
}
set
{
if (!String.IsNullOrEmpty(value))
base.Text = value.Trim();
}
}
}
}
This will trim recursively all text boxes before inserting.
public static void trimRecursive(Control root)
{
foreach (Control control in root.Controls)
{
if (control is TextBox)
{
var textbox = control as TextBox;
textbox.Text = textbox.Text.Trim();
}
else
{
trimRecursive(control);
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
trimRecursive(Page);
}
Simple Solution to your problem is to hide the Text property of your base class by using new keyword. sample code...
public class TrimmedTextBox : TextBox
{
public new string Text
{
get
{
var t = (string) GetValue(TextProperty);
return t != null ? t.Trim() : string.Empty;
}
}
}
For more info about how new keyword with property works refrer to this SO Question

Overriding Form.Text property

I'm attempting to override Form.Text in order to modify the Title prior to appearing on the form.
As a proof of concept I created this class, which will be used in place of directly inheriting from Form:
public class FormWithVersionNumber : Form
{
[SettingsBindable(true)]
public override string Text
{
get
{
return "tester";
}
}
}
I would've expected all forms that inherit from this to have the Title "tester" but instead it is always blank. I've been through with breakpoints, and can't see any reason why this should happen. So what is the reason?
Because the actual Title is not retreived from Text but from the internal property WindowText in Control.
Here's an example of how you can do:
public partial class FormWithVersionNumber : Form
{
public override sealed string Text
{
get
{
return base.Text + " 1.0.0.0";
}
set
{
base.Text = value + " 1.0.0.0";
}
}
public FormWithVersionNumber()
{
InitializeComponent();
Text = "Some Title";
}
}

C# Property Grid

I am writing an application which is going to allows users to change the properties of a text box or label and these controls are user controls. Would it be easiest to create a separate class for each user control which implements the properties I want them to be able to change and then bind those back to the user control? Or is there another method I am overlooking?
Create a custom Attribute, and tag the properties you want the user to edit with this attribute. Then set the BrowsableAttribute property on the property grid to a collection containing only your custom attribute:
public class MyForm : Form
{
private PropertyGrid _grid = new PropertyGrid();
public MyForm()
{
this._grid.BrowsableAttributes = new AttributeCollection(new UserEditableAttribute());
this._grid.SelectedObject = new MyControl();
}
}
public class UserEditableAttribute : Attribute
{
}
public class MyControl : UserControl
{
private Label _label = new Label();
private TextBox _textBox = new TextBox();
[UserEditable]
public string Label
{
get
{
return this._label.Text;
}
set
{
this._label.Text = value;
}
}
[UserEditable]
public string Value
{
get
{
return this._textBox.Text;
}
set
{
this._textBox.Text = value;
}
}
}

Categories