I have a list in a form and I want to access this list from Form1
in user control.
The following code line would be in Form1
:
public partial class form : Form
{
public static List<daftarBarang> tambahBarang = new List<daftarBarang>();
}
//UserControl
parent.tambahBarang.Add(new daftarBarang(nama, harga, stok, parent.tambahBarang.Count));
The issue is I cannot use my list, if I don't use static then the list won't save the results.
I don't understand exactly how you wired up your Form
and UserControl
but here's an example of a UserControl
that works as a container which displays the items that you add via AddItem
.
If this example does not help you to solve your problem please provide us with more information so that we can assist you further.
using System;
using System.ComponentModel;
using System.Windows.Forms;
namespace WindowsFormsApp
{
public class DaftarBarang
{
public string Nama { get; set; }
public int Harga { get; set; }
}
public class TheUserControl : UserControl
{
private readonly BindingList<DaftarBarang> list = new BindingList<DaftarBarang>();
public TheUserControl()
{
var grid = new DataGridView
{
DataSource = new BindingSource(list, null)
};
AutoSize = true;
Controls.Add(grid);
}
public void AddItem(DaftarBarang barang)
{
list.Add(barang);
}
}
public class TheForm : Form
{
public TheForm()
{
var uc = new TheUserControl();
uc.AddItem(new DaftarBarang { Nama = "Sepatu olahraga", Harga = 255000 });
uc.AddItem(new DaftarBarang { Nama = "Baju cantik", Harga = 85000 });
Controls.Add(uc);
}
}
static class Program
{
[STAThread]
static void Main()
{
Application.Run(new TheForm());
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.