use PictureBox from another class c# - c#

I hope my question will be clear
In Form1.cs i have PictureBox named: ico_ok
i would like to use this PictureBox in my new class that i bulit.
when i start typing ico... nothing appears.
what is the way to use this object in another class?
here the code:
public void button2_Click(object sender, EventArgs e)
{
lbl_check.Visible = true;
btn_continue.Visible = false;
txtbox_cusnumber.Enabled = false;
string userID = (txtbox_cusnumber.Text.ToString());
CheckOUinADexist checkou = new CheckOUinADexist(userID);
}
after that look at the new class:
namespace ChekingOUinActiveDirectory
{
class CheckOUinADexist
{
public CheckOUinADexist(string userID)
{
//this place i would like to use ico_ok
}
}
}
Thank you for helping.
Maayan

The simplest approach is probably to provide that class with the dependency on the PictureBox:
public CheckOUinADexist(string userID, PictureBox pbox)
{
pbox.[your code]
}
Then supply it when calling the method:
CheckOUinADexist checkou = new CheckOUinADexist(userID, ico_ok);
Whether or not this is the ideal approach depends on what you're going to be doing with that PictureBox inside that object, how portable that object needs to be across technology platforms, etc.
In general you don't want UI elements to permeate into non-UI logic. If CheckOUinADexist is a UI-bound class and exists solely to help the UI, then this isn't a problem. If it's part of business logic then you wouldn't want to couple that logic with the UI technology. Instead, you'd likely pass it the data needed from the PictureBox, but not the PictureBox itself.
This all depends a lot on the overall architecture of what you're trying to achieve here, which we don't know.

Basically you'd give the target class a reference to the "shared data" -- picture box in this case.
class CheckOUinADexist
{
PictureBox _picBox
public CheckOUinADexist(string userID, PictureBox picBox)
{
//this place i would like to use ico_ok
_picBox = picBox;
_picBox.myAction();
}
}
Whether you want to actually stored Picturebox as a field (as opposed to just use a parameter) depends on whether you need access to the field throughout the lifetime of the instance(s) or whether it is just needed for object construction. If you are not sure, you are safer (IMHO) just storing a reference in a field. Make further uses of it a lot easier.

Related

Updating object at program level within class

