I'm a bit new to C#, and not quite sure how to call a subroutine. Here's what I'm trying to do:
private void button1_Click(object sender, EventArgs e)
{
// Call whatever subroutine you like
StartExstream();
}
public void StartExstream()
{
// Do Stuff Here
}
Unfortunately for me, this doesn't work. I'm getting a "Only assignment, call, increment, decrement, and new object expressions can be used as a statement" error.
How do I call my StartExstream sub from my Button1_Click event?
Thanks,
Jason
EDIT:
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 Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
// Call whatever subroutine you like
StartExstream();
}
public void StartExstream()
{
tcpExstream.Service1Client MyTCP = new tcpExstream.Service1Client();
string ExStreamPath;
string datPath;
string optPath;
// My Working Arguments
ExStreamPath = #"C:\Program Files\Exstream\Dialogue 6.1\Engine.exe";
datPath = #"-FILEMAP=DataFile,\\Dev-srv1\Exstream\LetterWriterApp\Input Files\Data Files\SAVEezkazivaftf40s452ndayb45.dat";
optPath = #"-CONTROLFILE=C:\Exstream\Development\LetterWriter\ControlFiles\Letter.opt";
// Hong's Arguments
//ExStreamPath = #"C:\Program Files\Exstream\Dialogue 6.1\Engine.exe";
//datPath = #"-FILEMAP=DataFile,C:\Exstream\development\AGDocGenerator\TempFiles\DataFiles\Data_456231_1598.xml";
//optPath = #"-CONTROLFILE=C:\Exstream\development\AGDocGenerator\ExstreamDialogue\ControlFiles\AGDocGenerator.opt";
// Kick It!
MyTCP.StartExStream(datPath, optPath, ExStreamPath);
// Extra line of code for breaking point
optPath = "nothing";
}
}
}
First
If the Routine is in the same class than there you can directly call the routine by just writing name of it
Example
private void AnotherMethod()
{
// Call whatever subroutine you like
MyRutine();
}
Second
If its not in the same class you need to create instance of the class which contains routine and than you can use that object to call you routine
Example
MyClass c = new MyClass();
c.MyRutine();
You have to have this all in a namespace and then in a class for this to work.
namespace some.namespace
{
public class myclass
{
private void button1_Click(object sender, EventArgs e)
{ // Call whatever subroutine you like
StartExstream();
}
public void StartExstream()
{ // Do Stuff Here
}
}
}
OK, based on the further post, Your code
tcpExstream.Service1Client MyTCP = new tcpExstream.Service1Client();
is trying to create an object of a type that isn't a type but a member of a type.
instead you would use something like
WhateverTypeTcpExstreamIs MyTCP = new WhateverTypeTcpExstreamIs();
MyTCP.Service1Client = tcpExstream.Service1Client();
Related
I have the following form with a method called setIndex
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 ProjectName
{
public partial class SettingsWindow : Form
{
internal readonly static SettingsWindow Instance = new SettingsWindow { Visible = false };
public SettingsWindow()
{
InitializeComponent();
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string defaultsearch = listBox1.GetItemText(listBox1.SelectedItem);
Core.RegistryHelper.SaveSetting("Config", "ds", defaultsearch);
if (defaultsearch == "aaa") {
Core.LandingUrlOrig = Core.DomainName + "/defaulturl1.php";
} else {
Core.LandingUrlOrig = Core.DomainName + "/defaulturl2.php";
}
}
public static void setIndex(int i)
{
listBox1.SelectedIndex = i;
}
On another form called MainWindow during its initialization I call:
public MainWindow()
{
SettingsWindow.setIndex(0);
}
The error I get is:
An object reference is required for the non-static field, method, or property 'SettingsWindow.listBox1'
Initially the listbox method wasn't static and thus invisible from MainWindow. But now, listbox appears to not exist, even if the form has been instantiated. How do I solve this? I'm just learning C#.
Thank you in advance
because the function setIndex is static you need to use the Instance property:
public static void setIndex(int i)
{
Instance.listBox1.SelectedIndex = i;
}
or don't make that function static and then use instance in the mainwindow function:
public void setIndex(int i)
{
listBox1.SelectedIndex = i;
}
public MainWindow()
{
SettingsWindow.Instance.setIndex(0);
}
This question already has answers here:
Using list between forms
(3 answers)
Closed 2 years ago.
I am trying to get a list from another form. I have made the list public and put it in its own class to no avail.
Form1:
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;
using System.Data.Common;
using System.Configuration;
namespace eAnfonebu
{
public class variables
{
public List<int> rhifAnfoneb = new List<int>();
public List<int> rhifArcheb = new List<int>();
public string[] ddydiadArcheb;
public string[] enwArchebwr;
public string[] eBost;
public int[] gair;
public decimal[] prisMilGair;
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void createNew_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.ShowDialog(); // Shows Form2
}
}
}
Form2 (addInvoice):
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 eAnfonebu
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void AddInvoice_Click(object sender, EventArgs e)
{
try
{
variables.rhifAnfoneb.Add(variables.rhifAnfoneb[variables.rhifAnfoneb.Length - 1] + 1);
}
catch
{
variables.rhifAnfoneb.Add(1);
}
}
}
}
I am getting the error (An object reference is required for the non-static field, method, or property 'variables.rhifAnfoneb') in
try
{
variables.rhifAnfoneb.Add(variables.rhifAnfoneb[variables.rhifAnfoneb.Length - 1] + 1);
}
catch
{
variables.rhifAnfoneb.Add(1);
}
I am sorry for different languages in same code but I am billingual and sometimes I set out to make an app in one language but then it slowly morphs to another.
If awnsering could you please awnser as simply as you could because I am new to c#
Any help would be greatly appreciated.
Eoin
change
public class variables
to
public static class variables
And make all fields static as well. Because, A static class can only contain static data members, static methods.
or
create an instance of variables
variables v = new variables();
v.rhifAnfoneb.Add(variables.rhifAnfoneb[variables.rhifAnfoneb.Length - 1] + 1);
Reference
Static Classes and Static Class Members
I am getting the error (An object reference is required for the
non-static field, method, or property 'variables.rhifAnfoneb') in
Instantiate the Class then use the its members
public static Variables variabs {get;set;}
public Form2()
{
variabs = new variables();
InitializeComponent();
}
private void AddInvoice_Click(object sender, EventArgs e)
{
try
{
variabs.rhifAnfoneb.Add(variables.rhifAnfoneb[variables.rhifAnfoneb.Length - 1] + 1);
}
.
.
}
To Access from Form1
public static Variables variabs {get;set;}
public Form1()
{
variabs= Form2.variabs;
}
Cannot enter text from class to textbox in form.
We set a keypress event in the MyTreeView class.
The text box cannot contain characters.
What should I do?
*set of textBox1.
*Change Modifiers for textBox1 properties from private to public
*Change keypress event from private to public
*(It didn't work well, so I keep it private now.)
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;
using System.Diagnostics;
namespace treeview
{
public partial class Form1 : System.Windows.Forms.Form
{
MyTreeView m_tree_view = new MyTreeView();
public Form1()
{
try
{
InitializeComponent();
System.Windows.Forms.TreeNode[] tree1 = new System.Windows.Forms.TreeNode[2];
m_tree_view.Location = new System.Drawing.Point(0, 0);
m_tree_view.Size = ClientSize;
m_tree_view.AllowDrop = true;
tree1[0] = new System.Windows.Forms.TreeNode("TreeNode1");
tree1[1] = new System.Windows.Forms.TreeNode("TreeNode2");
m_tree_view.Nodes.Add("Node1");
Controls.Add(m_tree_view);
}
catch
{
}
}
//This is the code I added.
private void Form1_Load(object sender, EventArgs e)
{
}
}
public class MyTreeView : System.Windows.Forms.TreeView
{
public MyTreeView()
{
try
{
//This is the code I added.
KeyPress += MyTreeView_KeyPress;
}
catch
{
}
}
//This is the code I added.
private void MyTreeView_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
Console.WriteLine("key_press_ok");
//error code↓
//textBox1.Text = "sample";
}
}
}
If you want just to click an button and then print some text i don't understand why you are making another class.
Will be good to make your code efficient and not complicated.
In the main class
private void SendText_Click(object sender, EventArgs e)
{
textBox1.Text = "hi";
}
But if you want to make it complicated and make a class you shuld return i variable and send it to the other class the you can use it.
Learn how to use Public and private first and then use them.
You shuld have a public class which send data and the private to recive and process.
add (Exception ex) to your try catch.
so do:
try
{
// your code
}
catch (Exception ex)
{
MessageBox.Show(ex, "Error in (add where the error is)");
Console.WriteLine(ex);
}
So you will get a detailed Exception Message, maybe it helps you or maybe you will post it here, so we can see what the problem is.
And because you have System.Windows.Forms in your Using Directive
using System.Windows.Forms;
so
System.Windows.Forms.TreeNode[] tree1 = new System.Windows.Forms.TreeNode[2];
is redundant and can be shortened to:
TreeNode[] tree1 = new TreeNode[2];
Delay.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace LearnThread
{
class Delay
{
public int Convert()
{
int ErrorCode = 1;
//something
//takes long time. about 9 hours.
return ErrorCode;
}
}
}
Form1.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;
using System.Threading;
namespace LearnThread
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnStart_Click(object sender, EventArgs e)
{
Delay delay = new Delay();
Thread t = new Thread(delay.Convert);
//something
MessageBox.Show("Success");
}
}
}
Delay delay = new Delay(); is error here as it is expecting return value. I want the return value as it is contains errorcode. How can I do that? Background worker is better than Thread? Please help. (I should not lose control on the form when delay.Convert() is running.)
As mentioned by Juergen, you can make ErrorCode a class member and then access it once the thread has completed execution. This would require you to create a new instance of the Delay class if you are trying to run multiple Convert in parallel.
You can also use a delegate to get the return value to a variable in the btnStart_Click function as follows:
private void button1_Click(object sender, EventArgs e)
{
Delay delay = new Delay();
int delayResult = 0;
Thread t = new Thread(delegate() { delayResult = delay.Convert(); });
t.Start();
while (t.IsAlive)
{
System.Threading.Thread.Sleep(500);
}
MessageBox.Show(delayResult.ToString());
}
If you plan to run Convert in parallel here, you would have to create as many local variable as required or handle it someother way.
Make the ErrorCode a class member. This way you can get it afterwards.
class Delay
{
public int ErrorCode { get; private set; }
public void Convert()
{
ErrorCode = 1;
...
}
}
private void btnStart_Click(object sender, EventArgs e)
{
Delay delay = new Delay();
Thread t = new Thread(delay.Convert);
//something
int error = delay.ErrorCode;
MessageBox.Show("Success");
}
Specifically looking at the arrive method in the Customer class. I am using a for loop to create instances of the customer class, and when I try to write out their arrival times to a textBox (Just for testing purposes) the text box does not update. Why is this?
This is just a small simulation project for my Computing class. It is in its early stages, and is probably wrong in a lot of places!
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 System.Threading;
namespace QueueSimulation
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void Form1_Load(object sender, EventArgs e)
{
MessageBox.Show("The form has loaded");
}
public void goButton_Click(object sender, EventArgs e)
{
Initialisers init = new Initialisers();
Customer customer = new Customer();
customer.Arrive();
}
private void stopButton_Click(object sender, EventArgs e)
{
// put code here to break out of the program
}
}
public class Customer : Initialisers
{
int waitingTime;
int arrivalTime;
int arrivalInterval;
Initialisers init = new Initialisers();
public void Arrive()
{
Customer[] customer = new Customer[1000];
int counter = 0;
for (int i = 1; i <= 10; i++)
{
customer[i] = new Customer();
customer[i].TimeArrived();
displayArrival.Text = displayArrival.Text + customer[i].TimeArrived().ToString();
// Implement something to either show the time in the queue if needed
Thread.Sleep(init.CustomerArriveTime*100);
}
MessageBox.Show("All of the customers have arrived");
}
public string TimeArrived()
{
return Convert.ToString(DateTime.Now);
}
public void Leave()
{
}
public void GetServed()
{
}
}
public class Server
{
bool servingStatus;
int servingTime;
public void Serve()
{
}
}
public class Initialisers : Form1
{
private int cust_no = 3;
public int CustomerArriveTime
{
get
{
return cust_no;
}
set
{
cust_no = value;
}
}
private int s_time = 4;
public int serveTime
{
get
{
return s_time;
}
set
{
s_time = value;
}
}
}
}
Pass to the Arrive the instance of the textbox object created on your Form1.
public void Arrive(TextBox displayArrival)
Why are you inheriting the Form1 in Initialiserz? It's better to pass the reference to Form1 instead of inheritance in this case.
This seems overly complex. Try to model the real world. What is Initialisers, and why do you have an inheritance tree: Customer > Initialisers > Form1?
You're customer is writing to its own TextBox, instead of the TextBox you're looking at (the one from the Form that is visible).
Why not have a method Arrive that sets a private field to DateTime.Now. Then, ask the Customer its TimeArrived, which returns this field. In your Form, call these methods as much as needed in your loop.
This also seperaties command (Arrive) from query (TimeArrived) + keeps your inheritance more logical.
You might not even need Initialisers anymore. And don't let Customer inherit from Form, because a Customer isn't a Form.
I think there is more of a design issue here, you are creating instances of customer inside customer.
Your customer Arrive method should probably be a function inside the another class, like below, customer should just define what a customer is. Processing them should be handled by a different class.
class Customer
{
int waitingTime;
int arrivalTime;
int arrivalInterval;
// etc...
}
class ProcessCustomers
{
pubic void Arrive()
{
// etc...
}
}
public void goButton_Click(object sender, EventArgs e)
{
Initialisers init = new Initialisers();
ProcessCustomers CustomerQueue = new ProcessCustomers();
CustomerQueue .Arrive();
}
But for the text box issue you will have to expose a property in the form class and set it like that,
string ArrivalTime
{
get
{
return textBox1.Text;
}
set
{
textBox1.Text = value;
}
}