How can I access an object without knowing its name ? (how to concatenate object name).
I have the following code:
private void pb1_Click(object sender, EventArgs e)
{
Check("1");
}
void Check(string x)
{
if (("pb"+x).Image == img1)
{
("pb"+x).Image = img2;
}
}
This is not the way to go about it. I would recommend you use a dictionary to keep track of your loaded objects, and then just look them up by number in the dictionary.
private Dictionary<int, MyClass> myDict = new Dictionary<int, MyClass>();
void Check(int value)
{
MyClass target = null;
myDict.TryGetValue(value, out target);
//target.Image = etc.
}
You shouldn't pass the controls' name. You'll be better off by passing a reference to that object, which you already have in the eventhandler:
private void pb1_Click(object sender, EventArgs e)
{
SwapImages(sender as PictureBox);
}
private void SwapImages(PictureBox pb)
{
if (pb.Image == img1)
{
pb.Image = img2;
}
}
Related
Can access an control (image) from another class in C#, XAML?
For example: In class A (image) is collapsed/hidden, when check if image is collapsed/hidden in class B, i want to be visible/enabled, it's possible?
Thanks!
You can use the PhoneApplicationService to do it.
For example:
Suppose you navigated from class A to class B.
In class B, before you navigate back to class A, set
PhoneApplicationService.Current.State["showImage"] = true;
In class A, implement OnNavigatedTo to handle it:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
if (PhoneApplicationService.Current.State.ContainsKey("showImage"))
{
bool showImage = (bool)PhoneApplicationService.Current.State["showImage"];
if (showImage)
{
this.YourImage.Visibility = System.Windows.Visibility.Visible;
}
else
{
this.YourImage.Visibility = System.Windows.Visibility.Collapsed;
}
PhoneApplicationService.Current.State.Remove("showImage");
}
}
EDIT:
For multiple images, you can try the following approach:
In class B, instead of passing a bool to the PhoneApplicationService, pass a Dictionary of bools, each one representing the state of a image:
var showImage = new Dictionary<int, bool>();
showImage[1] = true;
showImage[2] = false;
showImage[3] = true;
PhoneApplicationService.Current.State["showImage"] = showImage;
In class A, create a dictionary for your images:
private Dictionary<int, Image> _images = new Dictionary<int, Image>();
Then in its constructor, fill the dictionaries with your Images:
InitializeComponent();
_images[1] = YourImage1;
_images[2] = YourImage2;
_images[3] = YourImage3;
In class A's OnNavigatedTo, do:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
if (PhoneApplicationService.Current.State.ContainsKey("showImage"))
{
var showImage = PhoneApplicationService.Current.State["showImage"] as Dictionary<int, bool>;
if (showImage != null)
{
foreach (var key in showImage.Keys)
{
if (_images.ContainsKey(key))
{
if (showImage[key])
{
_images[key].Visibility = System.Windows.Visibility.Visible;
}
else
{
_images[key].Visibility = System.Windows.Visibility.Collapsed;
}
}
}
}
}
}
If you prefer, you can change the key of the dictionaries for a more representative string.
Hope it helps! :)
I am trying to store multiple values from numerous buttons so I can return values of two or more things e.g. if chocolate and vanilla clicked both prices and names can be returned. I will also need to make calculations on the data set later. Whenever I return the data only the most recent values return rather than all of those I have selected.
private void VanillaBtn_Click(object sender, RoutedEventArgs e)
{
items.Price = 450;
items.Name = "Vanilla"
}
private void ChocolateBtn_Click(object sender, RoutedEventArgs e)
{
items.Price = 500;
items.Name = "Chocolate";
}
This is my class, any help or tips would be appreciated.
class Items
{
private int thePrice;
private string theName;
public int Price
{
get
{
return thePrice;
}
set
{
thePrice = value ;
}
}
public string Name
{
get
{
return theName;
}
set
{
theName = value;
}
}
Keep a list of whatever was clicked.
private List<Items> selectedItems = new List<Items>();
So, every time something is clicked, you store the object in the list defined above.
private void VanillaBtn_Click(object sender, RoutedEventArgs e)
{
var newItem = new Items();
newItem.Price = 450;
newItem.Name = "Vanilla";
selectedItems.Add(newItem);
}
I am having this very strange problem where i am creating a list of some objects in one class then trying to access it in another class but it's coming empty in other class:
My first class where i am populating the list:
namespace dragdrop
{
struct BR
{
private string var;
public string Var
{
get { return var; }
set { var = value; }
}
private string equalsTo;
public string EqualsTo
{
get { return equalsTo; }
set { equalsTo = value; }
}
private string output;
public string Output
{
get { return output; }
set { output = value; }
}
private string els;
public string Els
{
get { return els; }
set { els = value; }
}
private string elsOutput;
public string ElsOutput
{
get { return elsOutput; }
set { elsOutput = value; }
}
}
public partial class Form1 : Form
{
//******************
private List<BR> list = new List<BR>(); //This is the list!
//******************
internal List<BR> List
{
get { return list; }
set { list = value; }
}
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string[] vars = new string[] { "Name", "Gender", "Age", "Address", "email" };
comboBox1.DataSource = vars;
}
private void button1_Click(object sender, EventArgs e)
{
BR b = new BR();
b.Var = comboBox1.SelectedItem.ToString();
b.EqualsTo = textBox1.Text;
b.Output = textBox2.Text;
list.Add(b);
//*****************
textBox1.Text = List.Count.ToString(); //This gives the correct count value!
//*****************
//this.Close();
}
}
}
I am accessing it in second class like:
namespace dragdrop
{
public partial class Ribbon1
{
private void Ribbon1_Load(object sender, RibbonUIEventArgs e)
{
}
private void button1_Click(object sender, RibbonControlEventArgs e)
{
Form1 form = new Form1();
List<BR> l = form.List; ;
//*******************
MessageBox.Show(form.List.Count.ToString()); //This strangely gives count 0!
//*******************
}
}
}
I have even tried making everything public in first class but no matter what i do, im always getting empty list in second class.
The is no relation what-so-ever between Form1 and Ribbon1, how can one then access an instance of the other?
With this:
Form1 form = new Form1(); // new instance of Form1
List<BR> l = form.List; ; // of course the list is empty in a new instance!
you can never access values from another instance of Form1.
Since I have no idea how your classes are connected I cannot give you more advice than have a look at this good overview of OO-relationships. You have to connect them somehow for it to work, I would very much recommend composition // aggregation (same thing, different schools).
All i needed to do was make the list a static member in class one, that solved the issue of having different value when i tried to create a new instance of Form1 in Ribbon1 class.
private static List<BR> list = new List<BR>();
I am just learning about events, delegates and subscribers. I've spent the last 2 days researching and wrapping my brain around it all. I am unable to access the information being passed in my EventArgs e value. I have a saved project that wants to be opened. The state of the necessary forms are deserialized into a dictionary. A loop is hit that raises the UnpackRequest passing the key/value with it.
ProjectManager.cs file:
public delegate void EventHandler<TArgs>(object sender, TArgs args) where TArgs : EventArgs;
public event EventHandler<UnpackEventArgs> UnpackRequest;
Then farther down:
ProjectManager.cs file:
//Raise a UnpackEvent //took out virtual
protected void RaiseUnpackRequest(string key, object value)
{
if (UnpackRequest != null) //something has been added to the list?
{
UnpackEventArgs e = new UnpackEventArgs(key, value);
UnpackRequest(this, e);
}
}
Then within the open method, after dictionary gets populated with states of each form:
ProjectManager.cs file:
foreach (var pair in dictPackState) {
string _key = pair.Key;
dictUnpackedState[_key] = dictPackState[_key];
RaiseUnpackRequest(pair.Key, pair.Value); //raises the event.
}
I have a class for the Event:
public class UnpackEventArgs : EventArgs
{
private string strKey;
private object objValue;
public UnpackEventArgs(string key, object value)
{
this.strKey = key;
this.objValue = value;
}
//Public property to read the key/value ..and get them out
public string Key
{
get { return strKey; }
}
public object Value
{
get { return objValue; }
}
}
I am still working on the code to add subscribers and how the project components get re-constituted in the individual forms. But the part I'm trying to work on now is in the MainForm.cs where I handle the Unpacked Request using the arguements getting passed. My e contains the key values and the key represents where to send the value (which is the form object).
private void HandleUnpackRequest(object sender, EventArgs e)
{
//reflection happens here. turn key into object
//why can't i get e.key ???
object holder = e; //holder = VBTools.UnpackEventArgs key... value...all info
//object goToUnpack = (e.key).GetType();
//goToUnpack.unpackState(e.value);
}
I think I included all the necessary parts to get any help?! THANKS!
Change this:
private void HandleUnpackRequest(object sender, EventArgs e)
To this:
private void HandleUnpackRequest(object sender, UnpackEventArgs e)
Remember your event handler declaration:
public event EventHandler<UnpackEventArgs> UnpackRequest;
The follwing code works well working for lvwResult, but how can I display the results in listbox1?
I just want to use listbox1 only, instead of lvwResult.
private void btnBrowse_Click(object sender, System.EventArgs e)
{
folderBrowserDialog1.ShowDialog();
if (folderBrowserDialog1.SelectedPath != "")
{
txtDirectory.Text = folderBrowserDialog1.SelectedPath;
}
}
private void btnClose_Click(object sender, System.EventArgs e)
{
this.Close ();
}
private void btnSearchNow_Click(object sender, System.EventArgs e)
{
MLSecurityFinder lSecFinder = new MLSecurityFinderClass ();
int iCounter = 0;
lvwResult.Items.Clear ();
lSecFinder.bScanSubDirectories = chkSubfolders.Checked;
try
{
lSecFinder.FindSecurity (txtSymbol.Text, txtDirectory.Text);
while (lSecFinder.bSecLeft)
{
ListViewItem lItem = lvwResult.Items.Insert (iCounter, lSecFinder.SecName);
lItem.SubItems.Add (lSecFinder.SecSymbol);
lItem.SubItems.Add (lSecFinder.SecFileName);
lSecFinder.FindNextSecurity();
iCounter++;
}
}
catch (System.Runtime.InteropServices.COMException ComEx)
{
//MessageBox.Show (ComEx.Message);
}
finally
{
lSecFinder.DestroySearchDialog ();
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
List boxes don't support multiple columns, unless you're planning on owner-drawing your listbox items. So you'll need to start by deciding how you're going to map your old multi-column data to a single string. Let's say, for the sake of argument, that you decide to combine the used-to-be-columns with commas, so that each of your listbox items would look like "SecName,SecSymbol,SecFileName".
That's the only part that's likely to be at all mysterious. From here, it's just like solving any other problem. You want to replace usages of lvwResult with usages of listbox1? Sounds like a job for search-and-replace to me. Then fix whatever doesn't compile. The code that builds your columns (SubItems) definitely won't compile, but by this point, you will have already decided what to do with that, so it's just a matter of writing code.
Here is just a sample on adding items to the listbox.
public class SampleData {
public string Name { get; set; }
public int Id { get; set; }
}
Now you have the code of:
List<SampleData> sampleList = new List<SampleData>() {
new SampleData() { Id = 1, Name = "Peyton" }
};
listBox1.DataSource = sampleList;
listBox1.DisplayMember = "Name";
Or you can have it directly using the items property.
listBox1.Items.Add(new SampleData() { Id = 1, Name = "Sample" });
listBox1.DisplayMember = "Name";