nested unit of work and making unwanted object - c#

I have 3 forms in my application : frmTrucks, frmEditTruck and frmEditContent.
frmTrucks shows my Trucks in a grid.
I add a truck, or choose one of the trucks from the grid to edit in frmEditTruck
public void Edit()
{
using (NestedUnitOfWork nuow = session.BeginNestedUnitOfWork())
{
Truck currentTruck = nuow.GetNestedObject(
xpcTruck[gvTruck.GetDataSourceRowIndex(gvTruck.FocusedRowHandle)])
as Truck;
using (frmEditTruck form = new frmEditTruck(currentTruck))
{
if (form.ShowDialog() == DialogResult.OK)
nuow.CommitChanges();
}
}
}
in frmEditTruck there are some text boxes for truck properties and two buttons.
btnSave and btnAddContent. btnSave saves the changes (now.CommitChanges();). btnAddContent's click code is :
Truck truck;
Session session;
public frmEditTruck(Truck truck)
{
InitializeComponent();
this.truck = truck;
this.session = truck.Session;
}
private void btnAddContent_Click(object sender, EventArgs e)
{
TContent content = new TContent(session);
using (frmEditTContent form = new frmEditTContent(content, truck))
{
if (form.ShowDialog() == DialogResult.OK)
truck.TContents.Add(content);
}
}
it shows frmEditContent. I can Add content to my truck. the problem is when I press AddContent and then cancel it. After that when I press the save button on my frmEditTruck it would add an empty row to my Content Table. I want to fix this problem. how can I fix it? I'm not sure my problem is clear enough for you. Please let me know
public class Truck : XPObject
{
.
.
.
[Association("Truck-TContents")]
public XPCollection<TContent> TContents { get { return GetCollection<TContent>("TContents"); } }
}
public class TContent : XPObject
{
.
.
.
private Truck truck;
[Association("Truck-TContents")]
public Truck Truck
{
get
{
return truck;
}
set
{
SetPropertyValue("Truck", ref truck, value);
}
}
}

private void btnAddContent_Click(object sender, EventArgs e)
{
TContent content = new TContent(session);
using (frmEditTContent form = new frmEditTContent(content, truck))
{
if (form.ShowDialog() == DialogResult.OK)
truck.TContents.Add(content);
}
}
I've changed the code to:
private void btnAddContent_Add(object sender, EventArgs e)
{
TContent content = new TContent(session);
using (frmEditTContent form = new frmEditTContent(content, truck))
{
if (form.ShowDialog() == DialogResult.OK)
{
truck.TContents.Add(content);
}
else
{
if (session.TrackingChanges)
session.RollbackTransaction();
}
}
}
and it works properly.

Related

ComboBox2 get fields in function of ComboBox1

I have to select one brand of moto. If i select "KTM", i want to get Ktm's motos. If i select "HVA", i want HVA's motos. Etc ..
I have a List of models with all models, and in function what i select, i want to add models by this brand and return this in my ComboBox2.
Modele.cs :
class Modele
{
public string NomModele;
public static List<Modele> lesModeles = new List<Modele>() {
// Husqvarna
new Modele() { NomModele = "TE"},
new Modele() { NomModele = "FE"},
// KTM
new Modele() { NomModele = "EXC"},
new Modele() { NomModele = "EXC-F"}
};
public Modele() { }
public Modele(string NomModele)
{
this.NomModele = NomModele;
}
}
Main.cs :
namespace SuiviEntretien
{
public partial class SuiviEntretien : Form
{
public SuiviEntretien()
{
InitializeComponent();
this.lesMarques.Items.AddRange(Marque.lesMarques.Select(x => x.NomMarque).ToArray());
this.lesModeles.Items.AddRange(Modele.lesModeles.Select(x => x.NomModele).ToArray());
}
private void SuiviEntretien_Load(object sender, EventArgs e)
{
}
private void SauvegarderMoto_Click(object sender, EventArgs e)
{
try
{
Moto maMoto = new Moto(
maMarque.Text = lesMarques.SelectedItem.ToString(),
monModele.Text = lesModeles.SelectedItem.ToString()
);
MessageBox.Show("Moto enregistrée avec succès !", "Information");
tabControl1.SelectTab(MaMoto);
}
catch(Exception)
{
MessageBox.Show("Il manque des informations !", "Information");
}
}
}
}
Thanks for further help.
The following answer has been made with some assumptions, those being:
-You have a ComboBox that contains values, when a value is selected another ComboBox needs to re-populate itself with a new list of data.
Depending on the scale of this problem I would recommend two solutions. Move your data into a relational database and access it accordingly, then populate your first ComboBox as a list of all main keys. (One to many methodology) then populate your second ComboBox according to the first ComboBox value.
Assuming you want to build your list dynamically and want to avoid a database then simply use functionality based on if the ComboBox changes.
private void ComboBox1_SelectedIndexChanged(object sender, EventArgs e) {
if (ComboBox1.Text == "KTM")
{
// Populate ComboBox2 with KTM data.
}
else
{
// Populate ComboBox2 with some other data.
}
}
This should help you out.

