Trouble passing new object back to main form - C# .NET - c#

I am new to C# and the .NET framework. I am trying to create an array of chocolate orders that shows up as a list on the main screen(MainNavigation). I have a chocolate class and a form(form1) where the user can select which type of chocolate and a new chocolate object is created. I am stuck on trying to pass the new object back to the main form and then showing it in a list on the main form.
MainNavigation form.... I would like value to be the orders that the user creates in form1.
using System;
using System.Windows.Forms;
namespace GatesCandyStore
{
public partial class MainNavigation : Form
{
public MainNavigation()
{
InitializeComponent();
Chocolate[] chocolates = new Chocolate[100];
for (int runs = 0; runs < 100; runs++)
{
chocolates[runs] = value;
}
}
private void btnProcessCandySelection_Click(object sender, EventArgs e)
{
string candy = comboBoxCandySelection.SelectedItem.ToString();
Form1 aForm1 = new Form1(textBoxName.Text, candy);
aForm1.ShowDialog();
}
}
}
Form1 where the user creates a new chocolate order.... Close(newChocolate); does not work.
using System;
using System.Windows.Forms;
namespace GatesCandyStore {
public partial class Form1 : Form
{
Chocolate newChocolate = new Chocolate();
public Form1(string name, string candy)
{
InitializeComponent();
string str = name + " selected : ";
label1.Text = str;
Console.WriteLine(name + " selected : " + candy);
}
private void Form1_Load(object sender, EventArgs e)
{
newChocolate.Flavor = comboBoxChocolateSelection.SelectedItem.ToString();
newChocolate.Cost = 12.5;
newChocolate.GiftWrap = true;
newChocolate.Quantity = 2;
}
private void button1_Click(object sender, EventArgs e)
{
Close(newChocolate);
}
} }
Chocolate Class
namespace GatesCandyStore
{
public class Chocolate
{
#region Fields
public string flavor;
public double cost;
public bool giftWrap;
public int quantity;
#endregion End of Fields
#region Constructors
public Chocolate(string flavor, double cost, bool giftWrap, int quantity)
{
Flavor = flavor;
Cost = cost;
GiftWrap = giftWrap;
Quantity = quantity;
}
#endregion End of Constructors
#region Properties
public string Flavor { get; set; }
public double Cost { get; set; }
public bool GiftWrap { get; set; }
public int Quantity { get; set; }
#endregion End Properties
}
}

here In your question, I'm still not clear what you are doing candy and name in your Form1's constructor.
Assuming you know what you are doing with them and taking your main concern "How to pass newly created object back to main form", I'm suggesting you some correction.
Create A Model class
public delegate void ChocolateAddedEventHander(Chocolate newChocolate);
public class Model
{
//An Event which will be raised when you add new chocolate
public event ChocolateAddedEventHander ChocolateAdded;
//If at any point of program you need whole list of added chocolates
public List<Chocolate> ChocolateList = new List<Chocolate>();
public void AddChocolateInList (Chocolate chocolate)
{
ChocolateList.Add(chocolate);
if (ChocolateAdded != null)
ChocolateAdded(chocolate);
}
}
Your Chocolate class will same as you have shown here.
Make following changes in Program.cs
static void Main()
{
Model modelObj = new Model();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainNavigation(modelObj));
}
As you can see in above code, MainNavigation is accecpting an object of Model class now.
MainNavigation form.
In code you shown in question, you seem to be doing something in constructor of MainNavigation , if array of Chocolate is containing all added chocolates you can use m_modelObj.ChocolateList there. But as I'm not clear what is value there. I'm not adding that part in my answer.
public partial class MainNavigation : Form
{
private Model m_modelObj;
public MainNavigation(Model modelObj)
{
InitializeComponent();
m_modelObj = modelObj;
//subscribing an even of Model class,
//this will handle your logic what you want to perform on adding new Chocolate
m_modelObj.ChocolateAdded += m_modelObj_ChocolateAdded;
}
void m_modelObj_ChocolateAdded(Chocolate newChocolate)
{
//perform your task what you want to do with newly added chocolate
//if you want whole list of chocolates
List<Chocolate> chocolateList = m_modelObj.ChocolateList;
}
private void btnProcessCandySelection_Click(object sender, EventArgs e)
{
string candy = comboBoxCandySelection.SelectedItem.ToString();
Form1 aForm1 = new Form1(textBoxName.Text, candy, m_modelObj);
aForm1.ShowDialog();
}
}
Note that, now Form1 will accept three parameters, third as in object of Model class
Form1 where you are adding chocolate.
public partial class Form1 : Form
{
Model m_model;
public Form1(string name, string candy, Model modelObj)
{
InitializeComponent();
m_model = modelObj;
//Not sure what you are doing here, but it will work
string str = name + " selected : ";
label1.Text = str;
Console.WriteLine(name + " selected : " + candy);
}
private void button1_Click(object sender, EventArgs e)
{
//adding new chocolate to list;
Chocolate newChocolate = new Chocolate(comboBoxChocolateSelection.SelectedItem.ToString(), 12.5, true, 2);
m_model.AddChocolateInList(newChocolate);
this.Close();
}
}
One more thing I will suggest, naming of class and member should be proper, It will help a lot while debugging and code reviewing.

