How to send Form1 value to other cs - c#

I know how to send value Form1 to Form2 like and it works fine;
FORM1;
public static string sirket = "";
public static string personeladı = "";
public static string desc = "";
public static string toplampay = "";
private void prew_Click(object sender, EventArgs e)
{
List<ListViewItem> myList = new List<ListViewItem>();
foreach (ListViewItem lvi in this.listView1.Items)
{
myList.Add(lvi);
}
sirket = companyname.Text;
personeladı = personelcombo.Text;
desc = paydesc.Text;
toplampay = totalpay.Text;
Form2 frm2 = new Form2(listView1);
frm2.Show();
}
FORM2 ;
string com = Form1.sirket;
string pers = Form1.personeladı;
string descrip = Form1.desc;
string toppay = Form1.toplampay;
My question is I have a form name Form1(it is a form) and I wrote Listviewprint.cs(not Form).I want to send value Form1 to Listviewprint.cs but when I try to use like above it give me error ;
The name 'Form1' does not exist in the current context.
How can I send values Form1 to Listviewprint.cs

Not 100% clear for me what you really would like to do, but I think this will help you. Comment something if it's not clear for you.
Sou you have the Form1 class, and you declare your ListViewPrint in it. After that you can set it's public properties in Form1.
public partial class Form1 : Form
{
private ListViewPrint _mylistviewPrint;
public Form1()
{
InitializeComponent();
_mylistviewPrint = new _mylistviewPrint(/*or with your parameters*/);
}
public void DoSomethingInForm1()
{
_mylistviewPrint.SomeVariable = 52;
}
}
public class ListViewPrint
{
private int _somevariable;
public int SomeVariable
{
get
{
return _somevariable;
}
set
{
_somevariable = value;
}
}
private string _othervariable;
/// like the above
}

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

Add ONLY checked items from a checklistbox to a listView control

