C# Make a button change a public value - c#

I'm working in VisualStudio.
I have this Form:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Test
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void Form1_Load(object sender, EventArgs e)
{
}
public static int signal = 0;
public void button1_Click(object sender, EventArgs e)
{
}
}
}
And this User Control:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Test
{
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
if (Form1.signal == 1)
{
MessageBox.Show("Signal received!", "Atention!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
private void UserControl1_Load(object sender, EventArgs e)
{
}
}
}
I bust my head to try to display the 'MessageBox' from 'UserControl1' when 'button1' from 'Form1' is clicked. Basically, I want to change the value of 'signal' to 1 when the 'button1' is pressed. I'm newbie but I'm pressed by time here so a good help will be very welcome. Any ideas? Thank you!

The button1_Click is the event that is going to be triggered when you click on the button from the Form.
Either create an event like another user suggested, or refer to this question and create a custom message box with your UserControl as its content.

When your UserControl is loaded it sees Form1.signal as 0 since you initialized it with that value. Your UserControl1 will never be aware of the change on Form1.
What you need to do is make listener function in UserControl1 that will be triggered, let's say every 10milliseconds and that will check if Form1.signal == 1.
Check Interval library for that, and I suggest you find time to learn a bit of C#. The language is awesome.

The best way to deal with communication between containers is to implement an observer class
The observer pattern is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods.
(wikipedia)
the way i do this is creating an Observer class:
1 public delegate void dlFuncToBeImplemented(int signal);
2 public static event dlFuncToBeImplemented OnFuncToBeImplemented;
3 public static void FuncToBeImplemented(int signal)
4 {
5 OnFuncToBeImplemented(signal);
6 }
so basically: first line says that there would be a function that somebody else will implement
second line is creating an event that occur when the delegated function will call
and the third line is the creation of the function that calls the event
so in your UserControl you should add a function like this:
private void ObserverRegister()//will contain all observer function registration
{
Observer.OnFuncToBeImplemented += Observer_OnFuncToBeImplemented;
/*and more observer function registration............*/
}
void Observer_OnFuncToBeImplemented(int signal)//the function that will occur when FuncToBeImplemented(signal) will call
{
MessageBox.Show("Signal received!", "Atention!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
and in your Form you should do something like:
public static int signal = 0;
public void button1_Click(object sender, EventArgs e)
{
Observer.FuncToBeImplemented(signal);//will call the event in the user control
}
and now, you can register this function to a whole bunch of other controls and containers and they will all get the signal
I hope this would help :)

Related

Copying a contex into clipboard C#

I found this code in stackOF but it doesn't work at all and i can't fix that.
would you tell me what's wrong with this code?
using System.Windows.Forms;
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Button1_Click(object sender, EventArgs e)
{
Clipboard.SetText(textBox1.Text);
}
}
}
i think your problem because you named your program with same name of class that copy text to clipboard
take look at this code
using System.Windows.Forms;
namespace Clipboard
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//Clipboard.SetText(textBox1.Text); This will not work if you named your namespace Clipboard !
System.Windows.Forms.Clipboard.SetText(textBox1.Text); // you should use this way to confirm you need to access to clipboard not your namespace
}
}
}
i named my program with same name of class(Clipboard)
and i have problem now because the compiler confusing between your program and class that copy a text
So the best way is to specify a unique name each time you create a program :)
There is a namespace conflict with your own. You can either explicitly use the exact Clipboard.SetText() method using the full declaration as per #WaleedKhaled's answer:
System.Windows.Forms.Clipboard.SetText(textBox1.Text);
or else the using statement at the top of your example to say something like:
using WinForms = System.Windows.Forms;
then your line would read:
WinForms.Clipboard.SetText(textBox1.Text);

Why can't i use a method from another class

