I am pretty new to programming in c#. I have a listview (ListViewProjects) box in ProjectListForm but I want to be able to access the items in the listview box in AddProjectForm. How can I access them? I was going to try to do something like this
ProjectListForm.ListViewProjects.Items.Clear
but when I type in ProjectListForm., ListViewProjects isn't an option.
You can either set the list view's design time options to generate a public member (in control's properties, under Design set Modifiers to Public), or possibly better you could add a public property to ProjectListForm to expose either the list view or just the Items collection, eg:
public class ProjectListForm : Form
{
...
public ListView.ListViewItemCollection ProjectsListViewItems
{
get { return ListViewProjects.Items; }
}
}
The best way IMO is to write public methods in ProjectListForm that do what you're trying to achieve in AddProjectForm, such as ProjectListForm.ClearProjects(). That way you're not forcing AddProjectForm to depend on the implementation of ProjectListForm, say if you later want to change to a TreeView.
You cannot achieve this way in C#. you need to create the instance of the object.
To do this you have to create the method in ProjectListForm and in that methos you have to call this.ListViewProjects.Items.Clear.
Now from the AddProjectForm you have to call this method of the running instance of ProjectListForm.
If you want to know more about how to make the call, then please give the flow about how do you show the AddProjectForm from the ProjectListForm.
Related
I'm very new to using C#. If you have ever heard of the Karol the robot program that is written in Java then that's what I'm aiming to build.
But I am stumbling at almost the first hurdle, I want to make a class for Karol (It is just a picture) that can move around the screen in blocks of 32x32 squares.
Trouble is when you create a class you can't access the properties of form objects because they are separate things.
I would like to be able to manipulate form objects from my class but without having to pass the object through the method each time I use it.
Any help is much appreciated.
Do not need to pass a reference of the Form every time. Should be enough to do something like this:
`public class Karol
{
private Form _form=null;
public Karol(Form frm) {
_form = frm;
}
// after use _form inside the functions and properties of the class, where needed
}`
edit
to acces a control data inside a Form it needs to expose or controls itself, like
public Label MyFormLabel {....}
Or expose a functions/properties that sets or gets the data from the control.
public string MyFormLabelText { get{ return label.Text;} set{label.Text = value;}}
If it's just one form object that "Karol" is manipulating, you should be able to pass it to the constructor and save it for use in later member calls. That way you only pass it once at construction time.
I need to write the result of my query in a textbox in the main form, from another class. What is the best and easy way to achieve this?
Your external class should not know anything about a textbox. It may know about your form in order to send the result there, but the elements are belong to the form and should not be exposed (it is what is called encapsulation).
I suggest you to have a meaningful method on your form, something like ShowListOfUsers(users), or whatever you do, call it appropriately so it can be understood externally.
Then in this method you put the result into the controls (textbox) as you want it.
I also suggest you to have an interface for the form which will contain such behavioral methods and have your window implemented this interface, something like:
public interface IOrderView
{
void ShowOrderDiscount(result);
}
so your external class will know only about the interface, not about the window, the textbox, etc.
Now your query component is trivial:
public class SomeOperation
{
private readonly IOrderView _view;
public SomeOperation(IOrderView view)
{
_view = view;
}
public void DoSomething(parameters)
{
var result = GetMyComplicatedResult();
_view.ShowResult(result);
}
}
The code above is not ideal (as I don't know what is your scenario), but the idea is there.
Good Luck.
Use a public property (or a getter) in your class to retrieve the output of the query.
I have a checkbox that I created to windows forms, how can I set it to static?
public static CheckBox checkthis;
This code creates a new one as static, what I want to do is set one that I have created in the designer to static.
Update:
I tried below answer and it worked, though the checkbox disappeared from the form and various other issues kicked in. Instead I did this create a new one and did this:
public static CheckBox checkthisnew;
...
checkthisnew = checkthis;
Either way, I have now realised that I am fail and that I just can use the state changed on the events list, so all is well...
Sorry for not making my reasoning behind this more clear, I do appreciate your answers though, thank you.
Edit the MyForm.Designer.cs file, right where the declaration for your checkbox is. Note that your changes will be reverted if you use the designer to modify the UI again so you'll have to do this again.
Nothing good can come from making a dependent UI control static. It's one thing to make a component static and that could be ok, but for something like a CheckBox, you're just asking for trouble. For starters, a single control can only have one parent. So you can't just make a single instance of your control and expect to be able to add it to multiple forms and everything will magically appear to be in sync. If you need to share some values, do it the right way and bind to them, register some events, share the value and not the control that holds the value, or other similar methods.
I also cannot recommend you modify generated files (especially if it's generated from a tool you're using all the time). If you must insist on making the control static, declare it in your source file for the class, not the designer-generated file, the classes are declared partial for a reason.
You're probably trying to share some bool value that the CheckBox represents. Make that a static property.
public partial class MyForm : Form
{
public static bool IsToggled { get; set; }
}
If somewhere down the line you want to tie that to an event or whatever, you could always change the implementation of the accessors.
Hmm... without more context, I'd suggest to use a public boolean property for this.
Having a UI item be static is not a good idea.
Try something like this:
public class MyForm : Form
{
public static bool IsWhateverSet {get; private set;}
}
I have a class property that looks as follows:
public List<Recipe> RecipeList
{
get { return this._recipeList; }
set
{
this._recipeList = value;
OnPropertyChanged("RecipeList");
}
}
In another method I have the following which references the property above.
private void RecipeSearch()
{
this.RecipeList = RecipeManagerService.SearchByUnit(SearchCriteria)
.Where(recipe => recipe.IsApproved == true && !recipe.IsHidden).ToList();
}
Code Analysis is issuing a CA 2227 warning: Change RecipeList to be read-only by removing the setter. Could anyone tell me why?
Adding a public setter on a List<T> object is dangerous. You can eliminate this warning by making your setter private:
public List<Recipe> RecipeList
{
get { return this._recipeList; }
private set
{
this._recipeList = value;
OnPropertyChanged("RecipeList");
}
}
This will still allow your class to change this method, but no external source.
I think it's suggesting that usually collection properties themselves shouldn't be mutable - it's more common for the collection to be mutable, and just available via a setter.
It's only a suggestion though :)
In this case you'd use:
RecipeList.Clear();
RecipeList.AddRange(RecipeManagerService
.SearchByUnit(SearchCriteria)
.Where(r => r.IsApproved && !r.IsHidden));
Note that this won't fire the change event though... you might want to use ObservableCollection instead.
This will also mean that anyone can change the contents of the recipe list... do you definitely want that? Another alternative is to expose a ReadOnlyCollection<T> property or something like that, and only make changes within your own class. It really depends what you're trying to do though.
Do you want another instance messing with RecipeList? Generally, I don't let anything change my collection instances except the instance that owns the collection. You could make it private.
The MSDN description is fairly clear:
A writable collection property allows
a user to replace the collection with
a completely different collection
It wouldn't be good OO if the client of your class could change the list to be a completely different list of Recipes. That is against encapsulation.
Ensuring the clients just add or remove items is what you probably want to do.
I don't think there's anything illegal about the code, but it's common practice to have no public setter for collection type properties. Your private RecipeSearch method should just set _recipeList and raise the event, or you could make _recipeList itself a protected property that handles the event.
Allowing the list property to be mutated in two ways (via it's own Add and Remove methods and the list instance as a whole) creates an ambiguous interface to those who consume that property. This confuses responsibilities and creates a larger technical debt/maintenance overhead.
Instead, it is often better practise to separate these concerns so that the property provides access to a single instance of the list. If the list instance must be changeable, a separate mechanism for doing so makes it much clearer that the action of interacting with the property and the action of changing which list instance that property points to are distinct.
What is the best way to access components (e.g. imagelist, timer) from a form instance? I am working on multi form windows forms application on .NET Compact Framework version 3.5 SP1 with C#. I have a Controller class associated with each form for MVC implementation. Here is my sample Controller class.
public class Controller
{
public void Init(Form f)
{
//f.Controls will allow access to all controls
//How shall I access imagelist, timer on form f.
}
}
My question is how can I access non visual components without taking a performance hit of reflection? Any code snippets are welcome. If reflection is only way, then can you provide me optimal way for components access please?
Thanks,
You should be passing a strongly typed form or interface implementation which either exposes the controls directly (not the preferred choice) or abstracts the operations on the view into methods/properties which can be called from the controller (the preferred choice).
No, reflection is not the way. In terms of simply accomplishing what you're going for, you can expose a read-only property that returns the control. For example, say you have an ImageList named imageList1 on your form:
public ImageList ImageList
{
get { return imageList1; }
}
You can then access the ImageList property to get a reference to imageList1.
HOWEVER
This is smelly code. What you should expose is properties and functions that relate to what you need to DO with the ImageList. Your external code should not care about the particular implementation on your form (in other words, it should know you need to do something with images and provide functions to accomplish those actions; it shouldn't need to know that it's an ImageList control).