I know this is asked before, but I can't seem to figure it out.
I have a class which makes a list from a datagridview. I want to do stuff with this list in another class but I cant't access it. I can access it from Form1.cs like the code underneath. How do I access the list from a random class like I can in Form1.cs?
//Opens the file dialog and assigns file path to Textbox
OpenFileDialog browseButton = new OpenFileDialog();
private void browse_Click(object sender, EventArgs e)
{
browseButton.Filter = "Excel Files |*.xlsx;*.xls;*.xlsm;*.csv";
if (browseButton.ShowDialog() == DialogResult.OK)
{
ExcelPath.Text = browseButton.FileName;
fileExcel = ExcelPath.Text;
//SetAttributeValue(ExcelPath, fileExcel);
//nylp();
/*
////IMPORTERER 10TAB-DATA FRA EXCEL TIL DATAGRIDVIEW////
tenTabLine.fileExcel = fileExcel;
tenTabLine.tenTab(tenTabDgv);
*/
////IMPORTERER NYLPDATA TIL DATAGRIDVIEW////
nylpLine.fileExcel = fileExcel;
nylpLine.nylpData(nylpDgv);
////TAR DATA I NYLPDGV DATAGRIDVIEW OG BEREGNER VERTIKALE ELEMENTER////
vertElementer.vertBueDGV(nylpDgv, vertElementerDgv);
GetVertElementasList getList = new GetVertElementasList();
var TEST = getList.vertList(vertElementerDgv);
MessageBox.Show(TEST[5].p2.ToString());
}
else return;
}
When I try to do something like this I get lot of errors in Error List:
class GetKoord
{
GetVertElementasList getList = new GetVertElementasList();
var TEST = getList.vertList(vertElementerDgv);
MessageBox.Show(TEST[5].p2.ToString());
}
This is my list class
class GetVertElementasList
{
private List<vertEl> vertElementList = new List<vertEl>();
public List<vertEl> vertList(DataGridView VertElementer)
{
for (int i = 0; i<VertElementer.Rows.Count - 1; i++)
{
vertElementList.Add(new vertEl
{
elNr = (int)VertElementer.Rows[i].Cells[0].Value,
p1 = (double)VertElementer.Rows[i].Cells[1].Value,
p2 = (double)VertElementer.Rows[i].Cells[2].Value,
z1 = (double)VertElementer.Rows[i].Cells[3].Value,
z2 = (double)VertElementer.Rows[i].Cells[4].Value,
heln1 = Convert.ToDouble(VertElementer.Rows[i].Cells[5].Value),
heln2 = (double)VertElementer.Rows[i].Cells[6].Value
});
}
return vertElementList;
}
}
public class vertEl
{
private int _elNr;
private double _p1;
private double _p2;
private double _z1;
private double _z2;
private double _nylpRad;
private double _heln1;
private double _heln2;
public int elNr
{
get { return _elNr; }
set { _elNr = value; }
}
public double p1
{
get { return _p1; }
set { _p1 = value; }
}
public double p2
{
get { return _p2; }
set { _p2 = value; }
}
public double z1
{
get { return _z1; }
set { _z1 = value; }
}
public double z2
{
get { return _z2; }
set { _z2 = value; }
}
public double nylpRad
{
get { return _nylpRad; }
set { _nylpRad = value; }
}
public double heln1
{
get { return _heln1; }
set { _heln1 = value; }
}
public double heln2
{
get { return _heln2; }
set { _heln2 = value; }
}
}
EDIT:
I've made it work now except that I get a out of range exception.
class code is:
class GetKoord
{
public GetVertElementasList getList = new GetVertElementasList();
BridgGeometry obj = new BridgGeometry();
public void foo()
{
var TEST = getList.vertList(obj.vertElementerDgv);
MessageBox.Show(TEST[2].elNr.ToString());
}
}
In form1 or BridgGeometry as it is called in my project I have which is giving me out of range exception.
GetKoord getZ = new GetKoord();
getZ.foo();
EDIT2:
The code underneath works and gives a message box with some value in list. But the method foo() in class above gives a out of range error.
private void browse_Click(object sender, EventArgs e)
{
browseButton.Filter = "Excel Files |*.xlsx;*.xls;*.xlsm;*.csv";
if (browseButton.ShowDialog() == DialogResult.OK)
{
////TESTING////WORKING CODE AND GIVES A MESSAGEBOX WITH VALUE
GetVertElementasList getVertList = new GetVertElementasList();
var TEST = getVertList.vertList(vertElementerDgv);
MessageBox.Show(TEST[2].elNr.ToString());
}
else return;
}
I think you are trying to access the variable directly in the class; which will not work. Try following
class GetKoord
{
GetVertElementasList getList = new GetVertElementasList();
public void foo()
{
var TEST = getList.vertList(vertElementerDgv);
MessageBox.Show(TEST[5].p2.ToString());
}
}
I tested your code and it seemed to worked. My code for you and #Anand
No Errors, except for empty Lists. But thats because I didn't fed it any information. So, there shouldn't be a problem.
#Grohl maybe try my code and comment where the error is displayed. This should be the most easy way to find the problem.
TestClass which represents class GetKoord
namespace TestForm
{
class TestClass
{
public TestClass()
{
DataGridView tmp = new DataGridView();
GetVertElementasList getList = new GetVertElementasList();
var TEST = getList.vertList(tmp);
MessageBox.Show(TEST[5].p2.ToString());
}
}
}
The GetVertElementasList
namespace TestForm
{
class GetVertElementasList
{
private List<vertEl> vertElementList = new List<vertEl>();
public List<vertEl> vertList(DataGridView VertElementer)
{
for (int i = 0; i < VertElementer.Rows.Count - 1; i++)
{
vertElementList.Add(new vertEl
{
elNr = (int)VertElementer.Rows[i].Cells[0].Value,
p1 = (double)VertElementer.Rows[i].Cells[1].Value,
p2 = (double)VertElementer.Rows[i].Cells[2].Value,
z1 = (double)VertElementer.Rows[i].Cells[3].Value,
z2 = (double)VertElementer.Rows[i].Cells[4].Value,
heln1 = Convert.ToDouble(VertElementer.Rows[i].Cells[5].Value),
heln2 = (double)VertElementer.Rows[i].Cells[6].Value
});
}
return vertElementList;
}
}
//Some other stuff
}
Last but not least. the code from the button click event:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void simpleButton1_Click(object sender, EventArgs e)
{
DataGridView tmp = new DataGridView();
GetVertElementasList getList = new GetVertElementasList();
var TEST = getList.vertList(tmp);
MessageBox.Show(TEST[5].p2.ToString());
TestClass tmpClass = new TestClass();
}
}
To #Grohl EDIT2:
It hurts to see that you are trying to read data without checking if there is any. In such cases, check!
Like this:
if(TEST.Count() >= 3)
{
MessageBox.Show(TEST[2].elNr.ToString());
}
It should debug at be smooth at runtime. I think your problem is getting the data.
Make sure you load the needed data and check if it isn't null.
Related
I am making a program which will test if an airplane is allowed to fly or not. It's my very first personal project using Windows Form and C#. I made a lot of progress, however, I am having a huge problem with a feature I want to have. I have two forms called Main & FlightSetup and the second form uses a class called AircraftClass which contains constructors, behaviours, and properties.
PROBLEM
I will try to make it simple and understandable. I am calling class AircraftClass inside public void addaircraftButton_Click to make an object and store all necessary details like aircraftModel,airlineName, etc. However, I have a ListBox called aircraftList which shows only the aircraft name. The idea is to display all that data/details depending on what the user selects from the aircraftList inside a TextBox called detailsList (yes, I called it like that, but it's a textbox). This is when the issue happens, it is not displaying the correct information, and it's showing the properties value for AircraftClass
NOTES
aircraftList & detailsList are inside Main Form - I do know that there are some obvious mistakes here, but I am still learning, please go easy on me :(
Variables Inside Main Form
int planeCount = 0; int tailNumber = 0; int planeIndex;
string planeModel = "NONE"; string airline = "NONE";
double distanceM = 0.0; double fuelG = 0.0; double maxKG = 0.0; double totalKG = 0.0;
int passengers= 0; int bag1=0; int bag2 = 0;
Main Code (Only addbuttom method)
public void addaircraftButton_Click(object sender, EventArgs e)
{
FlightSetup addAircraft = new FlightSetup(); //CREATES INFO INSIDE DETAILS
string nl = "\r\n";
using (addAircraft)
{
DialogResult result = addAircraft.ShowDialog();
planeModel = addAircraft.planeModel_textbox.Text;
airline = addAircraft.airline_textbox.Text;
tailNumber = int.Parse(addAircraft.tailno_textbox.Text);
passengers= int.Parse(addAircraft.passengerTextBox.Text);
bag1 = int.Parse(addAircraft.carryonTextBox.Text);
bag2= int.Parse(addAircraft.checkedBagsTextBox.Text);
distanceM = double.Parse(addAircraft.distance_textbox.Text);
fuelG = double.Parse(addAircraft.fuel_textbox.Text);
maxKG = double.Parse(addAircraft.maxweight_textbox.Text);
AircraftDetails test = new AircraftDetails(planeModel,airline,tailNumber,passengers,bag1,bag2,distanceM,fuelG,maxKG,totalKG);
test.AircraftModel = addAircraft.planeModel_textbox.Text;
MessageBox.Show("Flight Setup is COMPLETED! \n\nPerfom Unit Testing For Take-Off Permission", "FLIGHT SAVED!");
planeCount++;
noaircraft_label.Text = planeCount.ToString();
aircraftList.Items.Add(planeModel + " - REGULAR ROLE");
}
}
Main Code (Only aircraftList method)
public void aircraftList_SelectedIndexChanged(object sender, EventArgs e) //PENDING SOLUTION
{
AircraftDetails getData = new AircraftDetails();
StringBuilder insertData = new StringBuilder(String.Empty);
string nl = "\r\n";
planeIndex = aircraftList.SelectedIndex;
if (planeIndex > -1)
{
insertData.Append(getData.AircraftModel.ToString());
insertData.Append(nl);
detailsList.Text = insertData.ToString();
}
}
AircraftClass Code
{
public class AircraftDetails
{
string aircraftModel = "UNKNOWN";
string airlineName = "UNKNOWN";
int id = 0; //not in use
int tailNumber = 0;
int passengerNo = 0;
int carrybag = 0;
int checkbag = 0;
double distance = 0.0;
double fuel = 0.0;
double mWeight = 0.0;
double totalWeight = 0.0;
int errorCount = 0;
//Constructors
public AircraftDetails()
{
aircraftModel = "UNKNOWN";
airlineName = "UNKNOWN";
id = 0;
tailNumber = 0;
passengerNo = 0;
carrybag = 0;
checkbag = 0;
distance = 0.0;
fuel = 0.0;
mWeight = 0.0;
totalWeight = 0.0;
}
public AircraftDetails(string aircraftModel, string airlineName, int tailNumber, int passengerNo, int carrybag, int checkbag, double distance, double fuel, double mWeight, double totalWeight)
{
this.aircraftModel = aircraftModel;
this.airlineName = airlineName;
this.tailNumber = tailNumber;
this.passengerNo = passengerNo;
this.carrybag = carrybag;
this.checkbag = checkbag;
this.distance = distance;
this.fuel = fuel;
this.mWeight = mWeight;
this.totalWeight = totalWeight;
}
//BEHAVIOUR
public override string ToString()
{
if (this.passengerNo >= 1)
return "Aircraft: " + aircraftModel + "\r\n Tail Number:" + tailNumber + "\r\nOperator: " + airlineName + "\r\nAircraft: " + "\r\nFlight Distance: " + distance + "\r\nFuel: " + fuel +
"\r\nMax Weight Allowed: " + mWeight + "\r\nTotal Weight: " + totalWeight + "\r\nPassengers: "+passengerNo+ "\r\nCarry-On Bags: "+carrybag+ "\r\nChecked Bags: "+checkbag;
else
{
errorCount++;
return "Passengers were less than 0\r\nIt means error was recorded\r\nError Count: "+errorCount;
}
}
//Properties
public string AircraftModel
{
get { return aircraftModel; }
set { aircraftModel = value; }
}
public string Airline
{
get { return airlineName; }
set { airlineName = value; }
}
public int TailNumber
{
get { return tailNumber; }
set { tailNumber = value; }
}
public int PassengerNo
{
get { return passengerNo; }
set { passengerNo = value; }
}
public int OnBoardBags
{
get { return carrybag; }
set { carrybag = value; }
}
public int CheckedBags
{
get { return checkbag; }
set { checkbag = value; }
}
public double FlightDistance
{
get { return distance; }
set { distance = value; }
}
public double Fuel
{
get { return fuel; }
set { fuel = value; }
}
public double MaxWeight
{
get { return mWeight; }
set { mWeight = value; }
}
}
}
Your question is how to display details from an object to a TextBox.
I see in your code that you've done a good job of overriding the ToString method. In a sense, you answered your own question because that's what it takes!
But let's try and boil all that code into a minimal reproducible example that will include data binding as Jimi so rightly recommended. The bare bones of our bindable class has this override:
// Minimal example of a class
class AircraftDetails : INotifyPropertyChanged
{
public override string ToString()
{
List<string> builder = new List<string>();
builder.Add($"{Airline} {Flight}");
builder.Add($"FlightStatus: {FlightStatus}");
builder.Add($"{OnboardBags} bags onboard");
builder.Add($"{CheckedBags} bags checked");
builder.Add($"Total bags: {TotalBags}");
builder.Add($"Fuel onboard: {Fuel.ToString("F2")}");
return string.Join(Environment.NewLine, builder);
}
.
.
.
public event PropertyChangedEventHandler? PropertyChanged;
}
Next, write the main form code to display details from an object to a TextBox.
One salient point is that ToString() can just be called on object because it's virtual.
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
buttonShowObjectInTextbox.Click += onButtonShowObjectInTextbox;
}
private void onButtonShowObjectInTextbox(object? sender, EventArgs e)
{
// For demonstration purposes, make an object.
// (Make sure parameterless constructor `AircraftDetails(){ }` is present)
object o = new AircraftDetails
{
Flight = "UA2907",
Airline = Airline.United,
Fuel = 50000,
OnboardBags = 237,
CheckedBags = 500,
};
textBoxMultiline.Text = o.ToString();
}
}
Your question also states I have a ListBox called aircraftList....
When a listbox is bound to BindingList<AircraftDetails> you can choose a property of your AircraftDetails class to show as the DisplayMember property.
Add code to the main form's Load event to set up the data source and the ListBox:
public partial class MainForm : Form
{
.
.
.
BindingList<AircraftDetails> Details = new BindingList<AircraftDetails>();
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
aircraftDetails.DataSource = Details;
aircraftDetails.DisplayMember = nameof(AircraftDetails.Flight);
aircraftDetails.SelectedIndexChanged += onAircraftDetailsSelection;
// Add a few flights
Details.Add(new AircraftDetails
{
Flight = "UA6026",
Airline = Airline.United,
Fuel = 45250,
OnboardBags = 155,
CheckedBags = 97,
});
Details.Add(new AircraftDetails
{
Flight = "UA8888",
Airline = Airline.United,
Fuel = 27620,
OnboardBags = 301,
CheckedBags = 134,
});
Details.Add(new AircraftDetails
{
Flight = "WN8610",
Airline = Airline.Southwest,
Fuel = 200,
OnboardBags = 5,
CheckedBags = 614,
});
aircraftDetails.SelectedIndex = -1;
}
In response to selection changes, call this method to show object in textbox:
private void onAircraftDetailsSelection(object? sender, EventArgs e)
{
if(aircraftDetails.SelectedItem != null)
{
textBoxMultiline.Text = aircraftDetails.SelectedItem.ToString();
}
}
}
so what i would like to is setting back some attributes after an Custom Event is finished.
Scenario i have a save BackupDrives Class that does collection of data and then offers a Event to be called after its done.
Changing object properties can be done by button click, what i would like is to set them back to the same value after the event is finished.
Button click does the thing :
private void bbdrives_Click(object sender, RoutedEventArgs e)
{
backup.SaveDrives += OnSavingDrives;
backup.DrivesSave();
Drive_text.Visibility = Visibility.Visible;
drives_progres.Visibility = Visibility.Visible;
drives_progres.IsIndeterminate = true;
}
Now the triggered event method is not able to change the properties back.
private void OnSavingDrives(object sender, DrivesEventArgs e)
{
Directory.CreateDirectory(....);
File.WriteAllLines(e.Something, e.List2ToSave);
File.WriteAllLines(e.Something_lse, e.List1ToSave);
Drive_text.Visibility = Visibility.Collapsed;
drives_progres.Visibility = Visibility.Collapsed;
drives_progres.IsIndeterminate = false;
}
How do i do this. Since this does not work.
And on other thig here to - when i run the GUI i need to click 2 times one the same button to start it all. Done Code Clean + Rebuild. Still the same.
---EDIT---
As for code here you go.
This is a Class for collecting method and event.
public class DrivesEventArgs : EventArgs
{
string MYDOC = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
const string backup_Drives = "....";
const string backup_Letters = "...";
public List<string> List1ToSave = new List<string>();
public List<string> List2ToSave = new List<string>();
public string SAVE_DRIVE_Letter
{
get
{
string name = Path.Combine(MYDOC, backup_Letters);
return name;
}
}
public string SAVE_DRIVE_Path
{
get
{
string name = Path.Combine(MYDOC, backup_Drives);
return name;
}
}
}
public class DrivesBackup
{
private const string path = "Network";
private List<string> drives_to_save = new List<string>();
private List<string> letters_for_drives = new List<string>();
private RegistryKey reg1, reg2;
public event EventHandler<DrivesEventArgs> SaveDrives;
public void DrivesSave()
{
var data = new DrivesEventArgs();
try
{
if (drives_to_save.Count == 0)
{
reg1 = Registry.CurrentUser.OpenSubKey(path);
string[] mounted_drives = reg1.GetSubKeyNames();
foreach (var drive in mounted_drives)
{ //get all UNC Paths from mounted_drives
string[] getUNC = { path, drive };
string fullUNC = Path.Combine(getUNC);
reg2 = Registry.CurrentUser.OpenSubKey(fullUNC);
string UNCPath = reg2.GetValue("RemotePath").ToString(); //getting UNC PATH
Console.WriteLine(UNCPath);
data.List1ToSave.Add(drive.ToString());
data.List2ToSave.Add(UNCPath);
OnSaveDrives(data);
}
}
}
catch (Exception er)
{
throw er;
}
}
protected virtual void OnSaveDrives(DrivesEventArgs eD)
{
SaveDrives?.Invoke(this, eD);
}
Now here is the MAINWINDOW WPF
public partial class MainWindow : Window
{
DrivesBackup backup = new DrivesBackup();
public MainWindow()
{
InitializeComponent();
}
private void bbdrives_Click(object sender, RoutedEventArgs e)
{
backup.DrivesSave();
backup.SaveDrives += OnSavingDrives;
Drive_text.Visibility = Visibility.Visible;
drives_progres.Visibility = Visibility.Visible;
drives_progres.IsIndeterminate = true;
}
private void OnSavingDrives(object sender, DrivesEventArgs e)
{
Directory.CreateDirectory(System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), #"SEG-Backup"));
File.WriteAllLines(e.SAVE_DRIVE_Path, e.List2ToSave);
File.WriteAllLines(e.SAVE_DRIVE_Letter, e.List1ToSave);
Drive_text.Visibility = Visibility.Collapsed;
drives_progres.Visibility = Visibility.Collapsed;
drives_progres.IsIndeterminate = false;
}
}
Now i do hope this would make some things more clear.
Everything works fine until I actually call the SetPicture() Method. Any ideas as to why the image will not display when the selected item is changed. Right now i only have one image preset until i figure out my problem. Thanks for any help
namespace CelestialWindowsApp
{
public partial class Form1 : Form
{
public static List CelestialLibrary = new List(); private static CelestialBody celestialBody; private static string name; private static string description; private static string image; public static CelestialBody NewPlanet { get { return celestialBody; } set { celestialBody = value; } }
public Form1()
{
InitializeComponent();
PopulateLibrary();
}
public void PopulateLibrary()//Runs when the Form 1 is loaded. Adds preset item into the ListNox.
{
CelestialLibrary = new List<CelestialBody>();
CelestialBody cb1 = new CelestialBody("Earth", "Our Home", #"C:\Users\Cassidy\documents\visual studio 2015\Projects\CelestialWindowsApp\CelestialWindowsApp\ImageResources\earthimage.jpg");
CelestialBody cb2 = new CelestialBody("Mars", "4th planet from the sun.");
CelestialBody cb3 = new CelestialBody("Venus", "2nd planet from the son");
CelestialLibrary.Add(cb1);
CelestialLibrary.Add(cb3);
lbLibrary.DataSource = CelestialLibrary;
foreach (var p in CelestialLibrary)
{
lbLibrary.DisplayMember = "ShowBodies";
}
}
public void AddItem() // Adds the new Item to my library and then adds to and updates the ListBox;
{
CelestialBody cb;
name = txtboxName.Text;
description = txtboxDescription.Text;
image = txtboxImagePath.Text;
cb = new CelestialBody(name, description, image);
CelestialLibrary.Add(cb);
MessageBox.Show(name + " has been added to the Library.");
txtboxName.Text = null;
txtboxDescription.Text = null;
lbLibrary.DataSource = null;
lbLibrary.DataSource = CelestialLibrary;
lbLibrary.DisplayMember = "ShowBodies";
}
public void DisplayItemInfo()//Displays the current selected item information.
{
List<CelestialBody> bodyList = (List<CelestialBody>)lbLibrary.DataSource;
CelestialBody currentItem = bodyList[lbLibrary.SelectedIndex];
foreach (CelestialBody cb in bodyList)
{
if (currentItem.MyId == cb.MyId)
celestialBody = new CelestialBody(cb.Name, cb.Description, cb.ImagePath);
{
txtboxItemInfo.Text = celestialBody.Description;
SetPicture(celestialBody.ImagePath);
}
}
}
public void SetPicture(string image)
{
if (picboxBodyImage.Image != null)
{
picboxBodyImage.Image.Dispose();
}
picboxBodyImage.ImageLocation = image;
}
private void btnAddNewBody_Click(object sender, EventArgs e)
{
AddItem();
}
private void lbLibrary_SelectedIndexChanged(object sender, EventArgs e)
{
DisplayItemInfo();
}
}
}
Did you check the path in variable image. Assuming path is correct, Try below
picboxBodyImage.Image = Image.FromFile(image);
I want to show the attributes of an object when I click on a button in Windows Forms using c# and I don't know how to do it. Part of my code looks like this until now. I'm a beginner in c#.
class Pizza: ICloneable
{
private string nume;
private int nrIngrediente;
private string[] ingrediente;
public Pizza()
{
nume = "Margherita";
nrIngrediente = 2;
ingrediente = new string[nrIngrediente];
for (int i = 0; i < nrIngrediente; i++)
{
ingrediente[0] = "Sos rosii";
ingrediente[1] = "Mozzarella";
}
}
public Pizza(string den, int nri, string[] ing)
{
nume = den;
nrIngrediente = nri;
ingrediente = new string[nrIngrediente];
for (int i = 0; i < nrIngrediente; i++)
ingrediente[i] = ing[i];
}
public Pizza(Pizza p)
{
nume = p.nume;
nrIngrediente = p.nrIngrediente;
ingrediente = new string[nrIngrediente];
for (int i = 0; i < nrIngrediente; i++)
ingrediente[i] = p.ingrediente[i];
}
public string PizzaName
{
get { return nume; }
set { nume = value; }
}
public int PizzaNrIng
{
get { return nrIngrediente; }
set { nrIngrediente = value; }
//also, i don't know how to write the getter and setter for this one
public string PizzaIngredients
//{
// get
// {
// for(int i=0;i<nrIngrediente;i++)
// return ingrediente[i];
// }
// set { ingrediente = value; }
//}
And now, the form code is the following(note that i designed it already):
public partial class ListaPizza : Form
{
public ListaPizza()
{
InitializeComponent();
}
private void Margherita_Click(object sender, EventArgs e)
{
string[] ingrMargh = new string[2] { "Sos rosii", "Mozzarella" };
Pizza Margherita = new Pizza("Margherita", 2, ingrMargh);
//Show(Margherita);
//here i want the object created above to be shown in a messagebox when i click the button in the form but i don't know how
}
}
Thank you!
MessageBox.Show();
has to be a string value so any parts of your object that is not a string will need the .ToString() method
Or if you want to customize the view you could pass the object to a new form and create a whole nice layout for it with the designer.
You can set the getter and setter in below way.
public string PizzaIngredients
{
get
{
return String.Join(",",nringrediente);
}
set
{
nringrediente = value.Split(',');
}
}
And Show(Margherita); can be implemented like in Pizza Class :
public string GetDisplayMessageForPizza()
{
return "My Pizza is " + nume + ". It contains " + nringrediente + " ingredients : " + PizzaIngredients;
}
And in form ListaPizza :
private void Margherita_Click(object sender, EventArgs e)
{
string[] ingrMargh = new string[2] { "Sos rosii", "Mozzarella" };
Pizza Margherita = new Pizza("Margherita", 2, ingrMargh);
MessageBox.Show(Margherita.GetDisplayMessageForPizza());
}
As for the getter - you should return an array of strings, not just a string:
public string[] PizzaIngredients
{
get
{
ingrediente;
}
set
{
ingrediente = value;
}
}
As for the showing - just use MessageBox.Show():
MessageBox.Show(string.Format("{0} {1}", Margherita.Name, Margherita.nrIngrediente));
Property grid do not show new value of selected object.
For example:
o.val = "1";
pg.SelectedObject = o;
o.val = "2";
pg.Refresh();
The property in property grid is still "1";
It is changing only if you click on this property.
Or like that:
o.val = "1";
pg.SelectedObject = o;
o.val = "2";
pg.SelectedObject = o;
but in this case focus will be changed to PropertyGrid.
As I told you in my comment, your code is not enough to understand your issue. Presented like this it should work. Here is mine that works well:
public class Target
{
private int _myInt = 1;
public int MyInt { set; get; }
public static Target target = new Target();
}
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Button button = new Button()
{
Text = "Click me",
Dock = DockStyle.Bottom
};
Form form = new Form
{
Controls = {
new PropertyGrid {
SelectedObject = Target.target,
Dock = DockStyle.Fill,
},
button
}
};
button.Click += new EventHandler(button_Click);
Application.Run(form);
}
static void button_Click(object sender, EventArgs e)
{
Target.target.MyInt = 2;
Form form = Form.ActiveForm;
(form.Controls[0] as PropertyGrid).Refresh();
}
}
The call to Refresh() actually rebuilds the grid. Remove it and you will see the change only when you click the property.
Cause you just not gave some code, here is a working example.
Just put a Button and a PropertyGrid onto a form.
using System;
using System.ComponentModel;
using System.Windows.Forms;
namespace WindowsFormsApplication
{
public partial class FormMain : Form
{
Random rand;
MyObject obj;
public FormMain()
{
InitializeComponent();
rand = new Random();
obj = new MyObject();
propertyGrid1.SelectedObject = obj;
}
private void button1_Click(object sender, EventArgs e)
{
obj.MyValue = rand.Next();
obj.IsEnabled = !obj.IsEnabled;
obj.MyText = DateTime.Now.ToString();
propertyGrid1.Refresh();
}
}
public class MyObject : INotifyPropertyChanged
{
private int _MyValue;
public int MyValue
{
get
{
return _MyValue;
}
set
{
_MyValue = value;
NotifyPropertyChanged("MyValue");
}
}
private string _MyText;
public string MyText
{
get
{
return _MyText;
}
set
{
_MyText = value;
NotifyPropertyChanged("MyText");
}
}
private bool _IsEnabled;
public bool IsEnabled
{
get
{
return _IsEnabled;
}
set
{
_IsEnabled = value;
NotifyPropertyChanged("IsEnabled");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
}
}