I am putting together an application but I'm getting a strange issue where i can't use any methods from a class i've created with a couple of methods, the methods don't do anything at the moment because I'm just getting the shell of the program in place. I am trying to call from the Form1 class below, specifically from a button click checking a specific operation from radio buttons.
If btnDeviceControlAccept_Click is clicked it checks which of the radio buttons and goes to a method in the DeviceControlMethods class such as Add, Change or Delete VLAN. When i use the object (dc, DeviceControlMethods dc = new DeviceControlMethods();)I created in the Form1 i'm unable to use the methods even if the class is public or if i set the methods to static and use DeviceControlMethods.AddVlan etc.
I'm sure I'm just doing something daft because I've not doing C# in quite a while.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace MFT___Configurator
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void groupBox1_Enter(object sender, EventArgs e)
{
}
private void btnDeviceControlAccept_Click(object sender, EventArgs e)
{
DeviceControlMethods dc = new DeviceControlMethods();
if (rbAddDevice.Checked == true)
{
dc.CreateVlan() // the method is not found
resutlBox.Clear();
}
else if (rbChange.Checked == true)
{
resutlBox.Clear();
}
else if (rbDelete.Checked == true)
{
resutlBox.Clear();
}
else
{
resutlBox.Clear();
resutlBox.Text = "Select a valid operation; Add, Change or Delete.";
}
}
Class with the methods i want to call;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MFT___Configurator
{
public class DeviceControlMethods
{
static DeviceControlMethods()
{
string CreateVlan()
{
Console.WriteLine("ggg");
return "";
}
string ChangeVlan()
{
return "";
}
void DeleteVlan()
{
}
}
}
}
I see only private methods, you need to make them public explicitly, not only the class. See the docs about access modifiers
public
The type or member can be accessed by any other code in the same assembly or another assembly that references it.
private
The type or member can be accessed only by code in the same class or struct.
protected
The type or member can be accessed only by code in the same class, or in a class that is derived from that class.
internal
The type or member can be accessed by any code in the same assembly, but not from another assembly.
protected internal
The type or member can be accessed by any code in the assembly in which it is declared, or from within a derived class in another assembly.
private protected
The type or member can be accessed only within its declaring assembly, by code in the same class or in a type that is derived from that class.
Edit
And, as other comments state as well, methods defined in the static constructor won't be accessible either.
You have scoping issues with your class. Read through this article to learn more about scoping in C#. https://msdn.microsoft.com/en-us/library/ms973875.aspx
But to solve your issue, change your class to be as follows:
public class DeviceControlMethods
{
public string CreateVlan()
{
Console.WriteLine("ggg");
return "";
}
public string ChangeVlan()
{
return "";
}
public void DeleteVlan()
{
}
}

c# Add listView items from another form [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am trying to add items in a listView from an antoher form but I don't no how I can do that. I have try this but it gives an error.
Form1
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Local_Host
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
_Form1 = this;
}
public static Form1 _Form1;
public void AddItem(object value)
{
listView1.Items.Add(value);
}
}
}
Form2
private void button1_Click(object sender, EventArgs e)
{
Form1._Form1.AddItem(textBox1.Text); //error
}
The error is in the function
public void AddItem(object value)
{
listView1.Items.Add(value);
}
you pass an object to this function and try to add it to the ListViewItemCollection, but there is no overload of the Add method of the ListViewItemCollection that accepts an object
Change it to
public void AddItem(string value)
{
listView1.Items.Add(value);
}
This will solve the immediate compilation problem, but you will have hard time working with that static variable. If your plan were to pass values from form2 to form1 it is better that you keep the created instance of form1 and use it to pass values through the AddItem method otherwise you will end to add that values to other instances of the Form1 (the latter instance created will receive the new string)
Instead pass the textbox value to Form1 constructor like
Form2
private void button1_Click(object sender, EventArgs e)
{
Form1 frm = new Form1(textBox1.Text);
frm.show();
}
Then in Form1 add the value to your listview like
public partial class Form1 : Form
{
public Form1(string listview_val)
{
InitializeComponent();
this.listView1.Items.Add(listview_val);
}
}

Call method/class from different file