Related

How can I access my method from another class

I'm very new to c#, I started a few days ago, so please excuse me if it is basic.
I have two forms, the first one is like a login page, where someone enters their name. On my "Info.cs" class, it reads this name via a setter, into a variable, and my Getter called "GetCardName" returns this Name. I now made a new form where I want to access this name via the GetCardName getter, just dont know how too. Heres the code :
Here is some of the "info.cs" class code:
private string CardName { get; set; } = "";
public string GetCardName()
{
return this.CardName;
}
public void SetName(string name = "")
{
this.CardName = name;
}
And here is the code from the other form that is just trying to call GetCardName():
private void Form2_Load(object sender, EventArgs e)
{
lblWelcome.Text = Info.GetCardName();
}
When creating Form2 you need also pass it reference to the other form to get its properties.
So when creating and showing Form1 you should also create Form2 to pass that reference. Example (not tested) code:
var form1 = new Form1();
var form2 = new Form2(form1);
form1.Show();
and Form2 should be like:
public class Form2
{
private Form1 _form1;
public Form2(Form1 form1)
{
_form1 = form1;
// ... other initialization code
}
// ... other class declarations
}
General solution is: you need to persist reference to the Form1 being shown to the user and then pass that reference to Form2 whenever you create it.
You have two options :
you can create an instance of the class that you want to call
EX : Info infoVar = new Info(); (now you can use infoVar to call any methods of the Info.cs class)
you can make Info class a STATIC class (probably not what you want to do, but still helpful for the future perhaps) This makes it possible to call the info class directly without having to create a variable of that class but has some drawbacks. (more info here)
There is few ways to achieve what you want:
Public static property:
public class Info
{
public static string CardName { get; set; } = string.Empty;
}
You can access it or set value to it directly by:
private void Form2_Load(object sender, EventArgs e)
{
// Set
Info.CardName = "Some name";
// Get
lblWelcome.Text = Info.CardName;
}
Public non-static property:
public class Info
{
public string CardName { get; set; } = string.Empty;
}
You can access it or set value to it directly too, but need to create Info class instance before:
private void Form2_Load(object sender, EventArgs e)
{
Info info = new Info();
// Set
info.CardName = "Some name";
// Get
lblWelcome.Text = info.CardName;
}
Private static field with separated public static Get and Set methods:
public class Info
{
private static string cardName = string.Empty;
public static string GetCardName()
{
return cardName;
}
public static void SetCardName(string name = "")
{
cardName = name;
}
}
You can access GetCardName and SetCardName without creating Info class instance:
private void Form2_Load(object sender, EventArgs e)
{
// Set
Info.SetCardName("Some name");
// Get
lblWelcome.Text = Info.GetCardName();
}
Private non-static field with separated public non-static Get and Set methods:
public class Info
{
private string cardName = string.Empty;
public string GetCardName()
{
return cardName;
}
public void SetCardName(string name = "")
{
cardName = name;
}
}
You can access GetCardName and SetCardName after creating Info class instance:
private void Form2_Load(object sender, EventArgs e)
{
Info info = new Info();
// Set
info.SetCardName("Some name");
// Get
lblWelcome.Text = info.GetCardName();
}
Difference between fields and properties was pretty nice explained here: What is the difference between a field and a property?. In short, properties are "wrappers" over fields, which usually are private and you can't access to them directly or modify. It is a part of Member Design Guidelines. Also properties allow to add some validations through property setter to be sure that valid value is stored at cardName field, e.g.:
public class Info
{
private string cardName = string.Empty;
public string CardName
{
get => cardName;
set
{
// Check that value you trying to set isn't null
if (value != null)
cardName = value;
// Or check that name is not too short
if (value.Length >= 3) // Card name should be at least of 3 characters
cardName = value;
}
}
}
info myInfo=new info();
lblWelcome.Text = myInfo.GetCardName();

