как закрыть this.form - PullRequest
       2

как закрыть this.form

1 голос
/ 13 декабря 2011

У меня есть 3 класса: Form1, LoginForm и program.

Программа содержит мой основной метод, который затем запускает loginform, если выполняется условие внутри формы входа в систему, то запускается form1.

ЧтоЯ хочу сделать это, чтобы скрыть форму входа непосредственно перед отображением формы 1.

Как мне это сделать, поскольку я не могу использовать loginform.hide ();

Вот код:

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

    private static DataTable LookupUser(string Username)
    {
        const string connStr = "Server=10asaf;" +
                            "Database=dfafa;" +
                            "uid=bufaf;" +
                            "pwd=dridfsdf;" +
                            "Connect Timdf0;";

        //"Data Source=apex2006sql;Initial Catalog=Leather;Integrated Security=True;";

        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();
            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();
                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
                //MessageBox.Show
                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();
                    return;
                }
            }
        }

    }
}

}

Я что-то упустил?вот мой основной класс;

namespace RepSalesNetAnalysis
{
static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        LoginForm fLogin = new LoginForm();
        if (fLogin.ShowDialog() == DialogResult.OK)
        {
            Application.Run(new Form1());
        }
        else
        {
            Application.Exit();
        }
    }
}
}

Ответы [ 3 ]

4 голосов
/ 13 декабря 2011

Стивен, это все неправильно.

есть и другие способы сделать то, что вам нужно, правильно используя метод Main вашего класса Program, создающий форму входа, и только если вход успешен, высоздать и показать основную форму заявки.

проверить этот вопрос / ответ для получения подробной информации и примеров: Как закрыть форму входа и показать основную форму без закрытия приложения?

На самом деле вам нужен такой подход:

static void Main()
{
    LoginForm fLogin = new LoginForm();
    if (fLogin.ShowDialog() == DialogResult.OK)
    {
        Application.Run(new MainForm());
    }
    else
    {
        Application.Exit();
    }
}
0 голосов
/ 13 декабря 2011

Вы можете установить DialogResult на OK или Cancel в вашей форме входа в систему. Это закроет вашу LoginForm и вернет DialogResult обратно в ваш метод Main. Затем проверьте результат в методе Main следующим образом.

[STAThread]
static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);

    LoginForm form = new LoginForm();
    if (form.ShowDialog() == DialogResult.OK)
        Application.Run(new Form1());
}

надеюсь, это поможет

0 голосов
/ 13 декабря 2011
static class Program
{
    private static bool canLogin;

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        using (LoginForm loginForm = new LoginForm()){
           // show as dialog
           // perform logic to check if successful
           canLogin = SomeStaticClass.VerifyCredentials(loginForm.Credentials);
           // grab any properties you may want here
        }
        //then run the application
        if(canLogin){
           Application.Run(new Form1());
        }
    }
}
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...