开发者

Getting values from method from other form

I'm having a problem where I retrieve a value in a method in a different form to my main form.

Here is my code: (This is the main form where i want to retrieve the value.)

private void EstimationComp_Click(object sender, EventArgs e)
{
    PaintingFender pff = new PaintingFender();
    textBox8.Text = panels;
    textBox30.Text = amounts;
    panels = pff.panel();
    descr = pff.desc();
    status = pff.stats();
    amounts = pff.amount();
    dtg.RowCount = 5;
    dtg[0, 0].Value = panels;
    dtg[1, 0].Value = descr;
    dtg[2, 0].Value = status;
    dtg[3, 0].Value = amounts;
}

This is the form where I declared the method in which I want to retrieve the value from the add button when a radiobutton is selected:

public string panel()
{
    return p;
}

public string desc()
{
    return d;
}
public string stats()
{
    return s;
}
public string amount()
{
    return a;
}

private void TADD_bump_Click(object sender, EventArgs e)
{
    try
    {
        if ((conn == null) || (conn.State != ConnectionState.Open))
        {
            MessageBox.Show("unab开发者_高级运维le to connect to database", "error");
            return;
        }
        else
        {
            OleDbCommand cmd = new OleDbCommand("select * from p_painting");
            cmd.CommandType = CommandType.Text;
            cmd.Connection = conn;
            da = new OleDbDataAdapter(cmd);
            ds = new DataSet("ds");
            da.Fill(ds);
            ds.Tables[0].TableName = "table_mirror";
            dtg.DataSource = ds.Tables["table_mirror"];
        }
    }
    catch (Exception x)
    {
        MessageBox.Show(x.Message);
    }

    if (frontbumper.Checked == true)
    {
        status();
        d = frontbumper.Text;
        a = textBox2.Text;
        p = "Fender";
        if (bump_light.Checked == true)
        {
            s = "Light Repair";
        }
        if (bump_moderate.Checked == true)
        {
            s = "Moderate Repair";
        }
        if (bump_heavy.Checked == true)
        {
            s = "Heavy Repair";
        }
        if (bump_replacement.Checked == true)
        {
            s = "Replacement";
        }
    }

I traced the method and I think it does not get the value from the button when it is clicked because from the beginning of the program the method is already performed. I want to perform the method only when the button is clicked so that I can retrieve the value from the TADD button to be passed the string values in my main form namely estimationcomp.


on your main form create a public field. A property would be better.

set this field or property in the method that has the variable containing the value you want to share.

now from the child from reference the parent form instance and you should have access to your field containing the value you want.


private void EstimationComp_Click(object sender, EventArgs e) 
{ 

NameOfDifferentForm nodf = new NameOfDifferentForm();
string s = nodf.panel();

//or

string s = new NameOfDifferentForm.panel();
}


I didn't quite good understand your problem. So i just made up a form, that calls some childs and processes the answer from these childs. Maybe this example can help.

Form.Designer.cs

namespace WindowsFormsApplication
{
    partial class FormMain
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.buttonCancel = new System.Windows.Forms.Button();
            this.textBoxMessage = new System.Windows.Forms.TextBox();
            this.buttonOk = new System.Windows.Forms.Button();
            this.buttonDialogResult = new System.Windows.Forms.Button();
            this.buttonEvent = new System.Windows.Forms.Button();
            this.SuspendLayout();
            // 
            // buttonCancel
            // 
            this.buttonCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
            this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this.buttonCancel.Location = new System.Drawing.Point(255, 138);
            this.buttonCancel.Name = "buttonCancel";
            this.buttonCancel.Size = new System.Drawing.Size(75, 23);
            this.buttonCancel.TabIndex = 4;
            this.buttonCancel.Text = "&Cancel";
            this.buttonCancel.UseVisualStyleBackColor = true;
            this.buttonCancel.Click += new System.EventHandler(this.OnButtonExitClick);
            // 
            // textBoxMessage
            // 
            this.textBoxMessage.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
                        | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.textBoxMessage.Location = new System.Drawing.Point(12, 12);
            this.textBoxMessage.Multiline = true;
            this.textBoxMessage.Name = "textBoxMessage";
            this.textBoxMessage.Size = new System.Drawing.Size(318, 120);
            this.textBoxMessage.TabIndex = 0;
            this.textBoxMessage.TextChanged += new System.EventHandler(this.OnTextChanged);
            // 
            // buttonOk
            // 
            this.buttonOk.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
            this.buttonOk.DialogResult = System.Windows.Forms.DialogResult.OK;
            this.buttonOk.Location = new System.Drawing.Point(174, 138);
            this.buttonOk.Name = "buttonOk";
            this.buttonOk.Size = new System.Drawing.Size(75, 23);
            this.buttonOk.TabIndex = 3;
            this.buttonOk.Text = "&OK";
            this.buttonOk.UseVisualStyleBackColor = true;
            this.buttonOk.Click += new System.EventHandler(this.OnButtonExitClick);
            // 
            // buttonDialogResult
            // 
            this.buttonDialogResult.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
            this.buttonDialogResult.Location = new System.Drawing.Point(12, 138);
            this.buttonDialogResult.Name = "buttonDialogResult";
            this.buttonDialogResult.Size = new System.Drawing.Size(75, 23);
            this.buttonDialogResult.TabIndex = 1;
            this.buttonDialogResult.Text = "by Result";
            this.buttonDialogResult.UseVisualStyleBackColor = true;
            this.buttonDialogResult.Click += new System.EventHandler(this.OnButtonResultClick);
            // 
            // buttonEvent
            // 
            this.buttonEvent.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
            this.buttonEvent.Location = new System.Drawing.Point(93, 138);
            this.buttonEvent.Name = "buttonEvent";
            this.buttonEvent.Size = new System.Drawing.Size(75, 23);
            this.buttonEvent.TabIndex = 2;
            this.buttonEvent.Text = "by Event";
            this.buttonEvent.UseVisualStyleBackColor = true;
            this.buttonEvent.Click += new System.EventHandler(this.OnButtonEventClick);
            // 
            // Form1
            // 
            this.AcceptButton = this.buttonOk;
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.CancelButton = this.buttonCancel;
            this.ClientSize = new System.Drawing.Size(342, 173);
            this.Controls.Add(this.buttonEvent);
            this.Controls.Add(this.buttonDialogResult);
            this.Controls.Add(this.buttonOk);
            this.Controls.Add(this.textBoxMessage);
            this.Controls.Add(this.buttonCancel);
            this.MinimumSize = new System.Drawing.Size(350, 200);
            this.Name = "Form1";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
            this.Text = "My Dialog";
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Button buttonCancel;
        private System.Windows.Forms.TextBox textBoxMessage;
        private System.Windows.Forms.Button buttonOk;
        private System.Windows.Forms.Button buttonDialogResult;
        private System.Windows.Forms.Button buttonEvent;
    }
}

