Sending ListView data between forms - c#

Hi, I am a newbie to C# and I have no programming background, but I am interested in it.
I want to send data to a ListView, but the data is in the other form. I already saw all the related posts here. I tried copying code from one of the post and changing it according to my needs, but it doesn't work.
Form3:
public partial class Form3 : Form
{
public Form3()
{
InitializeComponent();
}
public delegate void HandleItemAdded(object sender, ItemAddedEventArgs e);
public struct ItemAddedEventArgs: EventArgs
{
public string PartPrefix;
public string PartStartNumber;
public string AssemblyPrefix;
public string AssemblyStartNumber;
public string Name;
public string Profile;
public string Material;
public string Finish;
public string Class;
public ItemAddedEventArgs(string partprefix, string partstartnumber, string assemblyprefix, string assemblystartnumber, string name, string profile, string material, string finish, string classes)
{
PartPrefix = partprefix;
PartStartNumber = partstartnumber;
AssemblyPrefix = assemblyprefix;
AssemblyStartNumber = assemblystartnumber;
Name = name;
Profile = profile;
Material = material;
Finish = finish;
Class = classes;
}
}
public event HandleItemAdded ItemAdded;
public void RaiseItemAdded(ItemAddedEventArgs e)
{
if (ItemAdded != null)
ItemAdded(this, e);
}
public void AddToList()
{
RaiseItemAdded (new ItemAddedEventArgs (textBox221.Text, textBox222.Text, textBox223.Text, textBox224.Text, textBox225.Text, textBox226.Text, textBox227.Text, textBox228.Text, textBox229.Text));
}
}
Form1:
public void HandleItemAdded(object sender, WindowsFormsApplication1.Form3.ItemAddedEventArgs e)
{
ListViewItem item1 = new ListViewItem(textBox221.Text);
item1.SubItems.Add(textBox222.Text);
item1.SubItems.Add(textBox223.Text);
item1.SubItems.Add(textBox224.Text);
item1.SubItems.Add(textBox225.Text);
item1.SubItems.Add(textBox226.Text);
item1.SubItems.Add(textBox227.Text);
item1.SubItems.Add(textBox228.Text);
item1.SubItems.Add(textBox229.Text);
listView1.Add(item1);
Form3.ItemAdded += Form1.HandleItemAdded; *<-( i dont know if this is the correct place for this.)
}
The error I get is: type EventArgs in interface list is not an interface
Thank you in advance.

What you need to do in Form1 is this:
public void HandleItemAdded(object sender, WindowsFormsApplication1.Form3.ItemAddedEventArgs e)
{
ListViewItem item1 = new ListViewItem(e.PartPrefix);
item1.SubItems.Add(e.PartStartNumber);
item1.SubItems.Add(e.<Member_Name>);
.
.
.
listView1.Add(item1);
}
And for the error I think following should work for you:
public class ItemAddedEventArgs: EventArgs

Related

Pass data from listView to tabPage in xamarin forms

I am new to xamarin forms and I am trying to make a project similar to what you can see in the next picture.
photo
The thing I want to achieve is when I press an item from listView (which I already have with the items displayed) where I have all items I want to pass somehow the entire object to the tabPage so that I can see the description in one part and the opinions in the other page. I did some research but all the examples I saw uses MVVM and mine is more simple than that.
Here you have the code.
--->Model
public class Item
{
public String name;
public String description;
public Double price;
public int stock;
public List<String> opinions;
public Item(String name, String description ,Double price, int stock, List<String> opinions)
{
this.name = name;
this.description = description;
this.price = price;
this.stock = stock;
this.opinions = opinions;
}
public override string ToString()
{
return this.name + " " + this.price + " $" + this.stock + " ud";
}
}
---> The event that takes me to the TabPage.
private async void parent_listView_ItemSelected(object sender, SelectedItemChangedEventArgs e)
{
//here maybe I should pass the object...
await Navigation.PushAsync(new TabPage());
}
---> Here you have both classes that are used inside the tabPage
public partial class Datos : ContentPage
{
//private string descriptionList;
public Datos()
{
InitializeComponent();
}
}
public partial class Opinions : ContentPage
{
public Opinions()
{
InitializeComponent();
}
}
The thing is that I don't know how to pass the object in a specific position from listView to both pages from tabPage in a easy way. I tried to pass both classes(Datos and Opinions) using TabPage constructor but it doesn't work. Here you have the code...
private async void parent_listView_ItemSelected(object sender, SelectedItemChangedEventArgs e)
{
await Navigation.PushAsync(new TabPage(new Datos(itemList[e.SelectedItemIndex] ), new Opinions(itemList[e.SelectedItemIndex] )));
}
SelectedItemChangedEventArgs contains a reference to the selected object
private async void parent_listView_ItemSelected(object sender, SelectedItemChangedEventArgs e)
{
var item = (Item)e.SelectedItem;
await Navigation.PushAsync(new TabPage(item));
}

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();

Loaded an object into a listbox with 2 variables, listbox show only the name

I have a Class where there a 2 variables int ID and string name. I made a list of several objects and loaded them onto a listbox. The listbox only show the name. Is there a way to retrieve the ID from the listbox?
class Show
{
private int _Id;
private string _Naam;
private string _Genre;
public override string ToString()
{
return Naam;
}
}
from a database i make a list of objects.
private void bttn_zoek_Click(object sender, EventArgs e)
{
foreach (object a in List<show> List)
{
listbox1.Items.Add(a);
}
}
I hope this is enough
Assuming WinForms, here is a super simple example of overriding ToString() to control how the class is displayed in the ListBox, and also how to cast the selected item in the ListBox back to your class type so you can extract values from it. There are other ways to accomplish this task, but you should understand a bare bones example like this first:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
SomeClassName sc1 = new SomeClassName();
sc1.ID = 411;
sc1.Name = "Information";
listBox1.Items.Add(sc1);
SomeClassName sc2 = new SomeClassName();
sc2.ID = 911;
sc2.Name = "Emergency";
listBox1.Items.Add(sc2);
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (listBox1.SelectedIndex != -1)
{
SomeClassName sc = (SomeClassName)listBox1.Items[listBox1.SelectedIndex];
label1.Text = "ID: " + sc.ID.ToString();
label2.Text = "Name: " + sc.Name;
}
}
}
public class SomeClassName
{
public int ID;
public string Name;
public override string ToString()
{
return ID.ToString() + ": " + Name;
}
}
Posting some of your code would be nice. Have you tried listBox.items[index].ID?
Here I'm assuming that index is whatever index you're currently searching for.
You can also try listBox.SelectedItem[index].ID if you're doing something like an event.

Accesing child class value from list

There two classes
1) Parent Class has 3 fields *all classes have getters and setters
public class CellPhone
{
private string Iemi;
private string description;
private decimal price;
public CellPhone(){}
public CellPhone(string Iemi, string Description, decimal Price)
{
this.Iemi = Iemi;
this.description = Description;
this.price = Price;
}
2) the Child has 1 field, but inherits all frield from the parent class.
public class InDate : CellPhone
{
private string inDate;
public InDate(){}
public InDate(string Iemi, string Description, string InDate,
decimal Price):base( Iemi, Description, Price)
{
this.inDate = InDate;
}
3) I use manage to write all data, and read date to memory (to a list)
public partial class frmSellCellPhone : Form
{
CellPhoneList newList = new CellPhoneList();
public frmSellCellPhone()
{
InitializeComponent();
}
private void frmSellCellPhone_Load(object sender, EventArgs e)
{
newList.Fill();
}
private void btnSale_Click(object sender, EventArgs e)
{
int i = cmbBox.SelectedIndex;
}
private void SearchItemOnList()
{
foreach (CellPhone c in newList)
{
if (c.IEMI == txtSearchIEMI.Text)
{
txtDesciption.Text = c.Description;
txtInPrice.Text = Convert.ToString(c.Price);
txtInDate.Text = ""; //can't access inDate?
}
}
}
The issue is when i try displaying, the date is not accessible.
I would appreicate if any suggestion is offered.
You did not pasted your CellPhoneList class (or is it just a List ?), but surely it is using CellPhone instead of InDate.
Change your SearchItemOnList() to
private void SearchItemOnList()
{
foreach (InDate c in newList)
{
if (c.IEMI == txtSearchIEMI.Text)
{
txtDesciption.Text = c.Description;
txtInPrice.Text = Convert.ToString(c.Price);
txtInDate.Text = ""; //can't access inDate?
}
}
}
In the following method, you step through a list of CellPhones.
CellPhone doesn't have a inDate property.
private void SearchItemOnList() {
foreach (CellPhone c in newList) {
if (c.IEMI == txtSearchIEMI.Text) {
txtDesciption.Text = c.Description;
txtInPrice.Text = Convert.ToString(c.Price);
txtInDate.Text = ""; //can't access inDate?
}
}
}
You would need to step through a list of InDates to get that value.

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.

Categories