I have a windows application that sends and receives messages to/from a microprocessor using the serial port.
The application is working fine and does what is supposed to do. Now, I need to make some elaboration with the data I receive back from serial and I would like to access the variable "value" in SetText method.
How can I access the content of that variable from another method or class?
Thanks for helping.
delegate void SetTextCallback(string text);
private void SetText(string text)
{
if (this.txtOutput.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.BeginInvoke(d, new object[] { text });
}
else
{
txtOutput.AppendText(text);
}
// capture messages from serial port
if (txtOutput.Text.Length > 0)
{
MatchCollection mc = Regex.Matches(txtOutput.Text, #"(\+|-)?\d+");
if (mc.Count > 0)
{
long value = long.Parse(mc[mc.Count - 1].Value);
if (value > 1 && value < 1000)
{
textBox2.Text = value.ToString();
}
else if (value < 2000 && value > 1000)
{
value = value - 1000;
textBox3.Text = value.ToString();
}
}
}
}
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
try
{
SetText(serialPort1.ReadExisting());
}
catch (Exception ex)
{
SetText(ex.ToString());
}
}
Consider this :
Make a property
public long Value { get; set; }
Use this in your code.
if (txtOutput.Text.Length > 0)
{
MatchCollection mc = Regex.Matches(txtOutput.Text, #"(\+|-)?\d+");
if (mc.Count > 0)
{
value = long.Parse(mc[mc.Count - 1].Value);
if (value > 1 && value < 1000)
{
textBox2.Text = value.ToString();
}
else if (value < 2000 && value > 1000)
{
value = value - 1000;
textBox3.Text = value.ToString();
}
}
If you want to make sure that this property retains its value then use static one.
public static long Value { get; set; }
If the data is going to be used more than one place then don't hesitate just create a class with the list of output variables that are to be shared among the methods. Create properties for that variables within that class. Now create an object for this class globally and assign the retrieved values from the microprocessor to the properties within this globally declared object. You can access this in any place. Because of this is a windows application the data will retain until you clear or the application was closed.
Here is the code. I have a textbox and two buttons in the windows app. One button to get the data and another to show the data. The data was get from the user using the textbox. After getting the data once on clicking the show data button it will show the data pushed to the object as many times you want.
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 WindowsFormsApplication1
{
public partial class Form1 : Form
{
// Declare Global Variable
DataHolder objDataHolder = new DataHolder();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
// Here use your code to load the data retrieved from Microprocessor
objDataHolder.UserData = txtUserData.Text;
}
private void button2_Click(object sender, EventArgs e)
{
MessageBox.Show(objDataHolder.UserData);
}
}
// Class to hold Data
public class DataHolder
{
// Here have a list variables that you need to maintain that are retrieved from Microrocessor.
private string _userdata = string.Empty;
// Here have a list Properties that you need to maintain that are retrieved from Microrocessor.
public string UserData
{
get
{
return _userdata;
}
set
{
_userdata = value;
}
}
}
}
You can access the variable in other class using "Static" variable or instance variable
public class Demo1
{
//Static variable can be accessed without instantiating an instance of Demo1
public static int Number; //Demo1.Number
public string Info {get;set;}
}
public class AnotherClass
{
void DoSth()
{
Demo1.Number ++;
}
}
or if you have an instance of Demo1, say demo1Instance
demo1Instance.Info="Sth you like";
This is what I have done and it is now working.Thanks to all of you for the good suggestions. I am quite sure that I am going to use your examples very soon in the additional developments of the application.
internal long value;
private void SetText(string text)
{
if (this.txtOutput.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.BeginInvoke(d, new object[] { text });
}
else
{
txtOutput.AppendText(text);
}
// capture messages from serial port
if (txtOutput.Text.Length > 0)
{
MatchCollection mc = Regex.Matches(txtOutput.Text, #"(\+|-)?\d+");
if (mc.Count > 0)
{
value = long.Parse(mc[mc.Count - 1].Value);
if (value > 1 && value < 1000)
{
textBox2.Text = value.ToString();
}
else if (value < 2000 && value > 1000)
{
value = value - 1000;
textBox3.Text = value.ToString();
}
}
}
}
Related
The purpose of the code is to make it so that it loads from a .txt file, then randomly loads a line to display. I fiddled with it, and I need some more help. Any help would be appreciated. It is commented where it needs adjustments.
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.IO;
namespace EquityPicks
{
public partial class MainForm : Form
{
public List<string> appList = new List<string>(7);
public MainForm()
{
InitializeComponent();
loadList();
}
public void loadList() // Adjust to load from a text File
{
appList.Clear();
for(int i =0; i<10; i++)
{
string text;
using (var streamReader = new StreamReader(#"c:\file.txt", Encoding.UTF8))
{
text = streamReader.ReadToEnd();
}
}
nextUpTextBox.Text = getMember();
onDeckTextBox.Text = getMember();
studentsLeftTextBox.Text = appList.Count.ToString();
}
public string getMember() // Adjust for Randomness
{
string member = appList[0];
appList.RemoveAt(0);
return member;
}
void NextButtonClick(object sender, EventArgs e)
{
if(appList.Count >= 1)
{
nextUpTextBox.Text = onDeckTextBox.Text;
onDeckTextBox.Text = getMember();
}
else if (appList.Count == 0)
{
nextUpTextBox.Text = onDeckTextBox.Text;
onDeckTextBox.Text = "";
}
else
{
nextUpTextBox.Text = "";
onDeckTextBox.Text = "";
}
studentsLeftTextBox.Text = appList.Count.ToString();
}
void ResetButtonClick(object sender, EventArgs e)
{
loadList();
}
}
}
I would use:
string[] array = File.ReadAllLines("path");
And then can use:
new Random().Next(int minValue, int maxValue)
to select a line from the array.
Edit: to clarify
maxValue should be <= array.Length
I have setup an Class that holds names/Numbers/ect, and created a List of objects to hold them. I want to display them on a second Form in a ListView. Right now I am using a getter like...
public List<Employee> GetEmpList(){
return EmployeeList;
}
Then in the second Form's constructor I am using the Form1.GetEmpList() like...
DisplayForm{
InitializeComponent();
LoadEmployees(EmployeeAddition.GetList());
}
I am getting and error saying "an object reference is required for the nonstatic field". The method I am calling is non-static, and returns a reference to the List in the Form1 class. I have even tried to just make the List public and calling using Form1.List but it still gives me the same error.
Is there a way to pass a List between Form classes or is it impossible?
EDIT: Poeple said that more information was needed. I didn't want to copy paste all the code here, but I am going to put a good chunk just because I am new and not quite sure what is relevant and what is not. (I am taking a class, but remotely, and my teacher is...well a remote teacher, useless. She actually told me to ask here)
I guess I am missing how to instatize a method, I thought that when the object was created from the class the method became part of the object. The Method is part for the Form1 (Renamed but thats what it is) class/object. I will dumb the code under here, I don't know if that is frowned upon; if so I am sorry.
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 EmplyeeList
{
public partial class EmployeeDisplay : Form
{
public EmployeeDisplay()
{
InitializeComponent();
LoadEmployees(EmployeeAddition.GetList());
}
private void LoadEmployees(IList<CorpEmployee> emp)
{
foreach (CorpEmployee ce in emp)
{
ListViewItem lvi = new ListViewItem();
lvi.SubItems.Add(ce.Name);
lvi.SubItems.Add(ce.Address);
lvi.SubItems.Add(ce.PhoneNumber);
lvi.SubItems.Add(ce.ServiceArea);
lvi.SubItems.Add(ce.EmplNumber.ToString());
lvi.SubItems.Add(ce.RoomNumber.ToString());
lvi.SubItems.Add(ce.PhoneExt.ToString());
lvi.SubItems.Add(ce.email);
displayListView.Items.Add(lvi);
}
}
private void closeButton_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
This is the first Form class to load...
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 EmplyeeList
{
public class EmployeeAddition : Form
{
//Create a list to hold CorpEmployee objects.
private List<CorpEmployee> CorpEmplList = new List<CorpEmployee>();
public EmployeeAddition()
{
InitializeComponent();
}
private void saveButton_Click(object sender, EventArgs e)
{
int testingNum; //Used for output in parsing numbers
//If statments are used to make sure ints are ints, and nothing is blank.
if (Int32.TryParse(employeeNumTextBox.Text, out testingNum) || ! (employeeNumTextBox.Text == ""))
{
if (Int32.TryParse(roomNumTextBox.Text, out testingNum) || !(roomNumTextBox.Text == ""))
{
if (Int32.TryParse(phoneExtTextBox.Text, out testingNum) || !(phoneExtTextBox.Text == ""))
{
if (!(nameTextBox.Text == "") || !(addressTextBox.Text == "") || !(titleTextBox.Text == "") || !(phoneNumberTextBox.Text == "") ||
!(serviceAreaTextBox.Text == "") || !(emailTextBox.Text == ""))
{
//If all fields are filled in right then we add the object to the List
CorpEmplList.Add(CreateCorpEmployee(nameTextBox.Text, addressTextBox.Text, titleTextBox.Text,
phoneNumberTextBox.Text, serviceAreaTextBox.Text,
Convert.ToInt32(employeeNumTextBox.Text), Convert.ToInt32(roomNumTextBox.Text),
Convert.ToInt32(phoneExtTextBox.Text), emailTextBox.Text));
//Let the user know it was added
MessageBox.Show("Employee was added!");
//Clear fields
ClearAllFields();
}
else
{
MessageBox.Show("All fields must be filled in.");
}
}
else
{
MessageBox.Show("Phone Ext.# should be a number");
}
}
else
{
MessageBox.Show("Check your Room# and try again.");
}
}
else
{
MessageBox.Show("Employee Number Should be a number.");
}
}
//This takes in all the employee fields and returns a contructed object
private CorpEmployee CreateCorpEmployee(String name, String address, String title, String phoneNumber,
String serviceArea, int emplNumber, int roomNumber, int phoneExt, String email)
{
CorpEmployee corpEmpObject = new CorpEmployee(name, address, title, phoneNumber, serviceArea, emplNumber, roomNumber, phoneExt, email);
return corpEmpObject;
}
//This just clears all the fiels
private void ClearAllFields()
{
nameTextBox.Text = "";
addressTextBox.Text = "";
titleTextBox.Text = "";
phoneNumberTextBox.Text = "";
serviceAreaTextBox.Text = "";
employeeNumTextBox.Text = "";
roomNumTextBox.Text = "";
phoneExtTextBox.Text = "";
emailTextBox.Text = "";
}
//This returns the List of CorpEmployees
public List<CorpEmployee> GetList()
{
return CorpEmplList;
}
private void exitButton_Click(object sender, EventArgs e)
{
this.Close();
}
private void clearButton_Click(object sender, EventArgs e)
{
ClearAllFields();
}
private void showButton_Click(object sender, EventArgs e)
{
EmployeeDisplay ed = new EmployeeDisplay();
ed.Show();
}
}
}
After relooking at the code I think I might see what you are saying about calling it from a static class, not an object. Is there a way to find the name of the Object that the Compiler creates from the first Form?
The first problem you are having is you are treating the GetEmpList() function as an static method. It is not static and probably shouldn't be static. That is why people are saying you need to create an instance of it. However, looking at what you are asking the way you are going about this is probably flawed in a more fundamental way that just creating a new version of the form will solve. The problem is you want to pass model data between forms. Without more information it is really hard to tell how you want this all to go together. However you probably already have an instance of the EmployeeAddition form and don't need to create another instance inside the constructor of your DisplayForm. Instead what you should do is make the LoadEmployees method public and pass the results of GetEmpList() into that.
So your structure would be more like
public class EmployeeAddition : Form {
...
public List<Employee> GetEmpList(){
return EmployeeList;
}
...
public void ShowDisplayForm(){
var displayForm = new DisplayForm();
displayForm.LoadEmployees(GetEmpList());
displayForm.Show();
}
...
}
Of course this structure may be slightly off as I'm guessing at which form will own which form but this is closer to what you want.
try use "new"
DisplayForm{
InitializeComponent();
EmployeeAddition = new EmployeeAdditionClass();
LoadEmployees(EmployeeAddition.GetList());
}
I can't figure out why this keeps happening. I'm a beginner but to me there is a reference set to an instance. I had trouble at first getting the class to have a size for the array which is now set to 100
Here is my code.
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.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
SalesmanClass[] salesmen = new SalesmanClass[100];
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox6.Text.Trim().Length != 0)
{
for (int i = 0; i <= salesmen.Length; i++)
{
if (salesmen[i] == null)
{
salesmen[i].name = textBox6.Text; // error happens here when i enter something into the form it says
//Object reference not set to an instance of an object error
break;
}
}
}
else
{
MessageBox.Show("Please Input a Name");
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
List<string> names = new List<string>();
for (int i = 0; i < salesmen.Length; i++)//var salesmen in salesmen)
{
names.Add(salesmen[i].Name);// same problem here
}
listBox1.Items.Add(names);
}
private void textBox6_TextChanged(object sender, EventArgs e)
{
}
private void button2_Click_1(object sender, EventArgs e)
{
}
}
}
SalesmanClass.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WindowsFormsApplication1
{
public class SalesmanClass
{
public string name;
public string cNum;
public string Email;
public string address;
public string gArea;
public int tSales;
public SalesmanClass()
{
name = null;
cNum = null;
Email = null;
address = null;
gArea = null;
}
You use the == operator in your if statement, meaning that if the salesman IS null, set its name. I believe you meant that if the salesman is not null (!=). You're also going to encounter an index out of range exception in your for loop, so I've fixed that here as well.
for (int i = 0; i < salesmen.Length; i++)
{
if (salesmen[i] != null)
{
salesmen[i].name = textBox6.Text; // error happens here when i enter something into the form it says
//Object reference not set to an instance of an object error
break;
}
}
If you did mean for that instance to be null, perhaps you want something like this:
for (int i = 0; i < salesmen.Length; i++)
{
if (salesmen[i] == null)
{
salesmen[i] = new SalesmanClass();
salesmen[i].name = textBox6.Text; // error happens here when i enter something into the form it says
//Object reference not set to an instance of an object error
break;
}
}
In your button2_Click method, you are encountering the same issue because you aren't skipping the null salesmen. You can also see that I commented that I changed the field which you are accessing from Name to name since in the class which you posted, there is no Name field.
private void button2_Click(object sender, EventArgs e)
{
List<string> names = new List<string>();
for (int i = 0; i < salesmen.Length; i++)//var salesmen in salesmen)
{
if (salesmen[i] != null)
{
names.Add(salesmen[i].name); // changed from .Name to .name
}
}
listBox1.Items.Add(names);
}
Just remember that this line doesn't create any new SalesmanClass objects, only 100 references of type SalesmanClass.
SalesmanClass[] salesmen = new SalesmanClass[100];
I think you want:
if (salesmen[i] == null)
{
salesmen[i] = new SalesmanClass();
salesmen[i].name = textBox6.Text;
break;
}
[EDIT]
Lander beat me to it. What I would suggest is you use a List, the you don't have to worry about "empty spots"
List<Salesman>() salesmen = new List<Salesman>();
And then replace your for loop code with simply:
if (textBox6.Text.Trim().Length != 0)
{
salesmen.Add(new Salesmane() { name = textBox6.Text } );
}
else
{
MessageBox.Show("Please Input a Name");
}
You use this further down in List<string> names.
You might have to declare getters and setters on your properties:
public string Name { get; set; }
I would also make these property names CamelCase since that is the accepted standard.
You'll need to update your button2_click to use Count instead of Length or use a foreach loop:
foreach (Salesman salesman in salesmen)
{
names.Add(salesman.Name);
}
You can also use LINQ to simplify, this does exactly the same ting:
List<string> names = salesmen.Select(s => s.Name).ToList();
if an object reference error occurs check whether the variable u pass is correctly matching the correct index eg : If you are using Grid check whether the variable u access correctly pointing the index of the grid.
int StudID =
Convert.ToInt32(editableItem.OwnerTableView.DataKeyValues[editableItem.ItemIndex]
["StudID"].ToString());
I made a Windows Forms application that calculates the factorial of a number. All is fine, but now I have to do it using events. The concept of events is new to me and I've been trying to make it work for the past three days to no avail.
I have the form:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
... some function declarations...
//public event EventHandler ProgressBarChanged;
public int OnProgressBarChanged()
{
progressBar1.Value++;
return progressBar1.Value;
}
public void button2_Click(object sender, EventArgs e)
{
initialize();
label3.Visible = false;
int wait_time = telltime();
int number = reading();
Facto mth;
if (checkBox1.Checked && checkBox2.Checked)
{
mth = new Facto(label3, wait_time, progressBar1);
}
else if(checkBox1.Checked==false && checkBox2.Checked)
{
mth = new Facto(label3,wait_time);
}
else if (checkBox1.Checked && checkBox2.Checked == false)
{
checkBox1.Checked = false;
mth = new Facto();
}
else
{
mth = new Facto();
}
mth.Subs += new Eventhandler(OnProgressBarChanged); // Error. I don't understand why
int result = mth.Factorial(number);
string display = result.ToString();
label3.Visible = true;
label3.Text = display;
}
And the Facto class:
public class Facto
{
public event EventHandler Subs;
System.Windows.Forms.Label label_for_output;
int wait_time;
System.Windows.Forms.ProgressBar bar;
public Facto()
{
}
public Facto(System.Windows.Forms.Label l, int time)
{
label_for_output = l;
wait_time = time;
}
public int Factorial(int number_to_calculate)
{
int Result;
if (Subs != null)
{
Subs(this, new EventArgs());
}
System.Threading.Thread.Sleep(wait_time);
if (number_to_calculate == 0)
{
return 1;
}
else
{
Result = (number_to_calculate * Factorial(number_to_calculate - 1));
if (label_for_output != null)
{
label_for_output.Visible = true;
label_for_output.Text = Result.ToString();
label_for_output.Update();
}
else
Console.WriteLine(Result);
}
System.Threading.Thread.Sleep(wait_time);
return Result;
}
}
}
The event should be triggered when the recursive function calls itself. When the event is triggered progressbar1.value from Form1 should be incremented with 1 (it should also decrement when it comes back from recursion, but I'm more interested in getting it to work first).
How can I fix this?
It's really confusing to me and I can only find examples which show messages or are very badly explained.
You have this error because your method signature are not equal:
.NET assumes that you have
public int OnProgressBarChanged() as
public void OnProgressBarChanged(object o, EventArgs e);
This is a standart signature of all .net events. First parameter - is object, that raised the event. Second parameter is event data.
You can create your custom class, inherited from EventErgs to pass data to event handler
For this kind of task I would suggest using a BackgroundWorker with a ProgressChanged event handler, so that the calculations and UI updates are carried out on separate threads. See the MSDN docs for a similar example with Fibonacci number calculation and a progress bar.
First post, long time reader.
I'm currently learning C# with "Head First C#" (I'm up to Encapsulation and Get/Set properties)
I'm writing a small program to work with pictures for a friend, I'm just wondering if I'm heading along the right lines with my PictureController class? My main problem is that I am setting a lot of form items with this class, and it feels unnatured to keep referencing form items from within the class, I'm pasting my code below, if you could let me know if I'm doing anything wrong then I'd be most grateful :)
Many thanks!
PictureController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
namespace PictureController
{
class PictureController
{
private int arrayPosition = 0;
private int numFiles = 0;
private string[,] arrayPictures;
public PictureBox myPictureBox;
public RadioButton myCopyButton;
public RadioButton myDeleteButton;
public TextBox mySource;
public ComboBox myDestinations;
private FolderBrowserDialog sourceFolder;
private FolderBrowserDialog destFolder;
public void InitialisePicture()
{
if (arrayPictures != null && arrayPictures.Length > 0)
{
myPictureBox.ImageLocation = arrayPictures[arrayPosition, 0];
}
else
{
MessageBox.Show("The folder you have selected contains no pictures...");
myPictureBox.ImageLocation = null;
}
}
public void NavigatePicture(int direction)
{
if (arrayPosition + direction >= 0 && arrayPosition + direction < numFiles)
{
arrayPosition += direction;
myPictureBox.ImageLocation = arrayPictures[arrayPosition, 0];
myCopyButton.Checked = Convert.ToBoolean(arrayPictures[arrayPosition, 1]);
myDeleteButton.Checked = Convert.ToBoolean(arrayPictures[arrayPosition, 2]);
}
}
public void UpdateActions(bool copyChecked, bool deleteChecked)
{
if (arrayPictures != null)
{
arrayPictures[arrayPosition, 1] = copyChecked.ToString();
arrayPictures[arrayPosition, 2] = deleteChecked.ToString();
}
}
public void GetFiles()
{
sourceFolder = new FolderBrowserDialog();
sourceFolder.ShowDialog();
if (sourceFolder.SelectedPath != "")
{
string[] arrayTempFiles = Directory.GetFiles(sourceFolder.SelectedPath,"*.jpg");
numFiles = arrayTempFiles.Length;
arrayPictures = new string[arrayTempFiles.Length,3];
for (int i = 0; i < arrayTempFiles.Length; i++)
{
arrayPictures[i, 0] = arrayTempFiles[i];
arrayPictures[i, 1] = "false";
arrayPictures[i, 2] = "false";
}
mySource.Text = sourceFolder.SelectedPath;
InitialisePicture();
}
}
public void AddDestinationFolder()
{
destFolder = new FolderBrowserDialog();
destFolder.ShowDialog();
if (destFolder.SelectedPath != "")
{
myDestinations.Items.Add(destFolder.SelectedPath);
}
}
}
}
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;
namespace PictureController
{
public partial class Form1 : Form
{
PictureController PicControl;
public Form1()
{
InitializeComponent();
PicControl = new PictureController() { myPictureBox = pbPhoto, myCopyButton = rbMove, myDeleteButton = rbDelete, mySource = tbSource, myDestinations = cbDestination };
}
private void btnPrev_Click(object sender, EventArgs e)
{
PicControl.NavigatePicture(-1);
}
private void btnNext_Click(object sender, EventArgs e)
{
PicControl.NavigatePicture(1);
}
private void rbMove_CheckedChanged(object sender, EventArgs e)
{
if (rbMove.Checked || rbDelete.Checked)
{
PicControl.UpdateActions(rbMove.Checked, rbDelete.Checked);
}
}
private void rbDelete_CheckedChanged(object sender, EventArgs e)
{
if (rbMove.Checked || rbDelete.Checked)
{
PicControl.UpdateActions(rbMove.Checked, rbDelete.Checked);
}
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.A:
PicControl.NavigatePicture(-1);
break;
case Keys.D:
PicControl.NavigatePicture(1);
break;
case Keys.W:
rbMove.Checked = true;
break;
case Keys.S:
rbDelete.Checked = true;
break;
}
}
private void btnGetFiles_Click(object sender, EventArgs e)
{
PicControl.GetFiles();
}
private void btnProcess_Click(object sender, EventArgs e)
{
}
private void btnAddDest_Click(object sender, EventArgs e)
{
PicControl.AddDestinationFolder();
}
}
}
I don't see the reason to use Controls in your PictureController class. You should only use non-forms datatypes there and handle the interaction in your Form, offering events and methods from your PictureController class to react and act on it.
It's a good start in my opinion.
Hard to tell if you're doing something "wrong" because it depends what you think is right, every programmer has his/her own style and best practice set and as long as the code is working and efficient it's "right". There are many roads leading to Rome. :)
Anyway if you ask for personal opinion or advice, I would make two major changes in logic:
Have the Controller be a static class (Singleton if you prefer)
Don't pass or use the form controls directly. Instead pass the instance of your form to the static class in some Initialize method, then use that instance and call public method that is working with the controls directly.
Example for the second change:
public static void NavigatePicture(int direction)
{
if (arrayPosition + direction >= 0 && arrayPosition + direction < numFiles)
{
arrayPosition += direction;
_formInstance.SetPictureLocation(arrayPictures[arrayPosition, 0]);
_formInstance.SetCopyStatus(Convert.ToBoolean(arrayPictures[arrayPosition, 1]));
_formInstance.SetDeleteStatus(Convert.ToBoolean(arrayPictures[arrayPosition, 2]));
}
}
//...and in the form:
public SetPictureLocation(sLocation)
{
myPictureBox.ImageLocation = sLocation;
}
What is the point of having the controller, just encapsulate the extra logic out of the form? Do you need your controller to be testable? Do you want to use an abstract model of your business logic? If you answer yes to last 2 questions you might want to google:
a. MVC pattern
b. MVP pattern
Everything is wrong.
Controller (if it is a controller of the form/window) should know about form while in your sample - form know about controller.
Controller should know how to build data / and handle some form events when in your sample controller have references to pictureBox'es etc.
And there are no need to "extract" controller from the control code, while doesn't established what the "data/model" of the control is (and not framed with the type).
It's not clear what is the data there: path or image collection.