C# DataGridView ImageColumn

DataGridView Image Column is getting null when change the visibility of User Control that includes the dataGridView. Codes are below;
public partial class ReadingOrderListControl : UserControl
{
private Image Pending { get { return Image.FromFile(#"..\..\Resources\pending.png"); } }
private Image Completed { get { return Image.FromFile(#"..\..\Resources\completed.png"); } }
private void ReadingOrderListControl_Load(object sender, EventArgs e)
{
GetOrderList();
}
private void GetOrderList()
{
dgv_ReadingOrders.DataSource = DbManager.GetReadingOrders();
if (dgv_ReadingOrders.Rows[0].Cells["tamamlanma"].Value.ToString() == "1")
dgv_ReadingOrders.Rows[0].Cells["tamamlanma_image"].Value = Completed;
else
dgv_ReadingOrders.Rows[0].Cells["tamamlanma_image"].Value = Pending;
}
}
Try this:
if (dgv_ReadingOrders.Rows[0].Cells["tamamlanma"].Value.ToString() == "1")
dgv_ReadingOrders.Rows.Add(ID,...... , Bitmap.FromFile(Completed));
else
dgv_ReadingOrders.Rows.Add(ID,...... , Bitmap.FromFile(Pending));

How to pass data between WPF forms

I need help passing data from one WPF form to another. I have a main window with two other windows that will prompt the user for information. I want to end up with all the information in the first form so that I can store the data later on. The second form must return the Reservation and Room information when you click the OK button on the second form. The third form must return the Person information when you click OK.
public partial class MainWindow : Window
{
private string message;
public MainWindow()
{
InitializeComponent();
}
protected void Exit_Click(object sender, RoutedEventArgs e)
{
Application.Current.Shutdown();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
}
protected void Create_Reservation_Click(object sender, RoutedEventArgs e)
{
Reservation PersonReservation = new Reservation();//Create a reservation instance
Room PersonRoom = new Room(); //Create an instance of a room
Person myPerson = new Person();//Create an instance of a person
CreateResRoom createReservationRoom = new CreateResRoom();//Create a instance of the CreateReservation WPF Form
createReservationRoom.Show();
Here it is supposed to set the room, reservation and person instance that I created equil to their corresponding instances in the CreateResRoom class.
I think the problem lies here, because it keeps continuing before it opens the CreateResRoom form.
PersonRoom = createReservationRoom.myRoom;
PersonReservation = createReservationRoom.myReservation;
}
}
That was my first class, the second and third will follow.
public partial class CreateResRoom : Window
{
Person myPerson;
public CreateResRoom()
{
InitializeComponent();
myReservation = new Reservation();
myRoom = new Room();
myPerson = new Person();
}
public Room myRoom
{
get;
set;
}
public Reservation myReservation
{
get;
set;
}
private void btnCancel_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
private void btnOk_Click(object sender, RoutedEventArgs e)
{
myRoom.RoomBeds = txtHeadCount.Text;
myRoom.RoomNumber = 1;
myRoom.RoomPrice = 20;
myRoom.RoomType = cboRoomType.Text;
myReservation.ResEndDate = dpEnd.ToString();
myReservation.ResStartDate = dpStart.ToString();
CreateRes createReservation = new CreateRes();
createReservation.Show();
//I think the same problem lies here that is in the MainWindow.
myPerson = createReservation.myPerson;
this.Close();
}
}
And the last class follows:
public partial class CreateRes : Window
{
public Person myPerson
{
get;
set;
}
public CreateRes()
{
InitializeComponent();
myPerson = new Person();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
}
private void btnOk_Click(object sender, RoutedEventArgs e)
{
myPerson.FirstName = txtFName.Text;
myPerson.LastName = txtLName.Text;
myPerson.IdNumber = Convert.ToInt32(txtIdNumber.Text);
myPerson.PhoneNumber = Convert.ToInt32(txtPhoneNumber.Text);
myPerson.AddressCity = txtAddressCity.Text;
myPerson.AddressStreet = txtAddressStreet.Text;
myPerson.AddressProvince = txtAddressProvince.Text;
myPerson.AddressPostalCode = txtAddressPostalCode.Text;
this.Close();
}
private void btnCancel_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
}
Just make a overload constructor which takes parameters of the window in which you want to retrieve.
Example:
Suppose we want a user to login from our MainWindow( i.e Login Window ) and we want to pass an int ID / string Email to our second form to retrieve data of logging user.
Than We have to first overload our second wpf form constructor. You can either make default constructor to do this or make an overload constructor for this work.
SecondForm:
public secondForm()
{
//Your Default Constructor Logic
}
public secondForm(string email_ )
{
//Your Overload Constructor Logic
}
Now in MainWindow from where we are logging and passing our EMail
MainWindow:
public void btnLogin()
{
//On Success
SecondWindow sw = new SecondWindow(txtBoxEMail.Content);
sw.Show();
}
A pattern you can use for this sort of thing is to have each form be responsible for creating the instance on ok click and then provide the object via a property get.
public partial class SomeForm: Window
{
public SomeClass MyProperty { get; private set; }
private void btnOk_Click(object sender, RoutedEventArgs e)
{
this.MyProperty = new SomeClass();
//additional setter logic here
this.Close();
}
}
Then you would access it from a parent form like this (notice the use of ShowDialog() http://msdn.microsoft.com/en-us/library/system.windows.window.showdialog(v=vs.110).aspx for easy checking of whether ok was clicked or not).
protected void Create_Reservation_Click(object sender, RoutedEventArgs e)
{
SomeClass myObj;
SomeOtherClass myOtherObj;
SomeForm myForm = new SomeForm();
if(myForm.Show().Value)
{
myObj = myForm.MyProperty;
}
SomeOtherForm myOtherForm = new SomeOtherForm();
if(myOtherForm.ShowDialog().Value)
{
myOtherObj = myOtherForm.MyOtherProp;
}
//save myObj & myOtherObj or whatever you need to do with them
Use the "normal way", here is a short overview.
First create a Data Context:
public class DC_Reservation() : INotifyPropertyChanged {
protected Reservation _PersonReservation ;
public Reservation PersonReservation {
get { return _PersonReservation ; }
set {
_PersonReservation = value;
NotifyPropertyChanged("PersonReservation ");
}
}
protected Room _PersonRoom ;
public Room PersonRoom {
get { return _PersonRoom ; }
set {
_PersonRoom = value;
NotifyPropertyChanged("PersonRoom");
}
}
protected Person _myPerson ;
public Person myPerson {
get { return _myPerson ; }
set {
_myPerson = value;
NotifyPropertyChanged("myPerson ");
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged( string PropertyName ) {
if ( PropertyChanged != null ) {
PropertyChanged( this, new PropertyChangedEventArgs( PropertyName ) );
}
}
}
In the MainWindows you can assign and use the dataContext :
public partial class MainWindow : Window {
DC_Reservation dataContext {
get { return DataContext as DC_Reservation; }
}
private string message;
public MainWindow() {
InitializeComponent();
DataContext = new DC_Reservation();
}
protected void Create_Reservation_Click(object sender, RoutedEventArgs e) {
dataContext.PersonReservation = new Reservation();//Create a reservation instance
dataContext.PersonRoom = new Room(); //Create an instance of a room
dataContext.myPerson = new Person();//Create an instance of a person
CreateResRoom createReservationRoom = new CreateResRoom();//Create a instance of the CreateReservation WPF Form
// I'm not sure whether the next line is required.
createReservationRoom.DataContext = DataContext;
createReservationRoom.Show();
}
}
You can assign the DataContext in the constructor, but I think the better way is to define the DataContext in the MainWindow, in the other windows you can use the DesignContext:
<Window.DataContext>
<local:DC_Reservation />
</Window.DataContext>
So you can use the same DataContext over all forms ...
With DataBindings you can bind the input to the field:
<TextBox Text="{Binding FirstName, Path=myPerson, Mode=TwoWay}" />
I found another answer that Zarathos posted Jan 16 '13 at 21:43
for a different question
Use a public static class and access it from anywhere.
public static class Globals
{
public static String s_Name = "Mike"; //Modifiable in Code
public const int32 VALUE = 10; // unmodifiable
}
Then you can use it anywhere, provided you are working on the same namespace
string name = Globals.s_Name;

Datagrid not populating past headers

Thanks in advance for any help. I've been working with the tutorial listed here, but have run into an issue. I'm attempting to populate a datagrid in silverlight, but when I submit the button click, it will return the headers for columns but no data. I know data is in the system, so I'm confused why it's going to get the headers but not the actual data to populate. Code from my MainPage.xaml.cs and my data domain are below.
MainPage.xaml.cs
namespace SandCherryDemo
{
public partial class MainPage : UserControl
{
private SandCherryViewContext _sandCherryContext = new SandCherryViewContext();
public MainPage()
{
InitializeComponent();
}
private void StatusButton_Click(object sender, RoutedEventArgs e)
{
StatusButton.IsEnabled = false;
LoadOperation<SandCherryView> loadOp = this._sandCherryContext.Load(this._sandCherryContext.GetEQPByStatusQuery(StatusValue.Text), DataLoadedCallback, null);
SandCherryGrid.ItemsSource = loadOp.Entities;
}
void DataLoadedCallback(LoadOperation<SandCherryView> loadOperation)
{
StatusButton.IsEnabled = true;
}
}
}
SandCherryViewService.cs
[EnableClientAccess()]
public class SandCherryViewService : LinqToEntitiesDomainService<Charter_SandCherryEntities>
{
[Query(IsComposable=false)]
public IQueryable<SandCherryView> GetEQPByStatus(string status)
{
return this.ObjectContext.SandCherryViews.Where(e => e.StatusDescr.StartsWith(status) == true);
}
// TODO:
// Consider constraining the results of your query method. If you need additional input you can
// add parameters to this method or create additional query methods with different names.
// To support paging you will need to add ordering to the 'SandCherryViews' query.
public IQueryable<SandCherryView> GetSandCherryViews()
{
return this.ObjectContext.SandCherryViews;
}
public void InsertSandCherryView(SandCherryView sandCherryView)
{
if ((sandCherryView.EntityState != EntityState.Detached))
{
this.ObjectContext.ObjectStateManager.ChangeObjectState(sandCherryView, EntityState.Added);
}
else
{
this.ObjectContext.SandCherryViews.AddObject(sandCherryView);
}
}
public void UpdateSandCherryView(SandCherryView currentSandCherryView)
{
this.ObjectContext.SandCherryViews.AttachAsModified(currentSandCherryView, this.ChangeSet.GetOriginal(currentSandCherryView));
}
public void DeleteSandCherryView(SandCherryView sandCherryView)
{
if ((sandCherryView.EntityState != EntityState.Detached))
{
this.ObjectContext.ObjectStateManager.ChangeObjectState(sandCherryView, EntityState.Deleted);
}
else
{
this.ObjectContext.SandCherryViews.Attach(sandCherryView);
this.ObjectContext.SandCherryViews.DeleteObject(sandCherryView);
}
}
}
}
Since your data is not loaded yet. Try setting the ItemsSource of your grid in DataLoadedCallBack event -
void DataLoadedCallback(LoadOperation<SandCherryView> loadOperation)
{
StatusButton.IsEnabled = true;
SandCherryGrid.ItemsSource = loadOp.Entities;
}

Am I missing an if statement?

thanks in advance for any help!
A bit of background basically I am building an application that stores vehicles (cars,truck,buses), I have a vehicle superclass and all the individual classes (car.cs, truck.cs, minibus.cs) inherit from this super class.
I also have a class called 'fleet' that I would like to add the vehicles to an then display the results in a list box.
I have everything else working but I cannot get the trucks and minibus's to update and display on the list box like the cars do.
Here is my fleet class which includes the car.cs; and it works fine and the data taken from the car form gets added and displayed in the listbox.
class Fleet
{
private List<Vehicle> theFleet = new List<Vehicle>();
public List<Vehicle> fleet
{
get
{
return theFleet;
}
}
public void deleteFromFleet(Vehicle aCar)
{
theFleet.Remove(aCar);
}
public void addToFleet(Vehicle aCar)
{
theFleet.Add(aCar);
}
}
Here is my main form, that has the list box on it:
public partial class FrmHireCo : Form
{
private Fleet myFleet = new Fleet();
private ClientList mycustomer = new ClientList();
//Fleet object used to store cars
public FrmHireCo()
{
//Default constructor
InitializeComponent();
}
private void updateFleetList()
{
lstFleet.Items.Clear();
foreach (Car c in myFleet.fleet)
{
string line = "Car: " + c.make+" " + c.colour;
lstFleet.Items.Add(line);
}
}
private void updateClientList()
{
customers.Items.Clear();
foreach (Customer c in mycustomer.clientlist)
{
string line = "Customer: " + c.name + " " + c.address;
customers.Items.Add(line);
}
}
private void btnAddCar_Click(object sender, EventArgs e)
{
//Add a new car
FrmCar carGui = new FrmCar(); //Form used to add new car
carGui.ShowDialog();
Car myCar = carGui.car; //Get new car from form
myFleet.addToFleet(myCar); //Add to fleet list
updateFleetList(); //Uodate fleet list
}
private void lstFleet_SelectedIndexChanged(object sender, EventArgs e)
{
if (lstFleet.SelectedIndex > -1)
{
int index = lstFleet.SelectedIndex;
Car myCar = myFleet.fleet.ElementAt(index);
FrmCar carGui = new FrmCar();
carGui.car = myCar;
carGui.Show();
}
}
private void btnCustomer_Click(object sender, EventArgs e)
{
FrmCustomer customerGui = new FrmCustomer();
customerGui.ShowDialog();
Customer mycustomer = customerGui.customer;
mycustomer.addToClientList(mycustomer);
updateFleetList();
}
private void customers_SelectedIndexChanged(object sender, EventArgs e)
{
if (customers.SelectedIndex > -1)
{
int index = customers.SelectedIndex;
Customer myCustomer = mycustomer.clientlist.ElementAt(index);
FrmCustomer customerGui = new FrmCustomer();
customerGui.customer = myCustomer;
customerGui.Show();
}
}
}
Cheers for any help!
private void updateFleetList()
{
lstFleet.Items.Clear();
foreach (Vehicle c in myFleet.fleet)
{
string line = "Car: " + c.make+" " + c.colour;
lstFleet.Items.Add(line);
}
}
You should include all vehicles.
private void updateFleetList()
{
lstFleet.Items.Clear();
foreach (Vehicle v in myFleet.fleet)
{
lstFleet.Items.Add(v);
}
}
Also, just override ToString in all your Vehicle subclasses and the ListBox will use that inherently; this way not every Vehicle needs a Make or Color property.

Categories