Передача авторизованной пользовательской информации в другую форму c # mysql - PullRequest
0 голосов
/ 17 мая 2018

Например, я хочу отобразить информацию о вошедшем в систему пользователе из базы данных в другую форму, такую ​​как имя и фамилия. У меня нет проблем с администратором, потому что у него есть только одна форма или данные для нее.Я попытался передать текст в имени пользователя текстового поля в другую форму и затем выбрать пропущенный текст, чтобы отобразить другую информацию о нем, но это не так, вот мой код между прочим.

private void button2_Click(object sender, EventArgs e)
    {
        int i = 0;
        MySqlCommand comm = con.CreateCommand();
        comm.CommandText = "select * from accountinfo where username = @user and pass = @password";
        comm.Parameters.AddWithValue("@user", textBox1.Text);
        comm.Parameters.AddWithValue("@password", textBox2.Text);
        MySqlDataReader myReader;
        con.Open();
        comm.ExecuteNonQuery();
        myReader = comm.ExecuteReader();
        string accountType = string.Empty;
        DataTable dt = new DataTable();
        MySqlDataAdapter da = new MySqlDataAdapter(comm);
        i = Convert.ToInt32(dt.Rows.Count.ToString());

       while (myReader.Read())
       {
            i = i + 1;
            accountType = myReader["accountType"].ToString();
       }
       if (i == 0)
       {
            MessageBox.Show("Wrong username or password!");
       }
       else if (accountType == "admin")
       {
            MessageBox.Show("Welcome admin");
            this.Hide();
            textBox1.Text = string.Empty;
            textBox2.Text = string.Empty;
            Form3 frm3 = new Form3();
            frm3.Show();
       }
       else
       {
            MessageBox.Show("Welcome");
            this.Hide();
           using(var frm4 = new Form4())
           {

               frm4.FirstName = textBox1.Text;
               frm4.ShowDialog();
           }
       }
            con.Close();
    }

и мой код во второй форме

public partial class Form4 : Form
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string CellNo { get; set; }

    public Form4()
    {
        InitializeComponent();
    }

    private void Form4_Load(object sender, EventArgs e)
    {
        tbUser.Text = FirstName;
        try
        {
            string MyConnection2 = "server=localhost;user id=root;database=account;persistsecurityinfo=True;PASSWORD=test123;SslMode=none";
            string Query = "SELECT firstname = '" + tbFN.Text + "' from accountinfo WHERE username = '" + tbUser + "' " ; 
            MySqlConnection MyConn2 = new MySqlConnection(MyConnection2);
            MySqlCommand MyCommand2 = new MySqlCommand(Query, MyConn2);
            MySqlDataAdapter MyAdapter = new MySqlDataAdapter();
            MyAdapter.SelectCommand = MyCommand2;
            DataTable dTable = new DataTable();
            MyAdapter.Fill(dTable);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        } 

    }
}

1 Ответ

0 голосов
/ 17 мая 2018

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

. В качестве решения создайте класс пользователя

public class User {
    username, full name ...
}

Create embiendКласс ApplicationContext

public class ApplicationContext
{
   private ApplicationContext(){
   }

   public User UserInfo {get;}

   public static ApplicationContext Current{get;}

   public static Init(User userInfo)
   {
       if(Current != null)
           throw new Exception("Context already initialized");

       Current = new ApplicationContext(){
           UserInfo = userInfo
       }
   }
}

После входа в систему звоните

ApplicationContext.Init(userInfo);

Везде, где вам нужна информация о пользователе, звоните

ApplicationContext.Current.UserInfo
...