I have a program that runs in the system tray that communicates with our server and "syncs" data based on a users preferenced jobs. The idea is similar to Dropbox, but for our surveying software called 12d Synergy. The idea is that users can sync data without needing to navigate through the softwares Client.
I want to add the functionality so that when the program is syncing, the icon in the system tray changes to indicate that its still syncing, but i can't figure out how to get access to the original object within the portion of the program where the event is located.
My program stucture is as follows (in c#):
Program.cs
using (ProcessingIcon pi = new ProcessingIcon())
{
pi.SetIcon(Resources._12d);
pi.Display();
Application.Run();
}
ProcessingIcon.cs
NotifyIcon ni;
public void SetIcon(Icon path)
{
ni.Icon = path;
}
public void Display()
{
ni.Text = "Sunrise Surveying 12d Synergy Sync Tool";
ni.Visible = true;
ni.ContextMenuStrip = new ContextMenus().Create();
}
ContextMenus.cs
public ContextMenuStrip Create()
{
// Sync Now
item = new ToolStripMenuItem();
item.Text = "Sync Now";
item.Click += new EventHandler(syncNow_Click);
item.Image = Resources.Sync.ToBitmap();
cms.Items.Add(item);
}
void syncNow_Click(object sender, EventArgs e)
{
string[] jobs = Sync.GetSharedFiles();
string[] files = Sync.GetDataToSync(jobs);
Sync.SyncData(files);
}
What i want to happen, is in the syncNow_click, call the ProcessingIcon.SetIcon() to change the icon, but i can't figure out how to get access to an object that exists 3 layers up in the program.
I should note that i am not a programmer, i'm a surveyor with an interest in programming. I am completely self taught, so i know there is probably something relatively simple i'm missing. This is also my first post in StackOverflow, so i'm not 100% how to use this site to the full capability, so if this has been answered somewhere i apologise.
Any help or advice would be greatly appreciated.
So i worked out a way to answer my own question. Just putting it here in case anyone has the same issue. It turned out to be incredibly simple, and purely just by me not fully understanding the classes/objects structure.
I added a constructor for my ContextMenus object which passed in the the NotifyIcon that was calling it. This was passed to a NotifyIcon variable in that class which i could then access.
class ContextMenus
{
public NotifyIcon ni;
public ContextMenus(NotifyIcon ni)
{
this.ni = ni;
}
}

pass DataStruct around more efficiently (winforms)

i have a DataStruct[] that gets used multiple times on a form. It is created from reading a CSV file. The structure has 5 "columns", each with about 100,000 rows
in particular, i have a bunch of ChangeEvents (trackbars, textboxes, etc.), where each change event is re-making the data structure, but i feel it's slowing down the changes (they are rendering on a graph, and it's slow to react)
once i have the actual structure, i don't need to change it, i just need to work with the data. I don't know how i can create the DataStruct[] only once, then pass that struct into the various change events without rebuilding it
the following code currently exists in all my change events (edited for brevity):
string[] fileArray = File.ReadAllLines(tempfile);
DataStruct[] data = new DataStruct[fileArray.Length];
for (int i = 0; i < fileArray.Length; i++)
{
List<string> dataList = fileArray[i].Split(',').ToList<string>();
data[i].X = (Convert.ToSingle(dataList[0]));
}
my confusion is: i have a variety of void() methods that use the structure, and it's easy to pass into those. however i don't understand how to pass into a change event, since the handler refreshes every time the change occurs, i don't know where to call the pass. For example:
private void trackBar1_Scroll(object sender, EventArgs e)
{
label282.Text = trackBar1.Value.ToString();
chart17.Series[0].Points.Clear();
VoltageChanger();
}
how would i call this Scroll change without re-doing the struct? VoltageChanger() uses the struct to do some stuff and make a new graph based on the trackbar value.
or...am i silly in thinking that there may be a slowdown here, and it's just the graph rendering that won't get any better?
thanks (edit: i have been reading but event handling outside of the winforms defaults is currently new to me)
I suggest you read up on variable scope here. For your example, you need to read the information once and have it accessible to all the methods within the class. That is what a module-level variable will do. In the code snippet below, notice the declaration for DataStruct is within the class definition, not within any individual method. This makes the variable visible to that class' methods.
public partial class Form1 : Form
{
private DataStruct[] _data; // <-- Module level variable
public Form1()
{
InitializeComponent();
LoadData();
}
private void LoadData()
{
// Open file code omitted
_data = new DataStruct[fileArray.Length];
// Read data into file omitted
}
private void Method1()
{
// _data will be accessible here because it is a module-level variable
}
}

Why Windows Form TextBox won't update from outside class?

