例如,我想将登录用户的信息从数据库显示为另一种形式,例如名字和姓氏,我在管理中没有遇到问题,因为它只有一种形式或详细信息。我尝试将文本框用户名中的文本传递到另一个表单,然后选择传递的文本来显示它的其他信息,但它不会,这是我的代码顺便说一句。
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);
}
}
}
最佳答案
登录的用户信息对于您的所有应用程序来说都是静态的,因此您应该能够从任何地方访问它
作为解决方案创建类用户
public class User {
username, full name ...
}
创建嵌入类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
关于c# - 将登录的用户信息传递到另一个表单c# mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50386720/