c#从关闭的表单传递值

时间:2011-12-13 16:08:06

标签: c# forms

我有一个OOP问题。我有3节课。程序(主类),登录表单和form1。 程序运行登录检查身份验证,如果成功,则在登录关闭时运行form1。 现在我遇到的问题是,如果我需要将变量值传递给我的form1怎么办? 原因是我希望使用用户名login作为变量,将其传递给我的form1,然后运行适当的代码来执行特定的事情。
基本上,管理员可以完全访问控件,但普通用户访问权限有限。

这是我的代码,不包括我的form1(除非有人希望看到它,否则不需要)。

namespace RepSalesNetAnalysis
{
public partial class LoginForm : Form
{
    public bool letsGO = false;
    public LoginForm()
    {
        InitializeComponent();
    }

    private static DataTable LookupUser(string Username)
    {
        const string connStr = "Server=server;" +
                            "Database=dbname;" +
                            "uid=user;" +
                            "pwd=*****;" +
                            "Connect Timeout=120;";


        const string query = "Select password From dbo.UserTable (NOLOCK) Where UserName = @UserName";
        DataTable result = new DataTable();
        using (SqlConnection conn = new SqlConnection(connStr))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand(query, conn))
            {
                cmd.Parameters.Add("@UserName", SqlDbType.VarChar).Value = Username;
                using (SqlDataReader dr = cmd.ExecuteReader())
                {
                    result.Load(dr);
                }
            }
        }
        return result;
    }

    private void buttonLogin_Click(object sender, EventArgs e)
    {
        if (string.IsNullOrEmpty(textUser.Text))
        {
            //Focus box before showing a message
            textUser.Focus();
            MessageBox.Show("Enter your username", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
            //Focus again afterwards, sometimes people double click message boxes and select another control accidentally
            textUser.Focus();
            textPass.Clear();
            return;
        }
        else if (string.IsNullOrEmpty(textPass.Text))
        {
            textPass.Focus();
            MessageBox.Show("Enter your password", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
            textPass.Focus();
            return;

        }
        //OK they enter a user and pass, lets see if they can authenticate
        using (DataTable dt = LookupUser(textUser.Text))
        {
            if (dt.Rows.Count == 0)
            {
                textUser.Focus();
                MessageBox.Show("Invalid username.", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                textUser.Focus();
                textUser.Clear();
                textPass.Clear();
                return;
            }
            else
            {
                string dbPassword = Convert.ToString(dt.Rows[0]["Password"]);
                string appPassword = Convert.ToString(textPass.Text); //we store the password as encrypted in the DB

                Console.WriteLine(string.Compare(dbPassword, appPassword));

                if (string.Compare(dbPassword, appPassword) == 0)
                {
                    DialogResult = DialogResult.OK;
                    this.Close();
                }
                else
                {
                    //You may want to use the same error message so they can't tell which field they got wrong
                    textPass.Focus();
                    MessageBox.Show("Invalid Password", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    textPass.Focus();
                    textPass.Clear();
                    return;
                }
            }
        }
    }

    private void emailSteve_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
    {
        System.Diagnostics.Process.Start("mailto:stevesmith@shaftec.co.uk");
    }
}

和继承我的主要课程

namespace RepSalesNetAnalysis
{
static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        //Application.Run(new LoginForm());

        LoginForm fLogin = new LoginForm();
        if (fLogin.ShowDialog() == DialogResult.OK)
        {
            Application.Run(new Form1());
        }
        else
        {
            Application.Exit();
        }
    }
}
}

总而言之,我需要将一个值从我的登录类传递给我的form1类,这样我就可以在form1中使用一个条件来限制用户的交互。

4 个答案:

答案 0 :(得分:3)

您可以在属性中公开它并在构造函数中传递它,类似这样

 LoginForm fLogin = new LoginForm();
 if (fLogin.ShowDialog() == DialogResult.OK)
 {
    Application.Run(new Form1(fLogin.Username));
 }

我认为你需要为winforms Designer保留一个无参数构造函数,所以你可以尝试保留一个空的,或者先创建Form1,然后将Username值传递给它

答案 1 :(得分:3)

您需要在LoginForm中公开属性,并将其作为构造函数中的参数传递给Form1。以下是执行此操作的步骤:

1)将以下代码添加到LoginForm类中:

public string UserName
{
    get
    {
        return textUser.Text;
    }
}

2)然后,更改Form1的构造函数以接收用户名作为参数:

private _userName;
public class Form1(string userName)
{
    _userName = userName;
}

3)最后,您只需要使用所需参数构造Form1:

namespace RepSalesNetAnalysis
{
static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        //Application.Run(new LoginForm());

        LoginForm fLogin = new LoginForm();
        if (fLogin.ShowDialog() == DialogResult.OK)
        {
            Application.Run(new Form1(fLogin.UserName));
        }
        else
        {
            Application.Exit();
        }
    }
}

希望它有所帮助。

答案 2 :(得分:1)

您可以传递如下所需的值:

    LoginForm fLogin = new LoginForm();
    if (fLogin.ShowDialog() == DialogResult.OK)
    {
        Form1 frm = new Form1();
        frm.SomeValue = fLogin.txtUser.Text;
        Application.Run(frm);
    }
    else
    {
        Application.Exit();
    }

答案 3 :(得分:0)

创建一个从表单中收集数据的类:

  class LoginFormResult {
       public string UserName { get; set; }
       // ....
       public DialogResult Result { get; set; }
  }

现在在表单上创建一个方法(我通常使用静态)来执行表单

 public static void Execute(LoginFormData data) {
     using (var f = new LoginForm()) {
         f.txtUserName.Text = data.UserName ?? "";
         // ...
         data.Result = f.ShowDialog();
         if (data.Result == DialogResult.OK) {
           data.UserName = f.txtUserName.Text;
           // ....
         }
     }
 }

您可以调用表单,并处理来自Main的结果:

 public void Main() {
   // ...

   var loginData = new LoginData { UserName = "test" };
   LoginForm.Execute(loginData);
   if (loginData.Result == DialogResult.OK) {
      // ....
   }

   // ...
 }

这隐藏了调用方法的实现,并且尽可能早地处理表单。只要您需要,表格中的数据就可以使用。