Newbie here. I'm running Visual Studio C# Express 2008. I have two Windows Forms, each with a TextBox. The textboxes update within the same class but not as the result of a invoked method from outside the class. I need to be able to update tbRooms.Text when the UpdateListOfRooms() method is invoked. I've outlined the problem in pseudo-code below. I appreciate your help!
fLocations.cs
fLocations_Load()
{
this.tbLocations.Text = Properties.Settings.Default.LocationID + " locationsLoad"; --updates
}
dgvLocations_SelectionChanged()
{
var rooms = new fRooms();
rooms.tbRooms.Text = Properties.Settings.Default.LocationID + " locationssSelectionChanged"; --updates
rooms.UpdateListOfRooms();
}
fRooms.cs
fRooms_Load()
{
this.tbRooms.Text = Properties.Settings.Default.LocationID + " roomsLoad"; --updates
}
UpdateListOfRooms()
{
this.tbRooms.Text = Properties.Settings.Default.LocationID + " roomsUpdateListOfRooms"; --does NOT update; still says "roomsLoad"
}
Updated 8/20/14:
I've been a busy bee :) I read all the parts of the tutorial by #jmcilhinney and decided to approach this by including references to the two forms, Locations and Rooms, in the MainMenu class that launches them:
(MainMenu.cs) Instances of Locations and Rooms are created. In the constructor, 'rooms' is passed to the 'locations' instance and both forms are shown.
(Locations.cs) Another Rooms instance is created at class scope so it can be seen by all methods of the class. In the constructor, this instance is set to the one being passed by MainMenu which means that this class is working with the same instance created in MainMenu. When the user changes the selection on dgvLocations, the 'dgvLocations_SelectionChanged' event is fired which invokes the Rooms.UpdateRooms method.
(Rooms.cs) The 'UpdateRooms' method displays a new set of rooms based on the passed value of 'locationID'.
This link was helpful. Visual C# - Access instance of object created in one class in another.
public partial class MainMenu : Form
{
Locations locations;
Rooms rooms;
public MainMenu()
{
rooms = new Rooms();
locations = new Locations(rooms);
locations.Show();
rooms.Show();
InitializeComponent();
}
}
public partial class Locations : Form
{
Rooms rooms;
public Locations(Rooms r)
{
rooms = r;
InitializeComponent();
}
private void Locations_Load(object sender, EventArgs e)
{
// Populate this.dgvLocations using SQL query.
}
private void dgvLocations_SelectionChanged(object sender, EventArgs e)
{
// Update the rooms instance with current locationID.
rooms.UpdateRooms(dgvLocations.CurrentCell.Value.ToString());
}
}
public partial class Rooms : Form
{
public Rooms()
{
InitializeComponent();
}
private void Rooms_Load(object sender, EventArgs e)
{
// Populate this.dgvRooms using SQL query.
}
public void UpdateRooms(string locationID)
{
// Update dgvRooms based on user changing the locationID in dgvLocations
}
}
In the first code snippet, you create a new fRooms object but you never call its Show or ShowDialog method, which means that you never display it to the user. That means that any changes you make to that form will not be seen. Presumably the user can see an fRooms object though, but you are not making any changes to that one.
Consider this. Let's say that I give you a note pad and you open it and look at the first page. Let's say that I now buy a new note pad and write on the first page of it. Would you expect to see the words I wrote magically appear on the page in front of you? Of course not. We both are holding a note pad but they are two different note pads. You're looking at one and I'm writing on the other, so you won;t see what I write.
The same goes for your forms. They are both fRooms objects but they are two different fRooms objects. Changes you make to one will not affect the other. If you want the user to see the changes you make then you must make those changes to the fRooms object that the user is looking at.

Passing objects between classes in Windows Phone/C#