My situation:
I have a populated checklistbox control on Form1.
Then I have a listView control on Form2.
I would like for the user to be able to check items on the checklistbox on Form1, then click on a button on Form1 to open Form2.
Form2 contains the listView control, that I want to populate with only the checked items from checklistbox on Form1.
I tried
namespace Boodschappenlijst
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public static string[] strKruideniersw = new string[] { Boodschappenlijst.producten[0], Boodschappenlijst.producten[1], Boodschappenlijst.producten[2] };
public static string[] strVerswaren = new string[] { Boodschappenlijst.producten[3], Boodschappenlijst.producten[4], Boodschappenlijst.producten[5] };
public static string[] strVerzorgingspr = new string[] { Boodschappenlijst.producten[6], Boodschappenlijst.producten[7], Boodschappenlijst.producten[8], Boodschappenlijst.producten[9] };
public static List<string> kruidenierswList = new List<string>(strKruideniersw);
public static List<string> verswarenList = new List<string>(strVerswaren);
public static List<string> verzproductenList = new List<string>(strVerzorgingspr);
public static string[] strKruidenierswCh;
public void Form1_Load(object sender, EventArgs e)
{
clbKruidenierswaren.Items.AddRange(strKruideniersw);
clbVerswaren.Items.AddRange(strVerswaren);
clbVerzproducten.Items.AddRange(strVerzorgingspr);
strKruidenierswCh = clbKruidenierswaren.CheckedItems;
}
// TODO
// public string kruidenierswChecked = clbKruidenierswaren.CheckedItems;
private void button1_Click(object sender, EventArgs e)
{
// Create a new instance of the Form2 class
Form2 form2 = new Form2();
// Show the settings form
form2.Show();
}
}
public abstract class Boodschappenlijst : Form1
{
public static string[] producten = new string[] { "Peper", "Zout", "Kruidnagel", "Sla", "Komkommer", "Tomaten", "Tandpasta", "Shampoo", "Wax", "Deodorant" };
// Not working.. clbKruidenierswaren is not static.
List<string> items = clbKruidenierswaren.CheckedItems.Cast<string>().ToList();
// Make form1 controls accessible for other classes?
// Form1 form1 = Application.OpenForms.OfType<Form1>().FirstOrDefault();
}
}
but the I get the error
A field initializer cannot reference the non-static field, method, or property 'Form1.clbKruidenierswaren'.
Can you please direct me to a solution that works?
You should make a constructor in the class like this:
Class itself:
public class Boodschappenlijst
{
public static string[] producten { get; set; } = new string[] { "Peper", "Zout", "Kruidnagel", "Sla", "Komkommer", "Tomaten", "Tandpasta", "Shampoo", "Wax", "Deodorant" };
private List<string> Items { get; set; }
public Boodschappenlijst(List<string> items)// << Constructor
{
Items = items;
}
}
And then make an instance the class like so:
On the place (Form?) you have clbKruidenierswaren:
Boodschappenlijst boodschappenLijst =
new Boodschappenlijst(clbKruidenierswaren.CheckedItems.Cast<string>().ToList());
The problem is you're passing UI objects around, you should be passing data around instead. Here's an example of a Form that can be given data during construction.
public class BaseForm : Form
{
public object InitialisationData { get; set; }
}
public partial class MagicForm : BaseForm
{
public string MyBindableGuy;
public MagicForm()
{
InitializeComponent();
MyBindableGuy = InitialisationData as string;
}
}
and open it with:
var myForm = new MagicForm();
myForm.InitialisationData = "Hi, I'm a string.";
myForm.Show();
public partial class Form1 : Form
{
// Todo declare the variables
private List<string> kruidenierswList;
private List<string> verswarenList;
private List<string> verzproductenList;
public Form1()
{
InitializeComponent();
// call the instance once and add that to the variable lijst
Boodschappenlijst lijst = Boodschappenlijst.Instance; // <- # others on S/O this is just used as information I know I could do a new as well.
// initialize the variables
kruidenierswList = new List<string>() { lijst.Products[0], lijst.Products[1], lijst.Products[2] };
verswarenList = new List<string>() { lijst.Products[3], lijst.Products[4], lijst.Products[5] };
verzproductenList = new List<string>() { lijst.Products[6], lijst.Products[7], lijst.Products[8], lijst.Products[9] };
}
public void Form1_Load(object sender, EventArgs e)
{
// populate the checklist boxes
clbKruidenierswaren.Items.AddRange(kruidenierswList.ToArray());
clbVerswaren.Items.AddRange(verswarenList.ToArray());
clbVerzproducten.Items.AddRange(verzproductenList.ToArray());
}
private void button1_Click(object sender, EventArgs e)
{
// Create a new instance of the Form2 class
Form2 form2 = new Form2();
// Show the settings form
form2.Show();
}
}
public class Boodschappenlijst
{
private static Boodschappenlijst instance;
public string[] Products
{
get;
private set;
}
private Boodschappenlijst()
{
Products = new string[] { "Peper", "Zout", "Kruidnagel", "Sla", "Komkommer", "Tomaten", "Tandpasta", "Shampoo", "Wax", "Deodorant" };
}
public static Boodschappenlijst Instance
{
get
{
// singleton initialization => look for design pattern - singleton <- Design patterns can brighten your day.
//
return instance == null ? instance = new Boodschappenlijst() : instance;
}
}
}

C# - Accessing a list of Objects from one class to another

I am having this very strange problem where i am creating a list of some objects in one class then trying to access it in another class but it's coming empty in other class:
My first class where i am populating the list:
namespace dragdrop
{
struct BR
{
private string var;
public string Var
{
get { return var; }
set { var = value; }
}
private string equalsTo;
public string EqualsTo
{
get { return equalsTo; }
set { equalsTo = value; }
}
private string output;
public string Output
{
get { return output; }
set { output = value; }
}
private string els;
public string Els
{
get { return els; }
set { els = value; }
}
private string elsOutput;
public string ElsOutput
{
get { return elsOutput; }
set { elsOutput = value; }
}
}
public partial class Form1 : Form
{
//******************
private List<BR> list = new List<BR>(); //This is the list!
//******************
internal List<BR> List
{
get { return list; }
set { list = value; }
}
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string[] vars = new string[] { "Name", "Gender", "Age", "Address", "email" };
comboBox1.DataSource = vars;
}
private void button1_Click(object sender, EventArgs e)
{
BR b = new BR();
b.Var = comboBox1.SelectedItem.ToString();
b.EqualsTo = textBox1.Text;
b.Output = textBox2.Text;
list.Add(b);
//*****************
textBox1.Text = List.Count.ToString(); //This gives the correct count value!
//*****************
//this.Close();
}
}
}
I am accessing it in second class like:
namespace dragdrop
{
public partial class Ribbon1
{
private void Ribbon1_Load(object sender, RibbonUIEventArgs e)
{
}
private void button1_Click(object sender, RibbonControlEventArgs e)
{
Form1 form = new Form1();
List<BR> l = form.List; ;
//*******************
MessageBox.Show(form.List.Count.ToString()); //This strangely gives count 0!
//*******************
}
}
}
I have even tried making everything public in first class but no matter what i do, im always getting empty list in second class.
The is no relation what-so-ever between Form1 and Ribbon1, how can one then access an instance of the other?
With this:
Form1 form = new Form1(); // new instance of Form1
List<BR> l = form.List; ; // of course the list is empty in a new instance!
you can never access values from another instance of Form1.
Since I have no idea how your classes are connected I cannot give you more advice than have a look at this good overview of OO-relationships. You have to connect them somehow for it to work, I would very much recommend composition // aggregation (same thing, different schools).
All i needed to do was make the list a static member in class one, that solved the issue of having different value when i tried to create a new instance of Form1 in Ribbon1 class.
private static List<BR> list = new List<BR>();

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.