I'm terribly new so I might be completely off track overall with what I'm trying to do.
I don't really know how to ask the question, my english is a bit rocky.
But I have 2 files one containing this:
frmMain.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
Class1 cls = new Class1();
cls.Visibility();
}
}
}
And another file containing this:
Class1.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WindowsFormsApplication1
{
public partial class Class1
{
public void Visibility()
{
frmMain c = new frmMain();
c.label1.Visible = false;
}
}
}
What I'm trying to get is that when I'm running the program and clicking label1 I want it to disappear.
But it doesn't. I don't get any errors or anything.
Any help is appreciated :).
Thanks in advance.
First: Why are you trying to let the label on your mainform dissappear by using another class?
I would suggest the following:
private void label1_Click(object sender, EventArgs e)
{
label1.Visible = false;
}
I think the reason why your code isn't working is that inside the function Visibility() of Class1 you are creating a new frmMain and on that frmMain you are setting the visible property of label1 to false. So you are actually working with a different form.
You are instantiating a new, separate form. This means the label is being hidden.. but on a hidden form you have created.
You need to pass the current form instance into your other class:
public void Visibility(frmMain mainForm) {
mainForm.label1.Visible = false;
}
Then call it like this:
new Class1().Visibility(this);
What you're doing is you're creating a second instance of your window (which might not be obvious to you, as you're not displaying it). Then you are hiding the label in your second window. Probably not what you intended in the first place.
What you need to do is to pass a reference to your original form to the method you're calling, or (depending what you want to do) a reference to the control you need to hide:
in Class1:
public void Visibility(Control controlToHide)
{
controlToHide.Visible = false;
}
in frmMain.cs
new Class1.Visibility(this.label1)
few more comments:
Naming: do not use names like Class1, label1; I appreciate this is probably
just 'play around with' kind of code, but such names are completely
unreadable when you try to come back to your code later (or get
someone else to have a look)
Naming 2: try to name your methods to describe what they will do - HideControl, or HideLabel is much better than Visiblity
You may want to read some basic C# tutorials to learn about references, instances, parameters, etc.
Other than that, happy C#-ing :)
You do not want to let Class1 know about frmMain. Change it to something like this:
public class Class1
{
public bool GetVisibility()
{
return false;
}
}
And from your form, call it like this:
private void label1_Click(object sender, EventArgs e)
{
Class1 cls = new Class1();
this.Label1.Visible = cls.GetVisibility();
}
Your current implementation of Class1 initializes a new frmMain, hides that form's Label1, does not do anything with that instance (e.g. it does not Show() it) and then returns, not affecting the already instantiated and shown frmMain instance (the one you instantiate Class1 from).
You can change this by passing the label or even the form into Class1, but that is just bad design.
You may change your code this way:
public partial class FrmMain : Form
{
public frmMain()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
new Class1().Visibility(this);
}
public void Go()
{
this.label1.Visible = false;
}
}
Then
public partial class Class1
{
public void Visibility(FrmMain form)
{
form.Go();
}
}
You are setting the visibility of the label of another form (one that's not being displayed.
this line of code in the Visibility method creates a new object
frmMain c = new frmMain();
It's of the same type as the form being display, but it's a different object, that's not displayed. If you insert a line after the above
c.Show();
you should see the newly created form and also see that the label disappears
However there's a straight forward fix to your problem. Change the event handler to this
private void label1_Click(object sender, EventArgs e)
{
((Label)sender).Visible = false;
}
The sender object is the control that was clicked, and since the event is attached to the label it self. All you need to do is cast the sender to the type of a Label and then you can access the visible property. Alternatively you could do this:
private void label1_Click(object sender, EventArgs e)
{
this.label1.Visible = false;
}
That uses the current object (aka this) and gets the label from that object.

Issues displaying a second form C#

I have some issues displaying a second form after clicking a specific button in my first form. The question might sound silly, but I am a newbie to programming...
I have added a new Windows form into my project (Form2), but still, when I use
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.VisualBasic.ApplicationServices;
namespace WindowsFormsApplication1
{
public partial class Form2 : Form
{
public Report()
{
InitializeComponent();
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 Report = new Form2();
Report.Show()
}
}
}
I get the following error
Error 1 The type or namespace name 'Form2' could not be found (are you missing a using directive or an assembly reference?)
d:\Projects C#\The Bizzy D\The Bizzy D\Form1.cs 661 13 The Bizzy D
What am I doing wrong then? Any ideas would be appreciated. Thanks!
You forgot a using directive as the error message states. The problem is, that even if you created this second form, the connection between the type name Form2 and the file it contains isn't clear to C#.
Check if your Form1 and Form2 are in the same namespace.
If you Want To Open Form2 On Form1 Button Click Event.
Follow the Below Steps:
Right Click on Project.
Add->Windows Form...
Enter the Form Name : Form2.cs
Write the following Button Click Event Code in Form1.
private void btnShowForm2_Click(object sender, EventArgs e)
{
new Form2().Show();
}

Categories

Resources