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;
}
}
Related
I am modifying to first question attempt.
I need help passing the data from a listbox and pass it to another method so every time the listbox gets data add it from the tread, it should also send that data to my new method and it to the my list because in that method I will be doing some parsing because the data from the listbox is a long string barcode but I don't need help on parsing the data because I can do that, the part I need help only is to pass the data from thread that is passing it to the listbox it should also be send to my method ReadAllData() so in that method I will received the data and then I will do the parsing the make a return.
Here is the method where the listbox is stored and receives the data from a thread from telnet port 23
Here is the code I need to send the data from the lst_BarcodeScan to the method ReadAllData method and store to my list.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Runtime.Remoting.Messaging;
using System.Security.Authentication.ExtendedProtection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace BarcodeReceivingApp
{
public class TelnetConnection
{
private Thread _readWriteThread;
private TcpClient _client;
private NetworkStream _networkStream;
private string _hostname;
private int _port;
private BarcodeReceivingForm _form;
private bool _isExiting = false;
public TelnetConnection(string hostname, int port)
{
this._hostname = hostname;
this._port = port;
}
public TelnetConnection()
{
}
public void ServerSocket(string ip, int port, BarcodeReceivingForm f)
{
this._form = f;
try
{
_client = new TcpClient(ip, port);
}
catch (SocketException)
{
MessageBox.Show(#"Failed to connect to server");
return;
}
_networkStream = _client.GetStream();
_readWriteThread = new Thread(ReadWrite);
//_readWriteThread = new Thread(() => ReadWrite(f));
_readWriteThread.Start();
}
public void Exit()
{
_isExiting = true;
}
public void ReadWrite()
{
var received = "";
do
{
received = Read();
if (received == null)
break;
if (_form.lst_BarcodeScan.InvokeRequired)
{
_form.lst_BarcodeScan.Invoke(new MethodInvoker(delegate
{
_form.lst_BarcodeScan.Items.Add(received + Environment.NewLine);
}));
}
} while (!_isExiting);
CloseConnection();
}
public List<string> ReadAllData()
{
var obtainData = new List<string>();
return obtainData;
}
public string Read()
{
var data = new byte[1024];
var received = "";
var size = _networkStream.Read(data, 0, data.Length);
if (size == 0)
return null;
received = Encoding.ASCII.GetString(data, 0, size);
return received;
}
public void CloseConnection()
{
MessageBox.Show(#"Closed Connection",#"Important Message");
_networkStream.Close();
_client.Close();
}
}
}
Main class that will call the methods from the telnetconnection class or any other classes I will add.
using System;
using System.Windows.Forms;
namespace BarcodeReceivingApp
{
public partial class BarcodeReceivingForm : Form
{
//GLOBAL VARIABLES
private const string Hostname = "myip";
private const int Port = 23;
private TelnetConnection _connection;
public BarcodeReceivingForm()
{
InitializeComponent();
//FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
WindowState = FormWindowState.Maximized;
}
private void btn_ConnectT_Click(object sender, EventArgs e)
{
_connection = new TelnetConnection(Hostname, Port);
_connection.ServerSocket(Hostname, Port, this);
}
private void btn_StopConnection_Click(object sender, EventArgs e)
{
//_connection = new TelnetConnection(Hostname, Port);
//_connection.ServerSocket(Hostname, Port, this);
_connection.Exit();
}
private void btn_RemoveItemFromListAt_Click(object sender, EventArgs e)
{
for (var i = lst_BarcodeScan.SelectedIndices.Count - 1; i >= 0; i--)
{
lst_BarcodeScan.Items.RemoveAt(lst_BarcodeScan.SelectedIndices[i]);
}
}
private void BarcodeReceivingForm_Load(object sender, EventArgs e)
{
lst_BarcodeScan.SelectionMode = SelectionMode.MultiSimple;
}
private void btn_ApplicationSettings_Click(object sender, EventArgs e)
{
var bcSettingsForm = new BarcodeReceivingSettingsForm();
bcSettingsForm.Show();
}
private void btn_ClearBarcodeList_Click(object sender, EventArgs e)
{
lst_BarcodeScan.Items.Clear();
}
}
}
The easiest way to implement without adding more complexity to the thread is to simply raise an event on the listbox when and item is added to it. The problem is that the listbox do no have any events that allow to do that but you can create your own version with a dozen lines of code.
The goal is to create a derived control of the listbox then you add to it a method to trigger a custom event when an item is added and bingo.
Here's the custom listbox class with the custom EventArgs.
// custom override class over the list box so we can create an event when items are added
public class ListBoxWithEvents : ListBox
{
// the event you need to bind to know when items are added
public event EventHandler<ListBoxItemEventArgs> ItemAdded;
// method to call to add items instead of lst.Items.Add(x);
public void AddItem(object data)
{
// add the item normally to the internal list
var index = Items.Add(data);
// invoke the event to notify the binded handlers
InvokeItemAdded(index);
}
public void InvokeItemAdded(int index)
{
// invoke the event if binded anywhere
ItemAdded?.Invoke(this, new ListBoxItemEventArgs(index));
}
}
// basic event handler that will hold the index of the item added
public class ListBoxItemEventArgs : EventArgs
{
public int Index { get; set; } = -1;
public ListBoxItemEventArgs(int index)
{
Index = index;
}
}
Now you need to change your listbox on your form with the ListBoxWithEvents instead. You have 2 ways to do this but i'll give you the easiest. Compile your code and go in the design window for the form. In your toolbox you should have the ListBoxWithEvents control now and you can simply drag and drop in your form and replace the one you have. Since it derive from the listbox all it has is extra features. It didn't lose anything it had before.
Now you need to change 2 things. In your form select the new ListBoxWithEvents control and go in the properties events and you will find the new event called ItemAdded you can double click that and it should create an event like the following. I have also thrown in a sample MessageBox that display all you will need.
private void ListBox1_ItemAdded(object sender, ListBoxItemEventArgs e)
{
MessageBox.Show("Item was added at index " + e.Index + " and the value is " + listBox1.Items[e.Index].ToString());
}
Finally in order to trigger that event you need to use the new method lst.AddItem(object); instead of lst.Items.Add(object); so according to your sample code you need to change this :
_form.lst_BarcodeScan.Invoke(new MethodInvoker(delegate
{
_form.lst_BarcodeScan.Items.Add(received + Environment.NewLine);
}));
to this :
_form.lst_BarcodeScan.Invoke(new MethodInvoker(delegate
{
_form.lst_BarcodeScan.AddItem(received + Environment.NewLine);
}));
Try it and now you should have that event fire every time something is added to the list.
Since you are pretty new to programming i find it important to mention that this event will trigger on the UI thread and not the thread you created. This mean it behave normally like clicking on a button triggers a button_click(object sender, EventArgs e) event. No special thread involved whatsoever.
I have a form that has a button to get a method executed in another class.
Code on the form:
public delegate void CustomPreviewCreate();
public static event CustomPreviewCreate CustomPreviewCreate_Do;
private void CreatePreview()
{
if (CustomPreviewCreate_Do !=null)
{
CustomPreviewCreate_Do();
}
}
This event then gets handled in another class. What I would like to achieve is that I can feed back to the form some form of return value if the method correctly executed.
What I tried so far does not get me the result.
Here is the code:
public void Initialize()
{
SubAsstViewPartControl.CustomPreviewCreate_Do += SubAsstViewPartControl_CustomPreviewCreate_Do;
// this gives me a the compiler error that the return type is wrong
}
private bool SubAsstViewPartControl_CustomPreviewCreate_Do()
{
// do stuff
return false;
}
Is there any direct way to return value from an event handler or I need to use a separate static field to store the event result in?
Update:
Per #Jon's comment, which seemed the simplest to me, I added an answer below demonstrating the simplest approach.
The common approach is to encapsulate your value in the type of EventArgs your event expects. For example, the Framework's CancelEventArgs contains a settable bool Cancel property, allowing each CancelEventHandler to assign a value. The sender can then read the property after the event has been invoked. You could also use a container-like EventArgs class if you want to collect separate values from individual event handlers. For example:
using System;
using System.Collections.Generic;
namespace ConsoleApplication1
{
public class SingleValueEventArgs : EventArgs
{
public int Value { get; set; }
}
public class MultiValueEventArgs : EventArgs
{
private List<int> _values = new List<int>(); // Private to prevent handlers from messing with each others' values
public IEnumerable<int> Values
{
get { return _values; }
}
public void AddValue(int value) { _values.Add(value); }
}
public class Exposer
{
public event EventHandler<SingleValueEventArgs> WantSingleValue;
public event EventHandler<MultiValueEventArgs> WantMultipleValues;
public void Run()
{
if (WantSingleValue != null)
{
var args = new SingleValueEventArgs();
WantSingleValue(this, args);
Console.WriteLine("Last handler produced " + args.Value.ToString());
}
if (WantMultipleValues != null)
{
var args = new MultiValueEventArgs();
WantMultipleValues(this, args);
foreach (var value in args.Values)
{
Console.WriteLine("A handler produced " + value.ToString());
}
}
}
}
public class Handler
{
private int _value;
public Handler(Exposer exposer, int value)
{
_value = value;
exposer.WantSingleValue += exposer_WantSingleValue;
exposer.WantMultipleValues += exposer_WantMultipleValues;
}
void exposer_WantSingleValue(object sender, SingleValueEventArgs e)
{
Console.WriteLine("Handler assigning " + _value.ToString());
e.Value = _value;
}
void exposer_WantMultipleValues(object sender, MultiValueEventArgs e)
{
Console.WriteLine("Handler adding " + _value.ToString());
e.AddValue(_value);
}
}
class Program
{
static void Main(string[] args)
{
var exposer = new Exposer();
for (var i = 0; i < 5; i++)
{
new Handler(exposer, i);
}
exposer.Run();
}
}
}
Per Jon Skeet's comment, which seemed the simplest to me, the simplest approach seems to be as follows:
public delegate bool CustomPreviewCreate(); // here we declare a return type
public static event CustomPreviewCreate CustomPreviewCreate_Do;
private void CreatePreview()
{
if (CustomPreviewCreate_Do !=null)
{
bool returnval = CustomPreviewCreate_Do();
}
}
And then:
// the method is declared to return the same type
bool SubAsstViewPartControl_CustomPreviewCreate_Do()
{
// do stuff
return true; // return the value of the type declared
}
Hello everyone I am trying to make since of what I am doing wrong or maybe I am over thinking it again. I am trying to create a class and in the class I am calling 2 private variables such as num1 and num2. Then i create a public property that corresponds to num 1 and num2. Then after I create that I need to create a public overriable method called calculate and this will add the two variables together and returns the results. Then I have a add button that I have to add the code to the button that adds the two numbers and output the result to a messagebox.I have tried a couple different ways and I still am not getting it.
Here is code 1:
public abstract class CalulateValues
{
protected List<int> values = new List<int>();
public void AddValue(int value) { values.Add(value); }
public abstract int Calculate();
}
public class Add : CalulateValues
{
public override int Calculate()
{
return values.Sum(x => x);
}
}
and here is code 2 I tried:
class CalculateValues
{
private int _num1;
private int _num2;
public int Num1
{
get
{
return _num1;
}
set
{
_num1 = value;
}
}
public int Num2
{
get
{
return _num2;
}
set
{
_num2 = value;
}
}
public virtual int calculate()
{
return _num1 + _num2;
}
}
Now when it comes with the button I have tried this code:
public partial class Form2 : Form
{
public Form2()
{
CalculateValues myAdd = new CalculateValues();
MulitplyValues Add = new MulitplyValues();
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int total = myAdd.Add(int.Parse(textBox1.Text), int.Parse(textBox2.Text));
MessageBox.Show(total.ToString());
}
I am not too sure what I am doing wrong maybe I am not laying out the code the right way.
You have declared myAdd as a local variable in the Form2 constructor. Declare it as a global variable in order to be able to call it from button1_Click()
In addition to this, are you getting any error or exception? Second, where did you declare Add method that accepts two parameters?
public partial class Form2 : Form
{
CalculateValues myAdd;
public Form2()
{
InitializeComponent();
myAdd = new CalculateValues();
}
private void button1_Click(object sender, EventArgs e)
{
int total = myAdd.Add(int.Parse(textBox1.Text), int.Parse(textBox2.Text));
MessageBox.Show(total.ToString());
}
}
And then go and look up firstly a C# tutorial, then look at detail on variable scope.
int total = myAdd.Add(int.Parse(textBox1.Text), int.Parse(textBox2.Text));
myAdd has no Add method at all. It is AddValue. And you should call Calculate and retrieve the result.
Declare myAdd as member variable instead local in constructor.
And try that:
myAdd.AddValue(int.Parse(textBox1.Text)
myAdd.AddValue(int.Parse(textBox2.Text);
int total = myAdd.Calculate();
MessageBox.Show(total.ToString());
Multiple bugs in your code.
You don't have a method Add, you shoudl use the method calculate like this
private void button1_Click(object sender, EventArgs e)
{
int total = myAdd.Add(int.Parse(textBox1.Text), int.Parse(textBox2.Text));
MessageBox.Show(total.ToString());
}
You need to declare the myAdd variable outside of the constructor, even if you only initialize in the Form2() constructor.
Your CalculateValues class does not have an "Add" method.
Instead you should be calling the "Calculate" method like this:
public partial class Form2 : Form
{
public Form2()
{
CalculateValues myAdd = new CalculateValues();
MulitplyValues Add = new MulitplyValues();
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int total = myAdd.Calculate(int.Parse(textBox1.Text), int.Parse(textBox2.Text));
MessageBox.Show(total.ToString());
}
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();
I am getting the following error from my C# Windows Application:
Error 1 No overload for 'CreateLabelInPanel' matches delegate 'WorksOrderStore.ProcessDbConnDetailsDelegate' H:\c\WorksOrderFactory\WorksOrderFactory\WorksOrderClient.cs 43 39 WorksOrderFactory
I have 3 .cs files that essentially:
Opens a windows
Has an option for the users to connect to a db
When that is selected, the system will go off and connect to the db, and load some data in (just test data for now)
Then using a delegate, the system should do soemthing, which for testing will be to create a label. However I haven't coded this part yet.
But I can't build until I get this error sorted.
The 3 fiels are called:
WorksOrderClient.cs (which is the MAIN)
WorksOrderStore.cs
LoginBox.cs
Here's the code for each file:
WorksOrderClient.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 WorksOrderStore;
namespace WorksOrderFactory
{
using WorksOrderStore;
public partial class WorksOrderClient : Form
{
LoginBox lb = new LoginBox();
private static WorksOrderDB wodb = new WorksOrderDB();
private static int num_conns = 0;
public WorksOrderClient()
{
InitializeComponent();
}
private void connectToADBToolStripMenuItem_Click(object sender, EventArgs e)
{
lb.ShowDialog();
lb.Visible = true;
}
public static bool createDBConnDetObj(string username, string password, string database)
{
// increase the number of connections
num_conns = num_conns + 1;
// create the connection object
wodb.AddDbConnDetails(username, password, database, num_conns);
// create a new delegate object associated with the static
// method WorksOrderClient.createLabelInPanel
wodb.ProcessDbConnDetails(new ProcessDbConnDetailsDelegate(CreateLabelInPanel));
return true;
}
static void CreateLabelInPanel(DbConnDetails dbcd)
{
Console.Write("hellO");
string tmp = (string)dbcd.username;
//Console.Write(tmp);
}
private void WorksOrderClient_Load(object sender, EventArgs e)
{
}
}
}
WorksOrderStore.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WorksOrderFactory;
namespace WorksOrderStore
{
using System.Collections;
// Describes a book in the book list:
public struct WorksOrder
{
public string contractor_code { get; set; } // contractor ID
public string email_address { get; set; } // contractors email address
public string date_issued { get; set; } // date the works order was issued
public string wo_ref { get; set; } // works order ref
public string status { get; set; } // status ... not used
public job_status js { get; set; } // status of this worksorder within this system
public WorksOrder(string contractor_code, string email_address, string date_issued, string wo_ref) : this()
{
this.contractor_code = contractor_code;
this.email_address = email_address;
this.date_issued = date_issued;
this.wo_ref = wo_ref;
this.js = job_status.Pending;
}
}
// Declare a delegate type for processing a WorksOrder:
//public delegate void ProcessWorksOrderDelegate(WorksOrder worksorder);
// Maintains a worksorder database.
public class WorksOrderDB
{
// List of all worksorders in the database:
ArrayList list = new ArrayList();
// Add a worksorder to the database:
public void AddWorksOrder(string contractor_code, string email_address, string date_issued, string wo_ref)
{
list.Add(new WorksOrder(contractor_code, email_address, date_issued, wo_ref));
}
// Call a passed-in delegate on each pending works order to process it:
/*public void ProcessPendingWorksOrders(ProcessWorksOrderDelegate processWorksOrder)
{
foreach (WorksOrder wo in list)
{
if (wo.js.Equals(job_status.Pending))
// Calling the delegate:
processWorksOrder(wo);
}
}*/
// Add a DbConnDetails to the database:
public void AddDbConnDetails(string username, string password, string database, int conn_num)
{
list.Add(new DbConnDetails(username, password, database, conn_num));
}
// Call a passed-in delegate on each dbconndet to process it:
public void ProcessDbConnDetails(ProcessDbConnDetailsDelegate processDBConnDetails)
{
foreach (DbConnDetails wo in list)
{
processDBConnDetails(wo);
}
}
}
// statuses for worksorders in this system
public enum job_status
{
Pending,
InProgress,
Completed
}
public struct DbConnDetails
{
public string username { get; set; } // username
public string password { get; set; } // password
public string database { get; set; } // database
public int conn_num { get; set; } // this objects connection number.
public ArrayList woList { get; set; } // list of works orders for this connection
// this constructor just sets the db connection details
// the woList array will get created later .. not a lot later but a bit.
public DbConnDetails(string username, string password, string database, int conn_num) : this()
{
this.username = username;
this.password = password;
this.database = database;
this.conn_num = conn_num;
woList = new ArrayList();
}
}
// Declare a delegate type for processing a DbConnDetails:
public delegate void ProcessDbConnDetailsDelegate(DbConnDetails dbConnDetails);
}
LoginBox.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WorksOrderFactory
{
public partial class LoginBox : Form
{
public LoginBox()
{
InitializeComponent();
}
private void LoginBox_Load(object sender, EventArgs e)
{
this.Visible = true;
this.Show();
//usernameText.Text = "Username";
//new Font(usernameText.Font, FontStyle.Italic);
}
private void cancelBtn_Click(object sender, EventArgs e)
{
this.Close();
}
private void loginBtn_Click(object sender, EventArgs e)
{
// set up a connection details object.
bool success = WorksOrderClient.createDBConnDetObj(usernameText.Text, passwordText.Text, databaseText.Text);
}
private void LoginBox_Load_1(object sender, EventArgs e)
{
}
}
}
Any ideas??
Cheers,
m
The one thing jumps out when comparing the definition of the delegate with the definition of the method you're trying to use:
static void CreateLabelInPanel(DbConnDetails dbcd)
public delegate void ProcessDbConnDetailsDelegate(DbConnDetails dbConnDetails)
CreateLabelInPanel should probably not be declared as static.
The compiler is just saying that the method you are providing to a delegate is not matching the signature expected by the delegate.
So, in your case.
//To get this line working...
wodb.ProcessDbConnDetails(new ProcessDbConnDetailsDelegate(SomeMethod1));
//The method signature should be like this.
static void SomeMethod1(DbConnDetails dbcd)
//OR even this -- Instance/Static methods can be supplied to same delegate.
void SomeInstanceMethod(DbConnDetails dbcd)..
And if not, the compiler would complain.
Also, by any chance, do you have two classes with the name "DbConnDetails" ???
My best guess is you are referring to "DbConnDetails" that lies in different namespace than the one expected by the delegate.
thanks #amby and #massif and anyone else I may have missed.
This was a school boy error.
It turns out I had another file (which I thought I'd deleted) that also contained a class and constructor called DbConnDetails. I did a search for DbConnDetails in the solution.
I renamed that class/constructor and the filename as well, to be safe.
I then declared
static void CreateLabelInPanel(DbConnDetails dbcd)
which means that the app now compiles/builds again.
Thanks again to everyone.