Windows Form Application how return value form one form to other

I'm writing an application which will be storing film that i watched and I going to watch in future in XML file ( simple app only for training )
The main object which i use to store data in my app look like :
public class FilmDto : IFilmDto
{
public int FilmId { get; set; }
public string Name { get; set; }
public DateTime? WatchedDate { get; set; }
public int ParentId { get; set; }
public string ParentName { get; set; }
public FilmStatus FilmStatus { get; set; }
public string Category { get; set; }
public string SubCategory { get; set; }
}
All the operation is perform in Service class. There are list of film as main data file.
The service class look this :
public class FilmService
{
private List<FilmDto> _films = new List<FilmDto>();
private FilmDao _filmDao = new FilmDao();
private FilmService()
{
_films = _filmDao.Load();
}
public static FilmService Inicialize()
{
return new FilmService();
}
public void Save()
{
_filmDao.Save(_films);
}
public List<FilmDto> GetFilmsByCriteria(FilmCriteriaDto criteria, bool withStatus)
{
if (withStatus)
{
return _films.Where(x => x.Category.Contains(criteria.Category)
&& x.SubCategory.Contains(criteria.SubCategory)
&& x.ParentName.Contains(criteria.ParentName)
&& x.Name.Contains(criteria.Name)
&& x.FilmStatus.Equals(criteria.FilmStatus)).ToList();
}
else
{
return _films.Where(x => x.Category.Contains(criteria.Category)
&& x.SubCategory.Contains(criteria.SubCategory)
&& x.ParentName.Contains(criteria.ParentName)
&& x.Name.Contains(criteria.Name)).ToList();
}
}
public StatisticDto GetFilmStatistic()
{
return new StatisticDto
{
TotalCount = _films.Count,
TotalToWatch = _films.Where(x => x.FilmStatus == FilmStatus.DoObejzenia).Count(),
TotalWatched = _films.Where(x => x.FilmStatus == FilmStatus.Obejzany).Count()
};
}
public List<string> GetAllParentName()
{
return _films.Select(x => x.ParentName).ToList();
}
public void Add(FilmDto film)
{
_films.add(film);
}
// Private Methods
private int GetNexID()
{
return _films.OrderByDescending(x => x.FilmId).FirstOrDefault().FilmId + 1;
}
}
Now its time to form which i use to resent data. The form use service instance and call method form service to get those data ( form have only display data and do not have any logic to transform it )
public partial class Form1 : Form
{
private FilmService _filmService
public Form1()
{
_filmService = FilmService.Inicialize();
InitializeComponent();
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
FillTable(new FilmCriteriaDto(), false);
}
private void FillTable(FilmCriteriaDto criteria,bool witchStatus)
{
List<FilmDto> films = _filmService.GetFilmsByCriteria(criteria,witchStatus);
foreach (FilmDto film in films)
{
dataGridView1.Rows.Add(film.Name,film.WatchedDate,film.ParentName,film.Category,film.SubCategory,film.FilmStatus);
}
}
private void statisticToolStripMenuItem_Click(object sender, EventArgs e)
{
StatisticDto stats = _filmService.GetFilmStatistic();
MessageBox.Show(string.Format("Total :{0}\nWatched {1}\nTo watch {2}"
, stats.TotalCount, stats.TotalWatched, stats.TotalToWatch), "Stats INFO",MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void addToolStripMenuItem_Click(object sender, EventArgs e)
{
...Call new form to add new film
}
}
To this moment everything is quite nice. But now i need to create new form ( Form2) which will have TexBox to insert new film data to my list in service. No i don't know ho to do this.
First i thought that i change private FilmService _filmService to public FilmService FilmService {get;set;}
And in form2 create constructor where I give Form1 object like public Form2(Form1 form) and make call it form Form1 like : Form2 form = new Form2(this) . In that case i have access to that service method but it will look like form.FilmService.Add which is not nice. In other way i can pass FilmService object as parameter but in that way Form1 will don't know change which Form2 make. I want to create method in Form2 which will be returning FilmDto object to Form1 when e.g i click buton in Form2 is there any way to do that ?
You can use different ways to do this.
The simplest is to use Dialogs. You can open your Form2 as fialog by call ShowDialog and then just read the property if result is OK. It's a general way to implement your behavior in WinForms.
private void addToolStripMenuItem_Click(object sender, EventArgs e)
{
// Show testDialog as a modal dialog and determine if DialogResult = OK.
if (form2.ShowDialog(this) == DialogResult.OK)
{
// Read the contents of testDialog's TextBox.
this.txtResult.Text = form2.TextBox1.Text;
}
}
Note that you must set DialogResult property in Form2 to DialogResult.OK if user click the button and DialogResult.Cancel in other way. It helps you to handle scenario when user has decided not to add new movie.
The other way is to use events. Declare new event in Form2 and subscribe Form1 to this event. Raise new event on button click and pass your data as a parameter of your event.
First of all you can make FilmService static or singleton.
Also you can find some examplex for your particular task here - Communicate between two windows forms in C#
In my Point of View, you should use MVP pattern - https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93presenter
But probably it is overkill.

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;

Panel does not contain a constructor that takes 0 arguments

I need to load a User Control in my panel1 inside Form1.cs, the problem is that the UserControl (AudioPlaybackPanel) contains an ImportingConstructor ([ImportMany]IEnumerable<>) and I can't figure out what two arguments I should have in the Form1 AudioPlaybackPanel(????).
The error I get is: 'NAudio.App.AudioPlaybackPanel' does not contain a constructor that takes 0 arguments
Here is the Form1.cs
namespace NAudio.App
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
AudioPlaybackPanel myPanel = new AudioPlaybackPanel(????);
panel1.Controls.Add(myPanel);
}
}
}
And this is my User Control Panel (AudioPlaybackPanel.cs):
namespace NAudio.App
{
[Export]
public partial class AudioPlaybackPanel : UserControl
{
private IWavePlayer waveOut;
private string fileName = null;
private WaveStream fileWaveStream;
private Action<float> setVolumeDelegate;
[ImportingConstructor]
public AudioPlaybackPanel([ImportMany]IEnumerable<IOutputDevicePlugin> outputDevicePlugins)
{
InitializeComponent();
LoadOutputDevicePlugins(outputDevicePlugins);
}
[ImportMany(typeof(IInputFileFormatPlugin))]
public IEnumerable<IInputFileFormatPlugin> InputFileFormats { get; set; }
private void LoadOutputDevicePlugins(IEnumerable<IOutputDevicePlugin> outputDevicePlugins)
{
comboBoxOutputDevice.DisplayMember = "Name";
comboBoxOutputDevice.SelectedIndexChanged += new EventHandler(comboBoxOutputDevice_SelectedIndexChanged);
foreach (var outputDevicePlugin in outputDevicePlugins.OrderBy(p => p.Priority))
{
comboBoxOutputDevice.Items.Add(outputDevicePlugin);
}
comboBoxOutputDevice.SelectedIndex = 0;
}
void comboBoxOutputDevice_SelectedIndexChanged(object sender, EventArgs e)
{
panelOutputDeviceSettings.Controls.Clear();
Control settingsPanel;
if (SelectedOutputDevicePlugin.IsAvailable)
{
settingsPanel = SelectedOutputDevicePlugin.CreateSettingsPanel();
}
else
{
settingsPanel = new Label() { Text = "This output device is unavailable on your system", Dock=DockStyle.Fill };
}
panelOutputDeviceSettings.Controls.Add(settingsPanel);
}
private IOutputDevicePlugin SelectedOutputDevicePlugin
{
get { return (IOutputDevicePlugin)comboBoxOutputDevice.SelectedItem; }
}
// The rest of the code continues from here on...
}
}
Here is the Interface:
namespace NAudio.App
{
public interface IOutputDevicePlugin
{
IWavePlayer CreateDevice(int latency);
UserControl CreateSettingsPanel();
string Name { get; }
bool IsAvailable { get; }
int Priority { get; }
}
}
And just in case, here is one of the plugins:
DirectSoundOutPlugin.cs
namespace NAudio.App
{
[Export(typeof(IOutputDevicePlugin))]
class DirectSoundOutPlugin : IOutputDevicePlugin
{
private DirectSoundOutSettingsPanel settingsPanel;
private bool isAvailable;
public DirectSoundOutPlugin()
{
this.isAvailable = DirectSoundOut.Devices.Count() > 0;
}
public IWavePlayer CreateDevice(int latency)
{
return new DirectSoundOut(settingsPanel.SelectedDevice, latency);
}
public UserControl CreateSettingsPanel()
{
this.settingsPanel = new DirectSoundOutSettingsPanel();
return this.settingsPanel;
}
public string Name
{
get { return "DirectSound"; }
}
public bool IsAvailable
{
get { return isAvailable; }
}
public int Priority
{
get { return 3; }
}
}
}
Please help!
The error doesn't say it expects two arguments... it just says it doesn't take 0.
The constructor expects a single parameter - an IEnumerable<IOutputDevicePlugin>:
public AudioPlaybackPanel([ImportMany]IEnumerable<IOutputDevicePlugin> outputDevicePlugins)
{
...
}
You need to find something that implements the IOutputDevicePlugin interface and pass a collection of it, even if it's just an empty collection. (Passing null to the constructor will allow it to compile but will throw a runtime exception when you hit the loop in LoadOutputDevicePlugins.)
Considering the update to your question, something like this will get you up and running (although I doubt it means very much to pass an empty list):
var myPanel = new AudioPlaybackPanel(new List<DirectSoundOutPlugin>());
panel1.Controls.Add(myPanel);
It's worth asking whether you actually need to copy AudioPlaybackPanel.cs from the NAudio demo in its entirety. The reason it has this constructor is that it tries to demonstrate how you can use each and every one of NAudio's IWavePlayer implementations. But in a normal real-world application you would just select the one that was most appropriate for your use. e.g.
this.waveOut = new WaveOut();
waveOut.Init(new AudioFileReader("my file.mp3");
waveOut.Play();
So there's no need to incorporate the plug-in architecture from that particular demo, if all you want is just to play audio files.

Passing value from one form to a textbox in another form

Well I know this question has been asked a couple of times but none of the solutions worked for me. I simply want to pass a value from one form to a textbox in a different form.
On the first form I have a data grid when double-clicked on it obtains a value from the datagrid column.
public partial class AvailableRooms : Form
{
private void DCRoom(object sender, DataGridViewCellMouseEventArgs e)
{
var roomnum = dgRooms.Rows[e.RowIndex].Cells["iRoomNum"].Value.ToString();
RoomBooking rb = new RoomBooking();//The second form
rb.roomnumber = roomnum;
rb.Show();
}
}
On the second form I have set the properties of the textbox
public partial class RoomBooking : Form
{
public RoomBooking()
{
StartPosition = FormStartPosition.CenterScreen;
InitializeComponent();
}
public string roomnumber
{
get { return txtRoomNum.Text; }
set {txtRoomNum.Text = value;}
}
}
Thanks in advance for the help?
You have to find the control to edit it as it does not belong to the class.
private void DCRoom(object sender, DataGridViewCellMouseEventArgs e)
{
//new value
var roomnum = dgRooms.Rows[e.RowIndex].Cells["iRoomNum"].Value.ToString();
//The second form
RoomBooking rb = new RoomBooking(this);
//The textbox
TextBox roomnumber = (TextBox)rb.Controls.Find("roomnumber", true)[0];
//set the value of the textbox
roomnumber.Text = roomnum;
//show second form
rb.Show();
}
I would define the RoomBookingclass like this:
public partial class RoomBooking : Form
{
public RoomBooking() // WinForms Designer requires a public parameterless constructor
{
InitializeComponent();
StartPosition = FormStartPosition.CenterScreen;
}
public RoomBooking(string roomNumber) : this() // Constructor chaining
{
RoomNumber = roomNumber;
txtRoomNum.Text = RoomNumber;
}
public string RoomNumber { get; set; }
}
Then:
public partial class AvailableRooms : Form
{
private void DCRoom(object sender, DataGridViewCellMouseEventArgs e)
{
var roomNumber = dgRooms.Rows[e.RowIndex].Cells["iRoomNum"].Value.ToString();
var roomBooking = new RoomBooking(roomNumber);
roomBooking.Show();
}
}
Hope this helps.

Categories