Get data from another form

I have a listview in my Mainform and I need to get the value in the textbox and label in the other form name Add_Order?
Add_Order add = new Add_Order();
ListViewItem item = new ListViewItem();
item.Text = add.textBox3.Text;
item.SubItems.Add(add.label6.Text);
item.SubItems.Add(add.textBox2.Text);
item.SubItems.Add(add.textBox1.Text);
item.SubItems.Add(add.textBox3.Text);
mainform.listView2.Items.Add(item);
I personally would not expose the controls in your Add_Order Form. Your calling Form should not be aware of the internals of the Add_Order Form, only its public Methods and Properties. I would make a Public Method and use that to retrieve the information you need. something like this:
Add_Order.cs
public partial class Add_Order : Form
{
public Add_Order()
{
InitializeComponent();
}
public List<string> GetData()
{
List<string> list = new List<string>();
list.Add(textBox3.Text);
list.Add(label6.Text);
list.Add(textBox2.Text);
list.Add(textBox1.Text);
return list;
}
}
MainForm
private void button1_Click(object sender, EventArgs e)
{
Add_Order add = new Add_Order();
add.ShowDialog();
ListViewItem item = new ListViewItem();
List<string> data = add.GetData();
item.Text = data[0];
item.SubItems.Add(data[1]);
item.SubItems.Add(data[2]);
item.SubItems.Add(data[3]);
item.SubItems.Add(data[0]);
listView2.Items.Add(item);
}
You can pass the data to other forms in different ways like creating public classes to maintain data common data between forms or you can pass data using form constructor like :
Add_Order frmAddOrder=new Add_Order(data1,data2);
frmAddOrder.show();
and in your Add_Order Constructor :
public Add_Order (string data1,string data2)
{
InitializeComponent();
//you can access data1 and data2 here ...
}
I write a simple one for you:
Set element Modifiers to true in Add_Order form :
and get it in main form:
public partial class main : Form
{
public main()
{
InitializeComponent();
Get_Frm2_Data();
}
private void Get_Frm2_Data()
{
Add_Order frm2 = new Add_Order();
List<string> info= new List<string>;
info.Add( frm2.textBox1.Text);
.
.
.
}
}
edit
or make an structure:
Add_Order.cs
public partial class Add_Order : Form
{
public Add_Order()
{
InitializeComponent();
}
public Info Get_Data()
{
return new Info() { _textBox3 = textBox3.Text,
_label6 = label6.Text,
_textBox2 = textBox2.Text,
_textBox1 = textBox1.Text,
};
}
}
struct Info
{
public string _textBox3;
public string _label6;
public string _textBox2;
public string _textBox1;
}
Mainform.cs
public partial class main : Form
{
public main()
{
InitializeComponent();
Get_Frm2_Data();
}
private void Get_Frm2_Data()
{
Add_Order frm2 = new Add_Order();
frm2.ShowDialog();
Info lst_data= frm2.Get_Data();
ListViewItem item = new ListViewItem();
item.Text = lst._textBox3;
item.SubItems.Add(lst._label6);
item.SubItems.Add(lst._textBox2);
item.SubItems.Add(lst._textBox1);
mainform.listView2.Items.Add(item);
}
}

Categories