Form.cs

using System;
using System.Windows.Forms;

namespace WindowsFormsApplication
{
    public partial class FormMain : Form
    {
        private bool _IsDialog = false;
        private int _InstanceCounter = 1;
        private string _Suffix = String.Empty;

        public FormMain()
        {
            InitializeComponent();
        }

        //Special constructor to see in Caption of the Form
        //that this is a child window
        public FormMain(string suffix)
            : this()
        {
            _Suffix = suffix;
            Text += " " + _Suffix;
        }

        //Reflects the content of the TextBox to the outer world
        public string Result
        {
            get
            {
                return textBoxMessage.Text;
            }
            set
            {
                textBoxMessage.AppendText(value + Environment.NewLine);
                //Fire an event if the content has changed
                ResultChanged.Raise(this);
            }
        }

        public event EventHandler ResultChanged;

        //Overwrite ShowDialog() to find out if where called by Show() or ShowDialog()
        public new DialogResult ShowDialog()
        {
            _IsDialog = true;
            return base.ShowDialog();
        }

        //Pass event of changed text of the TextBox to the outer world
        private void OnTextChanged(object sender, EventArgs e)
        {
            ResultChanged.Raise(this);
        }

        private void OnButtonResultClick(object sender, EventArgs e)
        {
            //Create a new child form (including new suffix to see that this is a child)
            var childForm = new FormMain(_Suffix + "." + _InstanceCounter++.ToString());

            //Start modal and wait for the result
            if (DialogResult.OK == childForm.ShowDialog())
            {
                Result = childForm.Result;
            }
        }

        private void OnButtonEventClick(object sender, EventArgs e)
        {
            //Create a new child form (including new suffix to see that this is a child)
            var childForm = new FormMain(_Suffix + "." + _InstanceCounter++.ToString());

            //Listen to events of the child form
            childForm.ResultChanged += OnChildFormResultChanged;
            childForm.FormClosed += OnChildFormFormClosed;

            //Open the form concurrently
            childForm.Show();
        }

        private void OnButtonExitClick(object sender, EventArgs e)
        {
            //When we were not opened with ShowDialog() we have to do
            //the closing on ourself.
            if (!_IsDialog)
            {
                var button = sender as Button;

                if (button != null)
                {
                    DialogResult = button.DialogResult;
                    Close();
                }
            }
        }

        void OnChildFormResultChanged(object sender, EventArgs e)
        {
            //Write changes from child form into our TextBox
            var childForm = sender as FormMain;

            if (childForm != null)
            {
                Result = childForm.Result;
            }
        }

        void OnChildFormFormClosed(object sender, FormClosedEventArgs e)
        {
            //Disconnect events from child form
            var childForm = sender as FormMain;

            if (childForm != null)
            {
                childForm.ResultChanged -= OnChildFormResultChanged;
                childForm.FormClosed -= OnChildFormFormClosed;
            }
        }
    }

    public static class EventExtensions
    {
        //Simple extension class to wrap thread safe firing of events
        public static void Raise(this EventHandler handler, object sender)
        {
            var temp = handler;
            if (temp != null)
                temp(sender, EventArgs.Empty);
        }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