get value in windows form into another class? - c#

Code On Windows form is
private void button2_Click(object sender, EventArgs e)
{
CandleCollection collection = GetCandleCollection();
int Dim = int.Parse(txt_agent.Text);
int NumParticles = int.Parse(txt_part.Text);
SOSManager p = new SOSManager(collection);
//this part
p.Dim = Dim;
p.NumParticles = NumParticles;
m_part = new ParticleSwarm(fit,p.Dim, p.NumParticles);
}
So,I want to add value that i put on textbox to this class.
public class SOSManager
{
private ParticleSwarm m_part;
public ParticleSwarm BackTestPartReport
{
get
{
return m_part;
}
}
I declare this
public int Dim; //this part
public int NumParticles;
public double fit;
to add value .
public SOSManager(CandleCollection collection)
{
CandleList = collection;
Calculate();
m_backTesting = new BackTesting(this);
fit = m_backTesting.fitness;
//this part
m_part = new ParticleSwarm(fit, Dim, NumParticles);
m_part.Calculate(Dim,NumParticles);
//
}
Now,I can't get value from windows from into this class . What should i do ?

Instead of setting the properties when it's too late, pass them into a constructor with more parameters:
public SOSManager(CandleCollection collection, int Dim, int NumParticles)
{
// If you still need to store them as properties:
this.Dim = Dim;
this.NumParticles = NumParticles;
Then call it like this:
SOSManager p = new SOSManager(collection, Dim, NumParticles);

Related

How to add variable to list from different class

I am creating app with data base inside in windows forms and i don't know how to pass information through one class to another like here:
public partial class Form1 : Form
{
public Form1()
{
private void button1_Click(object sender, EventArgs e)
{
BazaDanychTabela BazaDanychTabelaVariable = new BazaDanychTabela();
string rejestracja = Rejestracja.ToString();
var dataoddania = dateTimePicker1.Value;
var kosztczescizamiennych = numericUpDown2.Value;
var pracamechanikawgodzinach = numericUpDown1.Value;
var index = MechanicyBox.SelectedIndex;
if (index < 0)
{
MessageBox.Show("Prosze Wybrac Mechanika");
}
else
{
var imie = ListC[index].Name;
var nazwisko = ListC[index].Nazwisko;
// this one I want to add
BazaDanych NowyLog = new BazaDanych(imie, nazwisko, rejestracja, dataoddania, kosztczescizamiennych, pracamechanikawgodzinach);
MessageBox.Show("Nowy log zostal utworzony!");
}
}
}
}
And here is the other class:
public partial class BazaDanychTabela : Form
{
public List<BazaDanych> Logi = new List<BazaDanych>();
}
And I want to add "NowyLog" to "Logi" how?

Dynamic created event in c#

I have a dynamical create button object where I want it to send an event to the mainform when I click on a button inside this object.
I have the code like this :
class Class1
{
internal class FObj_BtnRow
{
private Button[] _Btnmembers;
internal event EventHandler<SelValue_EArgs>[] e_BtnMember; //subscribe to a change
internal class SelValue_EArgs : EventArgs//events args (selected value)
{//return arguments in events
internal SelValue_EArgs(Boolean ivalue) { refreshed = ivalue; }//ctor
internal Boolean refreshed { get; set; }//accessors
}
private Boolean[] _ActONOFFValue; //Pump=0, valveInput = 1, Shower = 3, Washtool = 4 , WashWPcs = 5
private Boolean ActONOFFValue(int number)
{
_ActONOFFValue[number] = !_ActONOFFValue[number];
{
if (e_BtnMember[number] != null && number == 0) e_BtnMember[number](this, new SelValue_EArgs(_ActONOFFValue[number]));
}
return _ActONOFFValue[number];
}
public FObj_BtnRow(String[] TxtBtn, String UnitName)//ctor
{
_Btnmembers = new Button[TxtBtn.Length];
e_BtnMember = new EventHandler<SelValue_EArgs>[TxtBtn.Length];
for (int i = 0; i < TxtBtn.Length / 2; i++)
{
_Btnmembers[i].Click += new EventHandler(_Btnmembers_Click);
}
}
protected virtual void _Btnmembers_Click(object sender, EventArgs e)
{
int index = Array.IndexOf(_Btnmembers, (Button)sender);
ActONOFFValue(index);
}
}
}
But in the line : internal event EventHandler[] e_BtnMember;
the compiler told me that I should use a delegate. I don't understand good this remark, could you help me?
At the end the mainform should only subscribe to the event button click it wants.
And then in main we could use it to now when a button in the object multibutton row is clicked... like this:
public void main()
{
String[] txtbtn = new String[] { "btn1", "btn2", "btn3" };
FObj_BtnRow thisbtnrow = new FObj_BtnRow(txtbtn);
thisbtnrow.e_BtnMember[0] += new EventHandler<FObj_BtnRow.SelValue_EArgs> (btnmember0haschanged);
}
public void btnmember0haschanged(object sender, FObj_BtnRow.SelValue_EArgs newvalue)
{
bool thisnewvalue = newvalue.refreshed;
}
Can you help me?
Thanks in advance!!
I solved the problem by myself, thanks for your advices.
Code
class Class1
{
internal class FObj_BtnRowtest
{
private Button[] _Btnmembers;
public delegate void del_Btnmember(Boolean value);
public del_Btnmember[] btnvaluechanged;
internal class SelValue_EArgs : EventArgs//events args (selected value)
{//return boolean arguments in events
internal SelValue_EArgs(Boolean ivalue) { refreshed = ivalue; }//ctor
internal Boolean refreshed { get; set; }//accessors
}
private Boolean[] _ActONOFFValue;
private Boolean ActONOFFValue(int number)
{
_ActONOFFValue[number] = !_ActONOFFValue[number];
return _ActONOFFValue[number];
}
public FObj_BtnRowtest(int numofbtn, String UnitName)//ctor
{
_Btnmembers = new Button[numofbtn];
btnvaluechanged = new del_Btnmember[numofbtn];
_ActONOFFValue = new bool[numofbtn];
for (int i = 0; i < numofbtn / 2; i++)
{
_Btnmembers[i].Click += new EventHandler(_Btnmembers_Click);
}
}
protected virtual void _Btnmembers_Click(object sender, EventArgs e)
{
int index = Array.IndexOf(_Btnmembers, (Button)sender);
if (btnvaluechanged[index] != null) btnvaluechanged[index](ActONOFFValue(index));
}
}
}
And then in main
thisrow = new Class1.FObj_BtnRowtest(4,"thisunittest");//4 buttons
thisrow.btnvaluechanged[0] += new Class1.FObj_BtnRowtest.del_Btnmember(valuetesthaschanged);//to subscribe to btn0 change
using delegates make it easier. and yes we do need those kinds of stuffs to make code clearer and faster to developp.
Thanks all!!

Access list in class from another class

I know this is asked before, but I can't seem to figure it out.
I have a class which makes a list from a datagridview. I want to do stuff with this list in another class but I cant't access it. I can access it from Form1.cs like the code underneath. How do I access the list from a random class like I can in Form1.cs?
//Opens the file dialog and assigns file path to Textbox
OpenFileDialog browseButton = new OpenFileDialog();
private void browse_Click(object sender, EventArgs e)
{
browseButton.Filter = "Excel Files |*.xlsx;*.xls;*.xlsm;*.csv";
if (browseButton.ShowDialog() == DialogResult.OK)
{
ExcelPath.Text = browseButton.FileName;
fileExcel = ExcelPath.Text;
//SetAttributeValue(ExcelPath, fileExcel);
//nylp();
/*
////IMPORTERER 10TAB-DATA FRA EXCEL TIL DATAGRIDVIEW////
tenTabLine.fileExcel = fileExcel;
tenTabLine.tenTab(tenTabDgv);
*/
////IMPORTERER NYLPDATA TIL DATAGRIDVIEW////
nylpLine.fileExcel = fileExcel;
nylpLine.nylpData(nylpDgv);
////TAR DATA I NYLPDGV DATAGRIDVIEW OG BEREGNER VERTIKALE ELEMENTER////
vertElementer.vertBueDGV(nylpDgv, vertElementerDgv);
GetVertElementasList getList = new GetVertElementasList();
var TEST = getList.vertList(vertElementerDgv);
MessageBox.Show(TEST[5].p2.ToString());
}
else return;
}
When I try to do something like this I get lot of errors in Error List:
class GetKoord
{
GetVertElementasList getList = new GetVertElementasList();
var TEST = getList.vertList(vertElementerDgv);
MessageBox.Show(TEST[5].p2.ToString());
}
This is my list class
class GetVertElementasList
{
private List<vertEl> vertElementList = new List<vertEl>();
public List<vertEl> vertList(DataGridView VertElementer)
{
for (int i = 0; i<VertElementer.Rows.Count - 1; i++)
{
vertElementList.Add(new vertEl
{
elNr = (int)VertElementer.Rows[i].Cells[0].Value,
p1 = (double)VertElementer.Rows[i].Cells[1].Value,
p2 = (double)VertElementer.Rows[i].Cells[2].Value,
z1 = (double)VertElementer.Rows[i].Cells[3].Value,
z2 = (double)VertElementer.Rows[i].Cells[4].Value,
heln1 = Convert.ToDouble(VertElementer.Rows[i].Cells[5].Value),
heln2 = (double)VertElementer.Rows[i].Cells[6].Value
});
}
return vertElementList;
}
}
public class vertEl
{
private int _elNr;
private double _p1;
private double _p2;
private double _z1;
private double _z2;
private double _nylpRad;
private double _heln1;
private double _heln2;
public int elNr
{
get { return _elNr; }
set { _elNr = value; }
}
public double p1
{
get { return _p1; }
set { _p1 = value; }
}
public double p2
{
get { return _p2; }
set { _p2 = value; }
}
public double z1
{
get { return _z1; }
set { _z1 = value; }
}
public double z2
{
get { return _z2; }
set { _z2 = value; }
}
public double nylpRad
{
get { return _nylpRad; }
set { _nylpRad = value; }
}
public double heln1
{
get { return _heln1; }
set { _heln1 = value; }
}
public double heln2
{
get { return _heln2; }
set { _heln2 = value; }
}
}
EDIT:
I've made it work now except that I get a out of range exception.
class code is:
class GetKoord
{
public GetVertElementasList getList = new GetVertElementasList();
BridgGeometry obj = new BridgGeometry();
public void foo()
{
var TEST = getList.vertList(obj.vertElementerDgv);
MessageBox.Show(TEST[2].elNr.ToString());
}
}
In form1 or BridgGeometry as it is called in my project I have which is giving me out of range exception.
GetKoord getZ = new GetKoord();
getZ.foo();
EDIT2:
The code underneath works and gives a message box with some value in list. But the method foo() in class above gives a out of range error.
private void browse_Click(object sender, EventArgs e)
{
browseButton.Filter = "Excel Files |*.xlsx;*.xls;*.xlsm;*.csv";
if (browseButton.ShowDialog() == DialogResult.OK)
{
////TESTING////WORKING CODE AND GIVES A MESSAGEBOX WITH VALUE
GetVertElementasList getVertList = new GetVertElementasList();
var TEST = getVertList.vertList(vertElementerDgv);
MessageBox.Show(TEST[2].elNr.ToString());
}
else return;
}
I think you are trying to access the variable directly in the class; which will not work. Try following
class GetKoord
{
GetVertElementasList getList = new GetVertElementasList();
public void foo()
{
var TEST = getList.vertList(vertElementerDgv);
MessageBox.Show(TEST[5].p2.ToString());
}
}
I tested your code and it seemed to worked. My code for you and #Anand
No Errors, except for empty Lists. But thats because I didn't fed it any information. So, there shouldn't be a problem.
#Grohl maybe try my code and comment where the error is displayed. This should be the most easy way to find the problem.
TestClass which represents class GetKoord
namespace TestForm
{
class TestClass
{
public TestClass()
{
DataGridView tmp = new DataGridView();
GetVertElementasList getList = new GetVertElementasList();
var TEST = getList.vertList(tmp);
MessageBox.Show(TEST[5].p2.ToString());
}
}
}
The GetVertElementasList
namespace TestForm
{
class GetVertElementasList
{
private List<vertEl> vertElementList = new List<vertEl>();
public List<vertEl> vertList(DataGridView VertElementer)
{
for (int i = 0; i < VertElementer.Rows.Count - 1; i++)
{
vertElementList.Add(new vertEl
{
elNr = (int)VertElementer.Rows[i].Cells[0].Value,
p1 = (double)VertElementer.Rows[i].Cells[1].Value,
p2 = (double)VertElementer.Rows[i].Cells[2].Value,
z1 = (double)VertElementer.Rows[i].Cells[3].Value,
z2 = (double)VertElementer.Rows[i].Cells[4].Value,
heln1 = Convert.ToDouble(VertElementer.Rows[i].Cells[5].Value),
heln2 = (double)VertElementer.Rows[i].Cells[6].Value
});
}
return vertElementList;
}
}
//Some other stuff
}
Last but not least. the code from the button click event:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void simpleButton1_Click(object sender, EventArgs e)
{
DataGridView tmp = new DataGridView();
GetVertElementasList getList = new GetVertElementasList();
var TEST = getList.vertList(tmp);
MessageBox.Show(TEST[5].p2.ToString());
TestClass tmpClass = new TestClass();
}
}
To #Grohl EDIT2:
It hurts to see that you are trying to read data without checking if there is any. In such cases, check!
Like this:
if(TEST.Count() >= 3)
{
MessageBox.Show(TEST[2].elNr.ToString());
}
It should debug at be smooth at runtime. I think your problem is getting the data.
Make sure you load the needed data and check if it isn't null.

C# windows Form help listing results from string array on to MessaeBox or new Form

enter image description here
Ok i need little help with this project. This is my main windows in widows Form
and this is code from MainForm:
using System;
using System.Windows.Forms;
namespace TestNiCat1
{
public partial class Form1 : Form
{
private Atleticar atleticar;
public Atleticar noviAtleticar { get { return atleticar; } }
public string tipDiscipline;
private string imeDiscipline { get; set; }
private int brojUcesnika { get; set; }
public string [] nizUcesnika { get; set; }
public string[] getskakac()
{
string[] arr = new string[listBox1.Items.Count];
for (int i = 0; i < listBox1.Items.Count; i++)
{
arr[i] = listBox1.Items[i].ToString();
}
return arr;
}
//listBox2.trkac to array
public string[] getTrkac()
{
string[] arr1 = new string[listBox2.Items.Count];
for (int i = 0; i < listBox1.Items.Count; i++)
{
arr1[i] = listBox2.Items[i].ToString();
}
return arr1;
}
public Form1()
{
InitializeComponent();
}
private void buttonDodaj_Click(object sender, EventArgs e)
{
if (radioButtonSkok.Checked)
{
atleticar = new Skakac(textBoxIme.Text,textBoxPrezime.Text,float.Parse(textBoxRezultat.Text));
this.listBox1.Items.Add(atleticar);
}
else if (radioButtonPrepone.Checked)
{
atleticar = new Trkac(textBoxIme.Text, textBoxPrezime.Text, float.Parse(textBoxRezultat.Text));
this.listBox2.Items.Add(atleticar);
}
}
private void buttonTrazi_Click(object sender, EventArgs e)
{
if (radioButtonSkok.Checked)
{
getskakac();
}
else if (radioButtonPrepone.Checked)
{
getTrkac();
}
}
}
}
i have 1 abstract class and 2 classes code :
namespace TestNiCat1
{
public abstract class Atleticar
{
protected string ime { get; set; }
protected string prezime { get; set; }
protected float rezultat { get; set; }
public override string ToString()
{
return ime + " " + prezime + " " + rezultat;
} }//abstract Atleticar
public class Skakac : Atleticar
{
private String tip;
public Skakac(String ime,String prezime,float rezultat)
{
this.rezultat = rezultat;
this.ime = ime;
this.prezime = prezime;
}
}public class Trkac : Atleticar
{
public Trkac(String ime,String prezime,float rezultat)
{
this.rezultat = rezultat;
this.ime = ime;
this.prezime = prezime;
}
}
}
what i need is to List all items when pressed Trazi button that will be stored into Listbox1 or listbox2 and sort them by highest result stored.
I made when i press trazi button to store all listbox items into String Array but i need help hot to sort them by highest score and show them into new messageBox OR if there is a way to sort items in listBox immidiatly as they been made in listbox by highest number.
I think this is what you look for
public string[] getskakac()
{
listBox1.Sorted = true;
return listBox1.Items.Cast<string>().ToArray();
}
It appears you may be better off having your abstract class Atleticar implement an IComparable interface. This will make sorting much easier and give you complete control over how Atleticar objects are sorted.
First you need to indicate that the Atleticar class will implement a CompareTo method for sorting:
public abstract class Atleticar : IComparable
Below is the CompareTo method needed when you implement the IComparable interface. I simply compare each object based on the rezultat variable but you can customize this to sort on another variable(s) if needed.
public int CompareTo(object obj) {
Atleticar other = (Atleticar)obj;
if (this.rezultat == other.rezultat)
return 0;
if (this.rezultat > other.rezultat)
return 1;
else
return -1;
}
Below I created a form with a ListBox and two buttons. One button fills the list box with some unsorted Atleticar objects. Button two sorts the list. I do not think you can directly sort the listbox1.Items so I created a list of Atleticar objects from the list box items and then sorted it, cleared the list box items then update it with the sorted data.
private List<Atleticar> GetData() {
List<Atleticar> list = new List<Atleticar>();
Atleticar atl = new Trkac("textBoxIme.Text1", "textBoxPrezime.Text1", 12);
list.Add(atl);
atl = new Trkac("textBoxIme.Text2", "textBoxPrezime.Text2", 1);
list.Add(atl);
atl = new Trkac("textBoxIme.Text3", "textBoxPrezime.Text3", 122);
list.Add(atl);
atl = new Trkac("textBoxIme.Text4", "textBoxPrezime.Text4", 99);
list.Add(atl);
atl = new Trkac("textBoxIme.Text5", "textBoxPrezime.Text5", 03);
list.Add(atl);
atl = new Trkac("textBoxIme.Text6", "textBoxPrezime.Text6", 67);
list.Add(atl);
atl = new Trkac("textBoxIme.Text7", "textBoxPrezime.Text7", -12);
list.Add(atl);
return list;
}
private void buttonGetData_Click(object sender, EventArgs e) {
listBox1.Items.Clear();
foreach (Atleticar a in GetData()) {
listBox1.Items.Add(a);
}
}
private void buttonSort_Click(object sender, EventArgs e) {
List<Atleticar> list = new List<Atleticar>();
foreach (Atleticar a in listBox1.Items) {
list.Add(a);
}
list.Sort();
listBox1.Items.Clear();
foreach (Atleticar a in list) {
listBox1.Items.Add(a);
}
}
Hope this makes sense.

How to add one value of an array to a string

Basically I have a string array with a few text values in it. I want to on load assign a value from the array to a string then on button press change it to the next value, once it gets to the end it needs to loop around. So the string will be set to one value in the array then get changed after a button click.
Array stringArray = Array.CreateInstance(typeof(String), 3);
stringArray.SetValue("ssstring", 0);
stringArray.SetValue("sstring", 1);
stringArray.SetValue("string", 2);
Here's some code to get you going. You dont mention what environment you're using (ASP.NET, Winforms etc..)
When you provide more info I'll update my example so its more relevant.
public class AClass
{
private int index = 0;
private string[] values = new string[] { "a", "b", "c" };
public void Load()
{
string currentValue = this.values[this.index];
}
private void Increment()
{
this.index++;
if (this.index > this.values.Length - 1)
this.index = 0;
}
private void button1_Click(object sender, EventArgs e)
{
Increment();
}
}
Set Index = 0
Let Count = StringArray.Count
On Button Click Do the following
Set Return Value As StringArray(Index)
Set Index = ( Index + 1 ) Mod Count
You can program that algorithm in C#...
You could have a class that holds and iterates your strings like:
class StringIterator
{
private int _index = 0;
private string[] _strings;
public StringIterator(string[] strings)
{
_string = strings;
}
public string GetString()
{
string result = _string[_index];
_index = (_index + 1) % _strings.Length;
return result;
}
}
The usage would look like
class Program
{
private string _theStringYouWantToSet;
private StringIterator _stringIter;
public Program()
{
string[] stringsToLoad = { "a", "b", "c" };
_stringIter = new StringIterator(stringsToLoad);
_theStringYouWantToSet = _stringIter.GetString();
}
protected void ButtonClickHandler(object sender, EventArgs e)
{
_theStringYouWantToSet = _stringIter.GetString();
}
}

Categories

Resources