簡體   English   中英

通過表單C#Visual Studio 2010保持選中的單選按鈕

[英]Keep checked radio button checked through forms C# Visual Studio 2010

我有一個帶有10個單選按鈕的窗體(Form2),供用戶檢查(均在同一組中)。 然后一個按鈕轉到下一個窗體(Form3)。

在Form3上,如果需要,我有一個后退按鈕可以返回Form2來更改單選按鈕。

當按下后退按鈕時,它將帶有所有單選按鈕進入Form2,但不會顯示先前選中的單選按鈕。

示例代碼:

string SchoolName = "";

if (radioButton1.Checked)
{
    SchoolName = radioButton1.Text;
}

if (radioButton2.Checked)
{
    SchoolName = radioButton2.Text;
}

然后使用“后退”按鈕返回上一個表單:

private void button3_Click(object sender, EventArgs e)
{         
    this.Close();

    th = new Thread(opennewform);
    th.SetApartmentState(ApartmentState.STA);
    th.Start();
}

private void opennewform(object obj)
{
    Application.Run(new Form2());
}

重新創建像new Form2()這樣的表單將添加具有默認值的初始化表單,這將導致您所做的更改不完整。

解決您可以:

  • 使用顯示/隱藏而不是關閉/新建
  • 保存對象狀態,例如,在重新打開form2時,您可以調用類似的構造函數


    new form2(check1State,check2State,selectedDropItem,txtName...);

在您的opennewform()方法中,您將實例化一個Form2副本,而不是返回到原來的副本。 這就是為什么未保存原始單選按鈕選擇的原因。 您需要以某種方式返回到原始Form2實例,而不是創建新實例。

例如,您可以在用戶關閉Form2時隱藏它,並在用戶再次需要它時重新顯示它。

您不會返回到表單的同一實例,而是要創建一個新表單。 請參閱下面的兩個表單項目

表格1

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 WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        Form2 form2;
        public Form1()
        {
            InitializeComponent();
            form2 = new Form2(this);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            form2.Show();
            string  results = form2.GetData();
        }
    }
}

表格2

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 WindowsFormsApplication1
{
    public partial class Form2 : Form
    {
        Form1 form1;
        public Form2(Form1 nform1)
        {
            InitializeComponent();

            this.FormClosing +=  new FormClosingEventHandler(Form2_FormClosing);
            form1 = nform1;
            form1.Hide();
        }
        private void Form2_FormClosing(object sender, FormClosingEventArgs e)
        {
            //stops form from closing
            e.Cancel = true;
            this.Hide();
        }
        public string GetData()
        {
            return "The quick brown fox jumped over the lazy dog";
        }

    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM