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?
Related
so what i would like to is setting back some attributes after an Custom Event is finished.
Scenario i have a save BackupDrives Class that does collection of data and then offers a Event to be called after its done.
Changing object properties can be done by button click, what i would like is to set them back to the same value after the event is finished.
Button click does the thing :
private void bbdrives_Click(object sender, RoutedEventArgs e)
{
backup.SaveDrives += OnSavingDrives;
backup.DrivesSave();
Drive_text.Visibility = Visibility.Visible;
drives_progres.Visibility = Visibility.Visible;
drives_progres.IsIndeterminate = true;
}
Now the triggered event method is not able to change the properties back.
private void OnSavingDrives(object sender, DrivesEventArgs e)
{
Directory.CreateDirectory(....);
File.WriteAllLines(e.Something, e.List2ToSave);
File.WriteAllLines(e.Something_lse, e.List1ToSave);
Drive_text.Visibility = Visibility.Collapsed;
drives_progres.Visibility = Visibility.Collapsed;
drives_progres.IsIndeterminate = false;
}
How do i do this. Since this does not work.
And on other thig here to - when i run the GUI i need to click 2 times one the same button to start it all. Done Code Clean + Rebuild. Still the same.
---EDIT---
As for code here you go.
This is a Class for collecting method and event.
public class DrivesEventArgs : EventArgs
{
string MYDOC = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
const string backup_Drives = "....";
const string backup_Letters = "...";
public List<string> List1ToSave = new List<string>();
public List<string> List2ToSave = new List<string>();
public string SAVE_DRIVE_Letter
{
get
{
string name = Path.Combine(MYDOC, backup_Letters);
return name;
}
}
public string SAVE_DRIVE_Path
{
get
{
string name = Path.Combine(MYDOC, backup_Drives);
return name;
}
}
}
public class DrivesBackup
{
private const string path = "Network";
private List<string> drives_to_save = new List<string>();
private List<string> letters_for_drives = new List<string>();
private RegistryKey reg1, reg2;
public event EventHandler<DrivesEventArgs> SaveDrives;
public void DrivesSave()
{
var data = new DrivesEventArgs();
try
{
if (drives_to_save.Count == 0)
{
reg1 = Registry.CurrentUser.OpenSubKey(path);
string[] mounted_drives = reg1.GetSubKeyNames();
foreach (var drive in mounted_drives)
{ //get all UNC Paths from mounted_drives
string[] getUNC = { path, drive };
string fullUNC = Path.Combine(getUNC);
reg2 = Registry.CurrentUser.OpenSubKey(fullUNC);
string UNCPath = reg2.GetValue("RemotePath").ToString(); //getting UNC PATH
Console.WriteLine(UNCPath);
data.List1ToSave.Add(drive.ToString());
data.List2ToSave.Add(UNCPath);
OnSaveDrives(data);
}
}
}
catch (Exception er)
{
throw er;
}
}
protected virtual void OnSaveDrives(DrivesEventArgs eD)
{
SaveDrives?.Invoke(this, eD);
}
Now here is the MAINWINDOW WPF
public partial class MainWindow : Window
{
DrivesBackup backup = new DrivesBackup();
public MainWindow()
{
InitializeComponent();
}
private void bbdrives_Click(object sender, RoutedEventArgs e)
{
backup.DrivesSave();
backup.SaveDrives += OnSavingDrives;
Drive_text.Visibility = Visibility.Visible;
drives_progres.Visibility = Visibility.Visible;
drives_progres.IsIndeterminate = true;
}
private void OnSavingDrives(object sender, DrivesEventArgs e)
{
Directory.CreateDirectory(System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), #"SEG-Backup"));
File.WriteAllLines(e.SAVE_DRIVE_Path, e.List2ToSave);
File.WriteAllLines(e.SAVE_DRIVE_Letter, e.List1ToSave);
Drive_text.Visibility = Visibility.Collapsed;
drives_progres.Visibility = Visibility.Collapsed;
drives_progres.IsIndeterminate = false;
}
}
Now i do hope this would make some things more clear.
I get this weird NullReferenceExcpetion, in a WPF application. I don't get this every time, even if I do same operation. Can anyone please explain the reason for this,
public class AmazonUrl
{
public string Url { get; set; }
}
public partial class MainWindow : Window
{
public ObservableCollection<AmazonUrl> AmazonUrlList { get; set; }
public MainWindow()
{
InitializeComponent();
DataContext = this;
AmazonUrlList = new ObservableCollection<AmazonUrl>();
}
public List<string> getURLList()
{
List<string> urlList = new List<string>();
for(int i = 0; i < AmazonUrlList.Count; i++)
{
AmazonUrl url = AmazonUrlList[i];
if (url == null)
continue;
String str = url.Url.ToString().Trim();
if (str.Length > 0)
urlList.Add(str);
}
return urlList;
}
private void openMenuItem_Click(object sender, RoutedEventArgs e)
{
List<string> urlList = getURLList();//This is where exception occur
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "SCR File (.scr)|*.scr|All Files|*.*";
if (openFileDialog.ShowDialog() != true){ ... }
}
Note: After adding these lines I made lots of changes to the application, and recompiled several times. So this is not a problem with Build or Compiling
Edit: My stack trace can find from here, https://pastebin.com/2vyH1qah
I can't reproduce the error, it must be something with your collection. What does your collection look like?
This should fix the problem either way--
public partial class MainWindow : Window
{
private static object lockObj = new object(); //Add
...
public List<string> getURLList()
{
List<string> urlList = new List<string>();
for (int i = 0; i < AmazonUrlList.Count; i++)
{
Amazon url = new AmazonUrl(); // Add
url = AmazonUrlList[i]; // Update
...
private void openMenuItem_Click(object sender, RoutedEventArgs e)
{
lock (lockObj) // Add
{
List<string> urlList = getURLList(); //This is where exception occur
}
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);
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.
let me describe the situation. Winforms C#
I have xml file with data. I load this data to an user defined class object using Deserialize.
Based on this object with data, I build [in Form] UI: many tabPages of custom controls (textBox, 2 buttons in groupBox). I can also save this user defined class object using Serialize to XML file.
Question:
When I update textBox.Text in Form UI in custom control I do not know how to keep connection with the object with data (Layout layout) and save the updated object with data to XML. The change of text happens only in user custom control TextBox. I want to update data from UI in data object (layout) and then simply save with Serialization.
user class:
public class Layout
{
public string type;
public List<TabPage> TabPageList;
public Layout()
{
this.TabPageList = new List<TabPage>();
}
}
public class TabPage
{
public string text;
public List<ActionGroup> ActionGroupList;
public TabPage()
{
this.ActionGroupList = new List<ActionGroup>();
}
}
public class ActionGroup
{
public string type;
public string text;
public string sourceLocal;
public string sourceRemote;
public ActionGroup()
{
this.type = string.Empty;
this.text = string.Empty;
this.sourceLocal = string.Empty;
this.sourceRemote = string.Empty;
}
}
Custom control:
public partial class ViewActionGroup : UserControl
{
public string type;
public string text;
public string sourceLocal;
public string sourceRemote;
public bool isRemote;
public bool isDone;
public ViewActionGroup()
{
this.type = string.Empty;
this.text = string.Empty;
this.sourceLocal = string.Empty;
this.sourceRemote = string.Empty;
this.isRemote = false;
this.isDone = false;
InitializeComponent();
}
public ViewActionGroup(ActionGroup actionGroup)
{
this.type = actionGroup.type;
this.text = actionGroup.text;
this.sourceLocal = actionGroup.sourceLocal;
this.sourceRemote = actionGroup.sourceRemote;
this.isRemote = false;
this.isDone = false;
InitializeComponent();
groupBox1.Text = text;
button1.Text = type;
button1.Click += new EventHandler(Button_Click);
textBox1.Text = sourceLocal;
textBox1.TextChanged += new EventHandler(textBox1_TextChanged);
}
public void ChangeToRemote()
{
isRemote = true;
textBox1.Text = this.sourceRemote;
}
public void ChangeToLocal()
{
isRemote = false;
textBox1.Text = this.sourceLocal;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (this.isRemote)
{
this.sourceRemote = textBox1.Text;
}
else
{
this.sourceLocal = textBox1.Text;
}
}
Creating UI where I loose connection between UI and data object:
private void CreateLayout(Layout layout)
{
this.Text = layout.type;
TabControl tabControl = new TabControl();
tabControl.Dock = DockStyle.Fill;
int tabCount = 0;
foreach (TabPage tabpage in layout.TabPageList)
{
int actionCount = 0;
tabControl.TabPages.Add(tabpage.text);
foreach (ActionGroup actionGroup in tabpage.ActionGroupList)
{
ViewActionGroup view = new ViewActionGroup(actionGroup);
view.Location = new Point(0, actionCount * view.Height);
tabControl.TabPages[tabCount].Controls.Add(view);
tabControl.TabPages[tabCount].AutoScroll = true;
tabControl.TabPages[tabCount].AutoScrollMinSize = new System.Drawing.Size(tabControl.Width/2,tabControl.Height);
actionCount++;
}
tabCount++;
this.panelMain.Controls.Add(tabControl);
}
}
There are two common ways:
One is a routine WriteDataIntoControls and another ReadDataFromControls where you transfer the data to and from your visible controls manually (advantage: highest degree of control). In this case you'd have to read your object from your XML source, deserialize it into your business object and create all visible controls together with their value. On saving you'd have to transfer all values into your business object and serizalize it after this.
The second is DataBinding (advantage: highest degree of automation). Read here: https://msdn.microsoft.com/en-us/library/ef2xyb33%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396
You can bind to simple values as well as to lists (including navigation) or complex objects.
You find a tutorial here: http://www.codeproject.com/Articles/24656/A-Detailed-Data-Binding-Tutorial
#Shnugo Thank You for your feedback. The tutorial you posted did not help because it is too hard for me but Data Binding topic gave me some clue.
Here easy tutorial in VB actually but simple. It helped me to do it quickly in C#.
https://www.youtube.com/watch?v=jqLQ2K9YY2A
C# solution
class MyObject
{
string name;
public MyObject()
{ }
public string Name
{
get { return name;}
set { name = value; }
}
}
public partial class Form1 : Form
{
MyObject obj = new MyObject();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
obj.Name = "Lucas";
textBox1.DataBindings.Add("Text", obj, "Name", true, DataSourceUpdateMode.OnPropertyChanged);
}
private void button1_Click(object sender, EventArgs e)
{
label1.Text = obj.Name;
}
}