从其他形式的方法中获取值

时间:2010-03-04 10:37:04

标签: c#

我遇到了一个问题,我在一个方法中以不同的形式检索一个值到我的主窗体。

这是我的代码: (这是我想要检索值的主要形式。)

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;
}

这是我声明我想要在选择单选按钮时从添加按钮检索值的方法的表单:

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("unable 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";
        }
    }

我跟踪了该方法,并且我认为它在点击时不会从按钮获取值,因为从程序的开头已经执行了该方法。我只想在单击按钮时执行该方法,以便我可以从TADD按钮检索值,以便在我的主窗体中传递字符串值,即estimatecomp。

3 个答案:

答案 0 :(得分:1)

在主窗体上

创建一个公共字段。财产会更好。

在包含您要共享的值的变量的方法中设置此字段或属性。

现在来自参与父表单实例的子项,您应该可以访问包含所需值的字段。

答案 1 :(得分:0)

private void EstimationComp_Click(object sender, EventArgs e) 
{ 

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

//or

string s = new NameOfDifferentForm.panel();
}

答案 2 :(得分:0)

我不太了解你的问题。所以我只是编写了一个表单,调用一些孩子并处理这些孩子的答案。也许这个例子可以提供帮助。

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