I'm new to Windows Phone and C#, enjoying the change from Objective-C and Java.
I cant find the way to pass an object from one class to another. I came across some sample code looking on MSDN but I tink that maybe its not applicable for what I need.
private void meetingList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (meetingList.SelectedIndex != -1)
{
Meeting aMeeting = (Meeting)meetingList.SelectedItem;
this.NavigationService.Navigate(new Uri("/MeetDetails.xaml", UriKind.Relative));
ApplicationBar.IsVisible = true;
}
}
How can I pass my Meeting Object 'aMeeting' into my MeetDetails class so that I can display all the details to the user.
I know I can break it down, and pass in all the vars from the 'aMeeting' by using something like this:
this.NavigationService.Navigate(new Uri("/MeetDetails.xaml?Meeting=" +
aMeeting.meetName + "&TheDate=" +
aMeeting.meetDate, UriKind.Relative));
Is there something I've missed? Are there alternative ways you guys would recommend?
Many Thanks,
-Code
What you've posted is a good way of transferring simple data about the place. However it becomes a pain when you have to pass a complex object between pages.
The recommended way is to use the MVVM pattern (from wikipedia and MSDN). This gives you a way to separate the View from everything else by making use of data binding. The best tutorials I have seen is to watch the videos on MSDN.
var t1 = App.Current as App;
t1.SSIDToken = stData1SSID;
t1.CSRFToken = stData1CSRF;
this works real good, just make the members u need in the app.cs file
(here it was :
public string SSIDToken {get; set;}
public string CSRFToken {get; set;}
Then create the top code to create a var to serve as temp buffer.
If you want to get back the values use the same code :
var t1 = App.Current as App;
thisisatextbox.Text = t1.SSIDToken;
thisisalsoatextbox.Text = t1.CSRFToken;
Further info ;
http://www.eugenedotnet.com/2011/07/passing-values-between-windows-phone-7-pages-current-context-of-application/
EDIT: After a couple of months of experience, noticed you can add
public static new App Current
{
get { return Application.Current as App; }
}
In the App.xaml (In the public class App) to be able to call upon App.Current without having to declare it every single time!
Now you can use App.Current.CSRFToken = "" || string CSRFTk = App.Current.CSRFToken;
You might want to consider a manager class with properties which could store your current Meeting object. This would then be set in your SelectionChanged event handler and then accessed in your MeetDetails page. The manager class is defined externally to your pages so that it can be accessed from all your pages.

Refactoring big ball of mud; not sure static is being used properly here. Advice?

I'll admit sometimes the deeper nuances of the keyword static escape me.
Here's what I'm seeing:
public partial class Default : CSSDEIStatusBase
{
private static Default _csWitWeb;
protected void Page_Load(object sender, EventArgs e)
{
//DoStuff
_csWitWeb = this;
//OtherStuff
}
public static void ForceLoadSyncOperation(int? index)
{
Default._csWitWeb.LoadSelectedSyncOperation(index);
}
}
The only references to ForceLoadSyncOperation are:
Default.ForceLoadSyncOperation(index);
or
Default.ForceLoadSyncOperation(null);
Both of these calls originate from:
public partial class DataOriginUserControl : System.Web.UI.UserControl
and are not located inside of static methods.
E.G:
protected void btnCancelSyncOperation_Click(object sender, EventArgs e)
{
this.lblErrorMessage.Text = string.Empty;
this.lblErrorMessage.Visible = false;
int index = _syncOperation.Sequence - 1;
Default.ForceLoadSyncOperation(index);
}
This all seems really quirky to me. Does this smell to anyone else? Not really sure how to untangle it, though, as I can't exactly create an instance of the Default page inside of a user control.
Thoughts? Thanks for reading.
protected void LoadSelectedSyncOperation(int? index)
{
SyncOperationConfiguration[] syncOperations = CSServiceClient.GetInterfaceConfiguration().SyncOperationConfigurations.ToArray();
PopulateSyncOperationsListView(syncOperations);
SyncOperationConfiguration syncOperation = null;
try
{
syncOperation = syncOperations[index.HasValue ? index.Value : 0];
}
catch
{
syncOperation = syncOperations[0];
}
ucDataOrigin.LoadSyncOperationData(syncOperation);
Session["ConfigMenuActiveIndex"] = 1;
menuConfiguration.Items[(int)Session["ConfigMenuActiveIndex"]].Selected = true;
mvwConfiguration.ActiveViewIndex = (int)Session["ConfigMenuActiveIndex"];
}
Presumably, the user control is contained within the Default page and the static member is being used as a shortcut to get the current instance of Default. I would've done it this way:
Default defaultPage = this.Page as Default;
if (defaultPage != null)
{
defaultPage.LoadSelectedSyncOperation(index);
}
Using a static member in this way is not safe. It opens up the door for race conditions. There is the potential risk that the user control is loaded in another page and calls LoadSelectedSyncOperation() on a separate request's instance of Default, thus wreaking all kinds of potential havoc.
I don't know what LoadSelectedSyncOperation does but this code looks weird. Whenever you click btnCancelSyncOperation you end up calling this method on some page, but you never know on which of them. It doesn't make much sense to me.
I would definitely say your concerns are valid. I can't think of any reason that this design would make sense, ever. This would throw a flag for me, too.
Based on your reply to my comment, if the Default.LoadSelectedSyncOperation is not dependent upon the Default page somehow, then I suggest it be refactored into a separate class (not an ASP.NET Page).
Whether it makes sense for the method or new class to be static or not is a separate concern and would be based on the logic contained within the method.

Categories