How can I change the Title from a Usercontrol in another cs? - c#

I have made a UserControl button named UserControl1, and I am trying to change its title from the templates where I am copying it (much like the easy clock-devise but one little step ahead).
I can not seem to do it. I write this code in the UserControl1, :
public string Display
{
get { return label1.Text; }
set { label1.Text = value; }
}
Then, I write this in the form, within the public class:
UserControl1.Display = "Title";
It shows an error at the "=" sign:
Invalid token '=' in class, struct, or interface member declaration.
I have a feeling im really close, can someone help me out?

I think you have a code like this...
class someClass
{
UserControl1.Display = "Title";
}
You cannot directly put your code inside a class like this, you have to create a method and then write this code inside that. For ex, change your code as below...
class someClass
{
UserControl1 uc = new UserControl1();
public void some_Method()
{
uc.Display = "Title";
}
}

Related

Change text of Button from another form class in C#

I want to modify something in Mission Planner and I want to change button from another class/form in C# in this function :
public void CloseAllConnections()
{
myButton1.Text = "Disconnecting all";
...
}
function that is located in :
namespace MissionPlanner
{
public partial class MainV2 : Form
{
...
}
...
}
the idea is that everything works perfectly when i am focused on that menu, but sometimes i get a error
i even made a function like this
public MyButton GetMyButton1 { get { return myButton1; } }
and also created new instance
var myObject = new MainV2(true);
myObject.myButton1.Text = "Disconnecting all";
nothing works ...
i don't even know where is the function called from, because is clear that is not called from MainV2 class ...
An exception of type 'System.NullReferenceException' occurred in MissionPlanner.exe but was not handled in user code
Any ideas? Thank you.
It appears that your click event form object is called (name) myButton1, and that you are calling the following to change it: myobject.myButton1.Text = "Disconnecting all". Try using myButton1.Text = "Disconnecting all" instead.
You need to grab an instance of the form where the button resides.
Do this by saving a static reference to the form in it's constructor:
namespace MissionPlanner
{
public partial class MainV2 : Form
{
public static MainV2 CurrentForm;
public MainV2()
{
CurrentForm = this;
InitializeComponent();
}
Then somewhere else in your code:
public void CloseAllConnections()
{
MainV2.CurrentForm.myButton1.Text = "Disconnecting all";
...
}
One thing that you could try is to pass the button from the form to the class that will be modifying the button.
public class Example
{
public Button MyButton1 { get; set; }
public Example(Button myButton1)
{
MyButton1 = myButton1;
}
public void CloseAllConnections()
{
MyButton1.Text = "Disconnecting all";
}
}
This should successfully set the button's text on MainV2.
Are you using any sort of multi-threading in your app? if so:
Make sure you either only change the button from the same thread it was created by,
or simply use the ControlInstance.Invoke() method to delegate the change.

How to Typecaste a control and access its properties?

IDE: Visual Studio, C# .net 4.0
I have two identical user control uc1 and uc2 and both are having a textbox called txtbox1
now see this code and textbox1 is public in designer so it is assessable in form1.cs, Form 1 is simple windows form which is having uc1 and uc2.
In form1 see this function which i am calling in onLoad_form1 method.
UserControl currentUC; //Global variable;
public void loadUC(string p1)
{
//Here I want:
if(p1 == "UC1)
{
currentUC = uc1;
}
if(p1 == "UC2)
{
currentUC = uc2;
}
}
Than another function which calls update the textbox1 based on currentUC value
//on load
currentUC.textbox1.text = "UC1 called";
//Here I am getting error "currentUc does not contains definition for textbox1"
If i do:
uc1.textbox1.text = "UC1 text";
uc2.textbox1.text = "UC1 text"; //it works, But based on p1 string variable I want to make control as uc1 or uc2 than I want to access its child control. please suggest how to perform this.
please don't tell if else blocks, because This functionality I have to use in various places.
Thanks.
#Lee Answer: - works just for textbox, but I am having two usercontrols i.e. two different usercontrols not instance of it. UserControlLeft and UserControlRight and both are having same textboxes, listboxes etc (with minor design changes), and I want to access/load this based on some string "left" and "right".
Since the textboxes have the same name you can look them up in the Controls collection:
TextBox tb = (TextBox)currentUC.Controls["textbox1"];
tb.Text = "UC1 called";
a better solution would be to add a property to your user control class which sets the internal text property e.g.
public class MyUserControl : UserControl
{
public string Caption
{
get { return this.textbox1.Text; }
set { this.textbox1.Text = value; }
}
}
I think you're mixing a couple of things here.
First of all, you say that you have 2 exactly the same usercontrols, do you mean the ascx files are the same, or that you have 2 instances of the same usercontrol on the page?
Let's go with all the valid options:
1. To find a control and cast it:
Assume you have the following aspx snippet:
<div>
<uc1:MyCustomUserControl id="myControl" runat="server" />
<uc1:MyCustomUserControl id="myControl2" runat="server" />
</div>
If you now want to access the control, you should do the following:
public void Page_Load()
{
var myControl ((MyCustomUserControl)FindControl("MyControlName"));
// On 'myControl' you can now access all the public properties like your textbox.
}
In WPF you can do it like this:
//on load MAINFORM
public void SetText(string text)
{
CLASSOFYOURCONTROL ctrl = currentUC as CLASSOFYOURCONTROL ;
ctrl.SetText(text);
}
// in your control SUB
public void SetText(string text)
{
textbox1.text = "UC1 called"
}
i think this should work in winforms also. And is more clean than accessing the controls from your sub-control directly
#Lee's method is good. Another method will be to use a public property with a public setter (and textbox doesn't need to be public this way).
or an interface (this way you don't care what class you have at the given moment - and no ifs):
public interface IMyInterface
{
void SetTextBoxText(string text);
}
public partial class UC1: UserControl, IMyInterface
{
public void SetTextBoxText((string text)
{
textBox1.Text=text;
}
//...
}
public partial class UC2: UserControl, IMyInterface
{
public void SetTextBoxText((string text)
{
textBox1.Text=text;
}
//...
}
using the code:
((IMyInterface)instanceOfUC1).SetTextBoxText("My text to set");
((IMyInterface)instanceOfUC2).SetTextBoxText("My text to set");

How to pass value to constructor from xaml?

I want to assign a value right when initializing a new UserControl:
public partial class MyUserControl : UserControl
{
public MyUserControl(int id)
{
InitializeComponent();
//.. do something with id
}
// ...
}
Is it possible to pass a value to constructor (id in my case) from xaml?
<CustomControls:MyUserControl />
(Yes I can define a dependency property or make the control in code behind, but that doesn't help)
Yeah, that's possible. You can create a user control programmatically. Then, you can use any constructor you want. Here's a sample:
Supposing, that we have a usercontrol, that assigns a value to textbox on initialization:
public ControlWithP(int i)
{
InitializeComponent();
tb.Text = i.ToString();
}
Add this control to page:
public SamplePage()
{
InitializeComponent();
ControlWithP cwp = new ControlWithP(1);
this.sp.Children.Add(cwp);
}
where sp is StackPanel control. Same thing with adding user control to Grid.
see the result.
Is this, what you wanted?
From XAML-2009 you could do this with x:Arguments Directive but Windows Phone is using 2006 (for now) so it is not possible.
So to use your control from XAML you need a default contructor (parameterless).
I think you could use a little workaround, by using specially designed property for this:
public partial class MyControl : UserControl
{
private string myValue = "Default";
public string MyValue
{
get { return myValue; }
set
{
myValue = value;
// alternatively you can add some code here which
// will be invoked after control is created
}
}
public MyControl()
{
InitializeComponent();
}
}
then in XAML:
<local:MyControl MyValue="From xaml"/>
Just after the control is created, the property is set and its code invoked - so it can alternatively be used as additional part of code run during creation.
If you want to pass data to your control, better choice would be DependencyProperty - example here.

Access One WindowsForm label to another form in C#

I am using two windows form application, and I want to set 1st form label's value from 2nd form.
But when I access 1st form label in 2nd form then application show this error
Object reference not set to an instance of an object.
I am using this statement to access
login_form.ActiveForm.Controls["label_name"].Text = "Hello World";
sometime i worked fine but some time show this error
Please solve my problem. I will be very thankful to you.
You would be wise to either:
Expose a property in the first form through which you can enact a change to the label text.
Expose a method in the first form that you can call to affect a label text change.
Example #1:
public class Form1 : Form
{
public String LabelText
{
get { return label_name.Text; }
set { label_name.Text = value; }
}
}
//from Form2...
login_form.LabelText = "Hello World";
Example #2:
public class Form1 : Form
{
public void SetLabelText(String TextToSet)
{
label_name.Text = TextToSet;
}
}
//from Form2...
login_form.SetLabelText("Hello World");
I would not advise simply changing the control to be Public. Indirect access is preferable.

Finding controls in WPF ControlTemplate

I have created class that inherits from Window and I am applying control template to it:
public class BaseSearchWindow : Window {
static BaseSearchWindow() {
DefaultStyleKeyProperty.OverrideMetadata(typeof(BaseSearchWindow), new FrameworkPropertyMetadata(typeof(BaseSearchWindow)));
}
public BaseSearchWindow() {
Uri uri = new Uri("/WPFLibs;component/Resources/StyleResources.xaml", UriKind.Relative);
ResourceDictionary Dict = Application.LoadComponent(uri) as ResourceDictionary;
this.Style = Dict["WindowTemplate"] as Style;
}
Than I want to find some control in control template:
public override void OnApplyTemplate() {
RibbonCommand searchCommand = this.Template.FindName("searchCommand", this) as RibbonCommand;
//doesn't work, searchCommand is null
searchCommand.CanExecute += CanExecuteRibbonCommand;
}
But it is allways null.
I tried it in inherited class and it works, but I want it in my base class, so I don't have to search for it every time I use that class.
This works:
public partial class MainWindow : BaseSearchWindow {
public MainWindow() {
InitializeComponent();
RibbonCommand searchCommand = this.Template.FindName("searchCommand", this) as RibbonCommand;
searchCommand.CanExecute += CanExecuteRibbonCommand;
}
Using FindName in OnApplyTemplate is the correct way of doing it; I think it doesn't work because you forgot to call base.OnApplyTemplate().
My bet is that you are looking for a command that doesn't exist (or has a different name) or isn't a RibbonCommand.
That or you didn't specify x:FieldModifier="protected" for the command in xaml.
Actually, I made a mistake. When I try to find controls that are not RibbonCommands it worked, so now I find parent control first and than use VisualTreeHelper to find the RibbonCommand. Sorry about that, I was convinced that it worked only in extended class, but I guess I was too tired when I posted the question. Thank you for your help anyway.

Categories

Resources