在Form1中按按钮,然后在Form2中检查单选按钮

时间:2019-04-04 12:25:43

标签: c# winforms

我有两个表格1和2。在 @SqlQuery("select last_value from testsequence") public long getLastSequence(); @SqlQuery("select nextval('testsequence')") public long getNextSequence(); @SqlQuery("select currval('testsequence')") public long getCurrentSequence(); 中,我有一个Form2;在Button中,我有一个Form1。当我按下RadioButton中的Button时,我希望Form2会在RadioButton中被选中。怎么做?我在winform中使用c#。

2 个答案:

答案 0 :(得分:0)

只是一个简单的例子:

    //FORM 1
    Form form1 = new Form();
    Button button1 = new Button();
    Button button2 = new Button();
    button2.Top = button1.Bottom;
    form1.Controls.AddRange(new Control[] { button1, button2 });

    //FORM 2
    Form form2 = new Form();
    RadioButton rb1 = new RadioButton();
    RadioButton rb2 = new RadioButton();
    rb2.Top = rb1.Bottom;
    form2.Controls.AddRange(new Control[] { rb1, rb2 });

    //CLICK EVENT
    button1.Click += (s, e) => { rb1.Invoke(new Action(() => { rb1.Checked = true; })); };
    button2.Click += (s, e) => { rb2.Invoke(new Action(() => { rb2.Checked = true; })); };

    //ONE THREAD FOR EACH FORM
    new Thread(new ThreadStart(() => { form1.ShowDialog(); })).Start();
    new Thread(new ThreadStart(() => { form2.ShowDialog(); })).Start();

询问是否有疑问。希望对您有所帮助。

答案 1 :(得分:0)

有多种方法可以做到这一点。这是3种可能的解决方案
我的选择是第二个解决方案

第一个解决方案:订阅Form2上按钮的点击事件

Form2 form = new Form2();
form.button1.Click += MyClick; //the modifier property of button1 must be public for this to work

void MyClick(object sender, EventArgs e)
{
   radioButton1.Checked = true;
}

第二个解决方案:Form1上的公共方法并传递Form1的引用

在form1中有此代码

public void SetRadioButtonChecked(bool value)
{
    radioButton1.Checked = value;
}

并像这样调用Form2

Form2 form = new Form2(this); // this works only if done in Form1 !

在form2中有此代码

private Form1 _caller = null;

public Form2(Form1 caller)
{
    InitializeComponent();
    _caller = caller;
}

void button1_Click(object sender, EventArgs e)
{
   _caller.SetRadioButtonChecked(true);
}

第三种解决方案:将句柄传递给表单并直接使用radioButton

Form2 form = new Form2(this); // this works only if done in Form1 !

在form2中有此代码

private Form1 _caller = null;

public Form2(Form1 caller)
{
    InitializeComponent();
    _caller = Caller;
}

void button1_Click(object sender, EventArgs e)
{
   _caller.radioButton1.Checked = true;
}