I'm very new to c# and just started to use forms to create a GUI.
Here's some code:
public void Server_connect_button_Click(object sender, EventArgs e)
{
//Open CasparCG server connection and create a TCP client
int port = portnumber;
TcpClient serv1 = new TcpClient("localhost", port);
}
public void Disconnect_server_button_Click(object sender, EventArgs e)
{
serv1.Close();
}
This is code from a couple of button implementations within Form1.cs.
The problem I have is that the serv1 instance in the Disconnect_server button code is not recognised. So the instance is not making it's way out of the Server_connect code. I've tried using the same code (as well as variables and methods) within the Main() code in Program.cs but I'm unable to get any recognition of any of these outside of the same block of code into the button code so I'm clearly overlooking something. I've tried making everything public etc. but it all seems to make no difference. Nothing seems to communicate variables/methods/instances anywhere else in the code.
Please realise I'm a beginner with this language so I'm sometimes getting stuck on this (presumably) basic stuff.
Thanks,
Martin
Issue is Variable Scoping , right now variable scope is upto the method Server_connect_button_Click, you need to increate scope of variable at class level
For providing instance to all you method in given class you can do like this
class Abc {
private TcpClient serv1;
public void Server_connect_button_Click(object sender, EventArgs e)
{
//Open CasparCG server connection and create a TCP client
int port = portnumber;
serv1 = new TcpClient("localhost", port);
}
public void Disconnect_server_button_Click(object sender, EventArgs e)
{
if(serv1!=null)
serv1.Close();
}
}
What I mean to say is you need to declare variable at class level to resolve your issue, the current problem with your code is scope of a variable is up to given method only
Related
I am new to WPF and Coding in general, I am trying to create a small UI to read and write data on .txt files. All the reading part functions works well but now I am having trouble making a small UI to display the information found in the .txt files.
My problem is more with how button clicks work in WPF. All the data is stored in the forms of object of class Static_Data_Scheme and Dynamic_Data_Scheme inside the program, these class are just simple collection of Dictionaries Objects. Part of my data is 'static' meaning it will be stored in .txt files that won't change location and so can be loaded when the program is started, and another part of my data is 'Dynamic' meaning it can be stored anywhere and the file path can be changed using a file explorer in the program. Important thing to note, the Static_Data_Scheme is needed to generate the Dynamic_Data_Scheme.
My initial way of handling it when I made the program to test it out was to generates both Data Scheme with the same button press called load, but since the static dictionaries can be loaded right at the start of the program I want to try and add that method to the MainWindow instead and only have the program generates the Dynamic_Data_Scheme when I press the load button, but I'm unable to find any documentation on how to add arguments to the click method of the button.
Current code that works but that I don't like due to the fact that Static_Data_Scheme.Start method is called each time the load button is pressed and could instead be loaded only once when the program starts :
public MainWindow()
{
InitializeComponent();
}
private void Save_Loader_Click(object sender, RoutedEventArgs e)
{
Static_Data_Scheme static_Data_Scheme = new Static_Data_Scheme();
static_Data_Scheme = static_Data_Scheme.Start();
Dynamic_Data_Scheme dynamic_Data_Scheme = new Dynamic_Data_Scheme();
Save_Parser.Parse_Save(#"file_path", static_Data_Scheme, ref dynamic_Data_Scheme);
}
What I wanna try to achieve is something like that :
public MainWindow()
{
InitializeComponent();
Static_Data_Scheme static_Data_Scheme = new Static_Data_Scheme();
static_Data_Scheme = static_Data_Scheme.Start();
}
private void Save_Loader_Click(object sender, RoutedEventArgs e)
{
Dynamic_Data_Scheme dynamic_Data_Scheme = new Dynamic_Data_Scheme();
Save_Parser.Parse_Save(#"file_path", static_Data_Scheme, ref dynamic_Data_Scheme);
}
But this doesn't work due to the fact that the Save_Parser.Parse_Save method lack the static_Data_Scheme variable and I can't add it to the Save_Loader_Click method either.
So my question is how do I tell my ave_Loader_Click method to get the static_Data_Scheme from the program?
You almost had it, just move the variable outside of your method:
Static_Data_Scheme static_Data_Scheme = new();
public MainWindow()
{
InitializeComponent();
/* static_Data_Scheme = ???? */static_Data_Scheme.Start();
}
private void Save_Loader_Click(object sender, RoutedEventArgs e)
{
var Data_Scheme = new Dynamic_Data_Scheme();
Save_Parser.Parse_Save(#"file_path", static_Data_Scheme, ref dynamic_Data_Scheme);
}
i've run into this pretty tricky problem recently and i hoped somebody could help me.
i have a program that uses trackbars as to display sound volume and it's controlled with an Arduino via serial.
When i try to modify the value (programmaticaly) of the trackar (moving the slider) in any method, it works perfectly with the following code :
trackbar1.Value = ...;
However, when i put this in my serial data handler, it doesn't works :/
I declare the serial data handler this way :
//declaring arduinoCom
public SerialPort arduinoCOM;
//In form1
arduinoCOM.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
my handler looks like this :
public void DataReceivedHandler(
object sender,
SerialDataReceivedEventArgs e)
{
trackBar2.Value = 50;
}
The serial communication works flawlessly, and the handler does it's job no problem.
I've tried for 2 days now and i was able to identify that the only difference between the working trackbar and the not-working one is where the "trackbar1.value" is located. So i've remove the rest of the (i hope) unessecary code for clarity reasons.
So my Question is why does the Trackbar slider doesn't move when i try to modify it's value outside of the "standards method"
additional informations : I've tried runnning the program and then pausing it with visual stuio and the trackbar.Value has been changed successfully, the only thing that isn't working is the graphics side.
I've tested with multiple trackbars, and tried using
trackbar1.Refresh();
it didn't work
Picture of the value of trackbar 1 and 2 as well as picture of all 5 :
Values of trackbars
trackbars not moving
The DataReceived event for SerialPort is raised on a secundary thread (not the UI thread) from which you cannot change UI elements.
Using 'Invoke', you can make the change in the UI thread
Instead of
public void DataReceivedHandler(
object sender,
SerialDataReceivedEventArgs e)
{
trackBar2.Value = 50;
}
use:
public void DataReceivedHandler(
object sender,
SerialDataReceivedEventArgs e)
{
if (trackbBar2.IsHandlecreated) trackBar2.Invoke(new Action(() => trackbar.Value = 50));
}
I found the problem, when i was declaring my serial communication i was using `
Form1 form1 = new Mixer.Form1();
initialiseSerialEventHandler(arduinoCOM);
and instead i should only use
initialiseSerialEventHandler(arduinoCOM);
Let's say I have a thread that waits for a user to click a button before advancing:
System.Threading.AutoResetEvent dialoguePause = new System.Threading.AutoResetEvent(false);
public void AskQuestion()
{
/* buttons containing choices created here */
dialoguePause.WaitOne();
/*Code that handles choice here */
}
public void Choice_Clicked(object sender, EventArgs e)
{
dialoguePause.Set();
}
How can I pass data from the thread Choice_Clicked is on to AskQuestion without relying on class variables? The best I can do is this:
System.Threading.AutoResetEvent dialoguePause = new System.Threading.AutoResetEvent(false);
string mostRecentChoice;
public void AskQuestion()
{
/* buttons containing choices created here */
dialoguePause.WaitOne();
MessageBox.Show("You chose " + mostRecentChoice + ".");
}
public void Choice_Clicked(object sender, EventArgs e)
{
mostRecentChoice = (sender as Button).Content.ToString(); //Ugly!
dialoguePause.Set();
}
There are many ways to achieve this:
Use a property in a Singleton or Monostate. There is always one instance of such property, so regardless which thread writes, and which reads, the will share it, as long as they are in one Application Domain.
Use messaging
If you are in same class, use field or property (look out for cross-threads!)
...
What I am trying to say, it depends on the application. I have no clue if this is WinForm, WPF or Web ...
This question already exists:
Multiple Instances New Class() C#
Closed 9 years ago.
I am using the code sample below -
Program.cs has a list of clients as:
public static List<Client> clients = new List<Client>();
with an event handler for click on button1
private void button1_Click(object sender, EventArgs e)
{
Client client = new Client(combobox1.selecteditem);
Program.clients.Add(client);
}
Client.cs
All variables are non-static and public. There is an eventhandler where on packet receive, a class is called, this class is then filtered and processed
it is called in the following code:
public void recieved(short op, string str, Client c)
{
switch (op)
{
case (short)OpCodes.matches:
{
c.something(c, str);
break;
}
}
}
Handler.cs
public void something(Client c, string movement)
{
if (movement == null)
c.coords = movement;
c.freeSpot = true;
}
And in the above ^ the variables would overlap and freespot would be made true throughout all the instances.
It will work fine with one instance. But I'm trying to compile with multiple instances.
So creating a button_onclick would create a new instance using the above.
As the program is running, it runs flawlessly on one instance, but with 2+ instances, the variables in MyClass start to overlap. Is there a way to prevent this?
I can't say for certain without more context, but this may be a concurrency problem. List is not thread safe. Try using ConcurrentBag<T> instead of List<T>.
I've got a solution with a WPF client, a WCF service and a Silverlight Client (SL 4).
The WPF client works smoothly but the Silverlight is acting up on a point which I'm not sure how to handle it.
These are snippets of the code I have in Silverlight:
using sl_HFClient.svc;
namespace sl_HFClient
{
public partial class MainPage : UserControl
{
svc.IhfsvcClient dataSrv = new svc.IhfsvcClient();
ObservableCollection<svc.ReasonData> reasonData;
}
This is to set everything up, next comes the call to the service:
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
dataSrv.wcGetReasonsCompleted += ReasonsLoaded;
dataSrv.wcGetReasonsAsync();
}
And at last, the code to get the collection and bind it to a combobox:
private void ReasonsLoaded(object sender, wcGetReasonsCompletedEventArgs e)
{
reasonData = e.Result;
}
However, this returns the following error:
Cannot implicitly convert type 'sl_HFClient.svc.ReasonData[]' to 'System.Collections.ObjectModel.ObservableCollection'
I'm quite new to Silverlight and C#, I've done some things with SL4 and VB.NET before and
by comparing this code with a VB.NET project it seems to work.
What am I doing wrong??
//JaggenSWE
Try the following:
private void ReasonsLoaded(object sender, wcGetReasonsCompletedEventArgs e)
{
reasonData = new ObservableCollection<ReasonData>(e.Result);
}
Not entirely sure if this will work in Silverlight, but the solution nonetheless is to explicitly create a new ObservableCollection<ReasonData> instead of trying to implicitly cast from an ReasonData[].