I'm a new beginner on this topic. I created a c# win form. In this form, I have two textboxes and one label. What I want to do is create a delegate event to track the textbox's change and add up two numbers from textbox1 and textbox2. The label will show the result automatically. Hope someone can provide me a example for this, thank you so much! There is something I have right now,
events.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Project3
{
public delegate void Calculate(int obj1, int obj2);
public class events
{
int result;
public int Add(int x, int y)
{
result = x + y;
return result;
}
}
}
Form1.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Project3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
label1.Text ="";
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
}
}
If you just want to learn how to delegate the result into the label, and learn the delegate and event, here is a sample you may want to try and analyze for learning purposes:
Sample 1:
public delegate int CalculateEventHandler(object obj1, object obj2);
public partial class Form1 : Form
{
public event CalculateEventHandler Calculate;
private string OnCalculate(string text1, string text2)
{
string result = "0";
if (this.Calculate != null)
{
result = this.Calculate(this.textBox1.Text, this.textBox2.Text).ToString();
}
return result;
}
public Form1()
{
this.InitializeComponent();
this.InitializeEvent();
}
private void InitializeEvent()
{
this.Calculate += Form1_Calculate;
}
private int Form1_Calculate(object obj1, object obj2)
{
int a = 0;
int b = 0;
int.TryParse(obj1.ToString(), out a);
int.TryParse(obj2.ToString(), out b);
return a + b;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
this.label1.Text = OnCalculate(this.textBox1.Text, this.textBox2.Text);
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
this.label1.Text = OnCalculate(this.textBox1.Text, this.textBox2.Text);
}
}
Sample 2:
Form1.cs
public partial class Form1 : Form
{
public Form1()
{
this.InitializeComponent();
this.InitializeEvent();
}
private void InitializeEvent()
{
Event.Calculate += Event_Calculate;
}
private int Event_Calculate(object obj1, object obj2)
{
int x = 0;
int y = 0;
int.TryParse(obj1.ToString(), out x);
int.TryParse(obj2.ToString(), out y);
return Event.Add( x, y );
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
this.label1.Text = Event.OnCalculate(this.textBox1.Text, this.textBox2.Text).ToString();
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
this.label1.Text = Event.OnCalculate(this.textBox1.Text, this.textBox2.Text).ToString();
}
}
Event.cs
public delegate int CalculateEventHandler(object obj1, object obj2);
public class Event
{
static public event CalculateEventHandler Calculate;
static public int Add(int x, int y)
{
int result = x + y;
return result;
}
static public int OnCalculate( object obj1, object obj2 )
{
int result = 0;
if( Calculate != null )
{
result = Calculate(obj1, obj2);
}
return result;
}
}
NOTE: The above examples are by no means a good approach to calculate two values, this just serves as an example. The disadvantage of this approach would lead you to somehow spaghetti code, going back and forth to where the logic is going.
There is a simple solution
private void textBox1_TextChanged(object sender, EventArgs e)
{
try
{
if (textBox2.Text == string.Empty)
{
//textBox2.Text = (0).ToString();
label1.Text = ( Convert.ToInt32(textBox1.Text)).ToString();
}
else if (textBox1.Text == string.Empty)
{
label1.Text = (Convert.ToInt32(textBox2.Text)).ToString();
}
else
{
label1.Text = (Convert.ToInt32(textBox1.Text) + Convert.ToInt32(textBox2.Text)).ToString();
}
}
catch (Exception e3)
{
MessageBox.Show(e3.Message);
}
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
try
{
if (textBox2.Text == string.Empty)
{
//textBox2.Text = (0).ToString();
label1.Text = (Convert.ToInt32(textBox1.Text)).ToString();
}
else if (textBox1.Text == string.Empty)
{
label1.Text = (Convert.ToInt32(textBox2.Text)).ToString();
}
else
{
label1.Text = (Convert.ToInt32(textBox1.Text) + Convert.ToInt32(textBox2.Text)).ToString();
}
}
catch (Exception e3)
{
MessageBox.Show(e3.Message);
}
}
Related
I'm trying to understand the lock mechanism.
if I have multiple events to lock on different value should I use an object lock for each?
More serious code added:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Threading;
namespace ValueChangeOnEventForm
{
public partial class Form1 : Form
{
private Test_Onchange DataSource;
Thread Task1;
private bool Flag_Stop_Task1;
public Form1()
{
InitializeComponent();
graph1.ChartAreas[0].AxisX.ScrollBar.Enabled = true;
graph1.ChartAreas[0].AxisX.IsLabelAutoFit = true;
graph1.ChartAreas[0].AxisX.ScaleView.Size = 100;
graph2.ChartAreas[0].AxisX.ScrollBar.Enabled = true;
graph2.ChartAreas[0].AxisX.IsLabelAutoFit = true;
graph2.ChartAreas[0].AxisX.ScaleView.Size = 100;
DataSource = new Test_Onchange();
DataSource.ValueChanged += new EventHandler(EventValueChange);//Value input info
DataSource.SecondValueChange += new EventHandler(EventSecondValueChange);//second value
Task1 = new Thread(new ThreadStart(Task_1));//create the thread
Task1.Start();//start the thread
}
protected virtual void EventSecondValueChange(object sender, EventArgs e)
{
double valueMAX = 0, size = 0;
if (graph1.InvokeRequired)
{
graph1.Invoke(new MethodInvoker(delegate { graph1.Series["ValueOnGraph"].Points.AddY(DataSource.Value); }));
graph1.Invoke(new MethodInvoker(delegate { valueMAX = graph1.ChartAreas[0].AxisX.Maximum; }));
graph1.Invoke(new MethodInvoker(delegate { size = graph1.ChartAreas[0].AxisX.ScaleView.Size; }));
if (valueMAX - 10 > size)
{
graph1.Invoke(new MethodInvoker(delegate { graph1.ChartAreas[0].AxisX.ScaleView.Scroll(graph1.ChartAreas[0].AxisX.Maximum); }));
graph1.Invoke(new MethodInvoker(delegate { graph1.Series["ValueOnGraph"].Points.RemoveAt(0); }));
}
}
}
protected virtual void EventValueChange(object sender, EventArgs e)
{
double valueMAX=0,size=0;
if (graph2.InvokeRequired)
{
graph2.Invoke(new MethodInvoker(delegate { graph2.Series["ValueOnGraph2"].Points.AddY(DataSource.Secondvalue); }));
graph2.Invoke(new MethodInvoker(delegate { valueMAX = graph2.ChartAreas[0].AxisX.Maximum; }));
graph2.Invoke(new MethodInvoker(delegate { size = graph2.ChartAreas[0].AxisX.ScaleView.Size; }));
if (valueMAX - 10 > size)
{
graph2.Invoke(new MethodInvoker(delegate { graph2.ChartAreas[0].AxisX.ScaleView.Scroll(graph2.ChartAreas[0].AxisX.Maximum); }));
graph2.Invoke(new MethodInvoker(delegate { graph2.Series["ValueOnGraph2"].Points.RemoveAt(0); }));
}
}
}
private void Task_1()
{
while (!Flag_Stop_Task1)
{
Random RandVal = new Random();
Random RandVal2 = new Random();
int Value = RandVal.Next(0, 100);
int SecondValue = RandVal2.Next(50, 200);
DataSource.Value = Value;
DataSource.Secondvalue = SecondValue;
Thread.Sleep(100);
}
Flag_Stop_Task1 = false;
}
private void btn_StopTask_1_Click(object sender, EventArgs e)
{
Flag_Stop_Task1 = true;
}
}
}
And then
namespace ValueChangeOnEventForm
{
class Test_Onchange
{
private int value;
private int secondvalue;
protected object _lock = new object();
public event System.EventHandler ValueChanged;
public event System.EventHandler SecondValueChange;
protected virtual void OnValueChange()
{
lock (this._lock)
{
EventHandler eventvaluechange = ValueChanged;
if (eventvaluechange != null)
eventvaluechange(this, EventArgs.Empty);
}
}
protected virtual void OnSecondValueChange()
{
lock (this._lock)
{
EventHandler eventvaluechange = SecondValueChange;
if (eventvaluechange != null)
eventvaluechange(this, EventArgs.Empty);
}
}
public int Value
{
get { return this.value; }
set
{
if (value != this.value)
{//if value changed enter
this.value = value;
OnValueChange();
}
}
}
public int Secondvalue
{
get { return this.secondvalue; }
set
{
if (value != this.secondvalue)
{//if value changed enter
this.secondvalue = value;
OnSecondValueChange();
}
}
}
}
}
Do I need two lock (lock1 and lock2 object or only one for both value and secondvalue....?
Thanks a lot.
Update
Ok let's do it so.
I'm using beckhoff PLC which are real time Task PLC. and I'm reading two value on it when the value change. like this:
Form1 Class:
namespace RealTimeLock
{
using Beckhoff.App.Ads.Core;
using Beckhoff.App.Ads.Core.Plc;
using TwinCAT.Ads;
using System.IO;
public partial class Form1 : Form
{
private PLC PLCData;
public Form1()
{
InitializeComponent();
}
public Form1(IBAAdsServer _adsServer)
: this()
{
PLCData = new PLC(_adsServer);
PLCData.ErrorBoolChanged += new EventHandler(EventErrorChanged);//error info
PLCData.ForceValChanged += new EventHandler(EventForceChanged);//Force input info
}
protected virtual void EventErrorChanged(object sender, EventArgs e)
{
//state of error PLC
lv_ErrorInfo.Text = "PLC Error num : " + PLCData.i_ErrorID.ToString();
}
protected virtual void EventForceChanged(object sender, EventArgs e)
{//modify graphical data PLC Force data
lv_ForceInfo.Text = PLCData.i_ForceVal.ToString();
c_graphForceIN.Series["ForceData"].Points.AddY(PLCData.i_ForceVal);
if (c_graphForceIN.ChartAreas[0].AxisX.Maximum - 10 > c_graphForceIN.ChartAreas[0].AxisX.ScaleView.Size)
{
c_graphForceIN.ChartAreas[0].AxisX.ScaleView.Scroll(c_graphForceIN.ChartAreas[0].AxisX.Maximum);
c_graphForceIN.Series["ForceData"].Points.RemoveAt(0);
}
}
}
}
Error ID and Force change showed in Form1 label lv_ErrorID and lv_Force and graphForceIN add point.
The events handler on the other side (PLC class) looks like this:
PLC Class:
namespace RealTimeLock
{
using Beckhoff.App.Ads.Core;
using Beckhoff.App.Ads.Core.Plc;
using TwinCAT.Ads;
using System.IO;
public partial class Form1 : Form
{
private PLC PLCData;
public Form1()
{
InitializeComponent();
}
public Form1(IBAAdsServer _adsServer)
: this()
{
PLCData = new PLC(_adsServer);
PLCData.ErrorBoolChanged += new EventHandler(EventErrorChanged);//error info
PLCData.ForceValChanged += new EventHandler(EventForceChanged);//Force input info
}
protected virtual void EventErrorChanged(object sender, EventArgs e)
{
//state of error PLC
lv_ErrorInfo.Text = "PLC Error num : " + PLCData.i_ErrorID.ToString();
}
protected virtual void EventForceChanged(object sender, EventArgs e)
{//modify graphical data PLC Force data
lv_ForceInfo.Text = PLCData.i_ForceVal.ToString();
c_graphForceIN.Series["ForceData"].Points.AddY(PLCData.i_ForceVal);
if (c_graphForceIN.ChartAreas[0].AxisX.Maximum - 10 > c_graphForceIN.ChartAreas[0].AxisX.ScaleView.Size)
{
c_graphForceIN.ChartAreas[0].AxisX.ScaleView.Scroll(c_graphForceIN.ChartAreas[0].AxisX.Maximum);
c_graphForceIN.Series["ForceData"].Points.RemoveAt(0);
}
}
}
}
Does it seem to be correct coding for you guys? and while I have a real time task running there do I need to lock variables and if so, do I need two lock or only one??
Thanks for your remark on this!!
What I have to do is this:
Make an image gallery that has 5 buttons which each one select a folder of images.
Other two buttons for next and previous of the folder you are in. In my line 76, it says
argument 1: cannot convert from 'System.collection.Generic.list' to string
Any ideas?
Here's an image of the console
http://postimg.org/image/nct5pwdit/
Line 76 says:
pictureBox1.Load(semestres[semac].imagen[]);
I have the same command like 6 times.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
class semestres
{
public List<string> imagen = new List<string>();
private int _semestre;
public int canti;
public int actual;
public int c;
public semestres(int semestre, List<string> imagenes)
{
_semestre = semestre;
imagen = imagenes;
c = imagen.Count;
actual = 0;
}
public int semestre
{
get
{
return _semestre;
}
set
{
c = imagen.Count;
}
}
public int can
{
get
{
return c;
}
set
{
c = imagen.Count;
}
}
}
namespace Visor
{
public partial class Form1 : Form
{
private int cont;
private int semac;
private int _cant;
private int next;
private List<semestres> semestres = new List<semestres>();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
cont = semestres[semac].actual;
cont--;
if (cont >= 0)
{
pictureBox1.Load(semestres[semac].imagen[]);
semestres[semac].actual = cont;
}
else
{
// MessageBox("Esta es la primer imagen");
cont = 0;
semestres[semac].actual = cont;
pictureBox1.Load(semestres[semac].imagen);
}
}
private void button7_Click(object sender, EventArgs e)
{
cont = semestres[semac].actual;
next = semestres[semac].c;
cont++;
if (cont < next)
{
pictureBox1.Load(semestres[semac].imagen);
semestres[semac].actual = cont;
}
else
{
// MessageBox("Esta es la ultima imagen");
cont--;
semestres[semac].actual = cont;
pictureBox1.Load(semestres[semac].imagen(cont));
}
}
private void button2_Click(object sender, EventArgs e)
{
semac = 0;
try
{
if (semestres[0].c > 0)
{
cont = semestres[0].actual;
pictureBox1.Load(semestres[0].imagen(cont));
}
}
catch (Exception)
{
OpenFileDialog file = new OpenFileDialog();
file.InitialDirectory = #"C:\";
file.Filter = "Images (*.BMP; *.JPG; *.GIF)|*.BMP; *.JPG; *.GIF|" + "All files(*.*)|*.*";
file.FilterIndex = 1;
file.Multiselect = true;
file.RestoreDirectory = true;
file.ShowDialog();
string[] imgs = file.FileNames;
List<string> imagenes = new List<string>();
foreach (string imagen in imgs)
{
imagenes.Add(imagen);
}
semestres.Add(new semestres(1, imagenes));
pictureBox1.Load(imagenes[0]);
semestres[0].actual = 0;
cont = 0;
}
}
private void button6_Click(object sender, EventArgs e)
{
}
private void btn_3_Click(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void btn_sal_Click(object sender, EventArgs e)
{
}
private void btn_2_Click(object sender, EventArgs e)
{
}
}
}
So you have this:
pictureBox1.Load(semestres[semac].imagen);
Well the problem is that imagen is a List<string>. Picturebox.Load(string) takes a string, not a List<string>. So you need to get a string from that list instead of passing the whole list. One way would be:
pictureBox1.Load(semestres[semac].imagen[0]);
This would load the first image in that list.
Alternatively, you might be trying to do:
pictureBox1.Load(semestres[semac].imagen[cont]);
You just need to determine what the correct index is that you're trying to specify.
So I'm learning C# and just hit the Forms section and it's not going aswell as I hoped and Im feeling as my code isn't properly written.
Im also having problems figuring out how to output my calculated varible Im writting in with a button press.
What im asking for : Help with outputing my calculation from CalcFuelConsumptionPerKm() for example too a uneditible textbox by pressing a button
Also thanks for editing and helping out a beginner like me! You guys are awesome!
http://i.imgur.com/fcvV0yH.png > how Winform looks
Winform :
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
double obedomitor, fuel, price , oldvalue;
Fuel fc;
public Form1()
{
InitializeComponent();
fc = new Fuel();
}
private void GroupBox1_Enter(object sender, EventArgs e)
{
}
private void TextBox1_TextChanged(object sender, EventArgs e)
{
if (TextBox1.Text.Trim() != "")
{
try
{
obedomitor = Convert.ToDouble(TextBox1.Text.Trim());
fc.SetCurrentReading(obedomitor);
}
catch
{
MessageBox.Show("Please enter a valid number");
TextBox1.Text = "";
}
}
}
private void TextBox2_TextChanged(object sender, EventArgs e)
{
if (TextBox2.Text.Trim() != "")
{
try
{
oldvalue = Convert.ToDouble(TextBox1.Text.Trim());
fc.setPreviousReading(oldvalue);
}
catch
{
MessageBox.Show("Please enter a valid number");
TextBox2.Text = "";
}
}
}
private void Button1_Click(object sender, EventArgs e)
{
}
private void TextBox3_TextChanged(object sender, EventArgs e)
{
if (TextBox3.Text.Trim() != "")
{
try
{
fuel = Convert.ToDouble(TextBox3.Text.Trim());
fc.SetFuelAmount(fuel);
}
catch
{
MessageBox.Show("Please enter a valid number");
TextBox1.Text = "";
}
}
}
private void TextBox4_TextChanged(object sender, EventArgs e)
{
if (TextBox4.Text.Trim() != "")
{
try
{
price = Convert.ToDouble(TextBox4.Text.Trim());
fc.setUnitPrice(price);
}
catch
{
MessageBox.Show("Please enter a valid number");
TextBox1.Text = "";
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void TextBox5_TextChanged(object sender, EventArgs e)
{
}
private void TextBox7_TextChanged(object sender, EventArgs e)
{
}
}
}
My other class :
namespace WindowsFormsApplication1
{
class Fuel
{
double CurrentCal;
double FuelAmount;
double PreReading;
double unitPrice;
double km;
public void Fuelcalculator()
{
GetPreviousReading();
}
public double CalcConsumptionKilometerPerLiter()
{
km = CurrentCal - PreReading;
double litPerKm = FuelAmount / km;
return litPerKm;
}
public double CalcConsumptionPerMetricMile()
{
const double kmToMileFactor = 0.621371192;
double litPerKm = CalcConsumptionKilometerPerLiter();
double litPerMetricMile = litPerKm / kmToMileFactor;
return litPerMetricMile;
}
public double CalcCostPerKm()
{
double cost = (FuelAmount / km) * unitPrice;
return cost;
}
public double CalcFuelConsumptionPerKm()
{
double consumption = FuelAmount / km;
return consumption;
}
public double CalcConsumptionKilometerPerSweMil()
{
double literPerMil = CalcConsumptionKilometerPerLiter();
literPerMil = literPerMil*10;
return literPerMil;
}
public double GetCurrentReading()
{
return CurrentCal;
}
public double GetFuelAmount()
{
return FuelAmount;
}
public double GetPreviousReading()
{
double previous = CurrentCal;
return previous;
}
public double UnitPrice()
{
return unitPrice;
}
public void SetCurrentReading(double newValue)
{
CurrentCal = newValue;
}
public void SetFuelAmount(double newValue)
{
FuelAmount = newValue;
}
public void setPreviousReading(double newValue)
{
PreReading = newValue;
}
public void setUnitPrice(double newValue)
{
unitPrice = newValue;
}
}
}
If you want everything to update in realtime (which it sounds like you do) I would have a "UpdateResult" method that sets all the "output" text box's text properties:
private void UpdateResult()
{
TextBox3.Text = fc.CalcConsumptionKilometerPerLiter().ToString();
//All the others
}
And invoke that once you have validated the user's input in the "TextChanged" events. For example:
private void TextBox1_TextChanged(object sender, EventArgs e)
{
if (TextBox1.Text.Trim() != "")
{
try
{
obedomitor = Convert.ToDouble(TextBox1.Text.Trim());
fc.SetCurrentReading(obedomitor);
UpdateResults();
}
catch
{
MessageBox.Show("Please enter a valid number");
TextBox1.Text = "";
}
}
}
A couple quick notes since you are learning:
TextBoxX is not a good naming convention. Give your controls descriptive names
Since you mentioned it in a comment, double.TryParse is used for converting inputted strings into numbers. It shouldn't be involved in your output
Instead of using .Trim != "", you could just use !String.IsWhitespaceOrEmpty. It reads a lot better :)
If you expect user error, exceptions are expensive. Use double.TryParse instead of Convert.ToDouble (which really uses double.Parse) so you can have a safer, non-throwing check for user input.
i have a main form name fmMain
black mark is show browse file path to datagridview
and red mark is show form to datagridview.
i try to send path to datagridview and succes. here is the code
namespace tstIniF
{
public partial class fmMain : Form
{
string ConfigFileName = "app.cfg";
CFileConfig cFileConfig;
public fmMain()
{
InitializeComponent();
cFileConfig = new CFileConfig();
}
private void btnQuit_Click(object sender, EventArgs e)
{
Close();
}
private void btnDirectort_Click(object sender, EventArgs e)
{
if (dlgFolder.ShowDialog() != DialogResult.OK) return;
string s = dlgFolder.SelectedPath;
txtDirectory.Text = s;
/*p = (string)dgvConfigFile.Rows[idx++].Cells[1].Value; cFileConfig.cfgContourFile = p;
p = (string)dgvConfigFile.Rows[idx++].Cells[1].Value; cFileConfig.cfgConnectionString = p;*/
}
private void btnDirectBase_Click(object sender, EventArgs e)
{
if (dlgFile.ShowDialog() != DialogResult.OK) return;
string s = dlgFile.FileName;
int idx = 0;
dgvConfigFile.Rows[idx++].Cells[1].Value = cFileConfig.cfgBaseMapFile = s;
}
private void btnDirectCont_Click(object sender, EventArgs e)
{
if (dlgFile.ShowDialog() != DialogResult.OK) return;
string s = dlgFile.FileName;
int idx = 1;
dgvConfigFile.Rows[idx++].Cells[1].Value = cFileConfig.cfgContourFile = s;
}
private void btnDirectConn_Click(object sender, EventArgs e)
{
fConn op = new fConn();
op.ShowDialog();
}
}
}
red mark as btnDirectConn i show new form like this
and here is my form fConn
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace tstIniF
{
public partial class fConn : Form
{
public fConn()
{
InitializeComponent();
}
private void btnSave_Click(object sender, EventArgs e)
{
if (txtServ.Text.Trim() == "" || txtDb.Text.Trim() == "" || txtUid.Text.Trim() == "" || txtPwd.Text.Trim() == "")
{
MessageBox.Show("Mohon diisi semua field....");
}
else
{
//string textAll = this.txtServ.Text + this.txtDb.Text + this.txtUid.Text + this.txtPwd.Text;
fmMain frm = new fmMain();
frm._textBox = _textBox1;
this.Close();
//Close();
//frm.Show();
}
}
public string _textBox1
{
get { return txtServ.Text + txtDb.Text; }
}
}
}
the question is how to show data in form fConn to fmMain datagridview , i fill the fConn entry and close and back to fmMain so the result is
I would use delegate to handle this,
change fConnform as below
public partial class fConn : Form
{
public SaveDelegate SaveCallback;
public fConn()
{
InitializeComponent();
}
public void btnSave_Click(object sender, EventArgs e)
{
SaveCallback("set text what you need to send to main form here...");
}
}
And fmMain as below
public delegate void SaveDelegate(string text);
public partial class fmMain
{
public fmMain()
{
InitializeComponent();
}
private void btnDirectConn_Click(object sender, EventArgs e)
{
fConn op = new fConn();
op.SaveCallback += new SaveDelegate(this.SavemCallback);
op.ShowDialog();
}
private void SavemCallback(string text)
{
// you have text from fConn here ....
}
In the frmMain declare the fConn form at the class level so that it won't get disposed when the form closes. Now the frmMain can access any public objects in fConn.
Don't re-declare frmMain in fConn. Use _textBox = op._textBox1 right after op.ShowDialog();
I have a project that wants
A method that returns the current count.
A Constructor that sets the count to zero.
I have the first few down but need help with the return count to 0 and then the constructor. I need to do this by adding a counter class but I'm confused about the way to add it.
Can some one help me out?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Project10TC
{
public partial class Form1 : Form
{
int zero = 0;
int i = 1;
public Form1()
{
InitializeComponent();
}
private EventHandler myCounter;
// end of Form class
private class myCounter()
{
myCounter = new myCounter( );
}
private void exitToolStripMenuItem1_Click(object sender, EventArgs e)
{
this.Close();
}
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("Teancum Clark\nCS 1400\n Project 10");
}
private void button1_Click(object sender, EventArgs e)
{
textBox1.Text = (++i).ToString();
}
private void button2_Click(object sender, EventArgs e)
{
textBox1.Text = (--i).ToString();
}
private void button3_Click(object sender, EventArgs e)
{
textBox1.Text = (zero).ToString();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
}
}
public class Counter
{
public int Value { get; private set; }
public void Increment()
{
Value = Value + 1;
}
public void Decrement()
{
if (Value > 0) Value = Value - 1;
}
public Counter()
{
Value = 0;
}
}