表格1:
public partial class FrmMain : Form
{
OleDbCommand cmd = new OleDbCommand();
OleDbConnection cn = new OleDbConnection();
public FrmMain()
{
InitializeComponent();
}
public string Use = String.Empty;
private void btnLogin_Click_1(object sender, EventArgs e)
{
Use = txtUsername.Text;
}
}
表格2:
private void button1_Click(object sender, EventArgs e)
{
string theDate1 = dateTimePicker1.Value.ToString("yyyy-MM-dd");
string theDate2 = dateTimePicker2.Value.ToString("yyyy-MM-dd");
dateTimePicker1.MaxDate = dateTimePicker2.Value;
FrmMain Form = new FrmMain();
string username = Form.Use;
if (cboFrom.Text != "" && cboTo.Text != "" && Adults.Text != "" && Children.Text != "" && dateTimePicker2.Value > dateTimePicker1.Value)
{
string q = "insert into Booking([Departure], [Return], [From], [To],[Adults],[Children],[Username]) values ('"
+ theDate1.ToString() + "', '" + theDate2.ToString() + "','" + cboFrom.Text + "','"
+ cboTo.Text + "','" + Children.Text + "','" + Adults.Text + "', '" + username + "')";
dosomething(q);
MessageBox.Show("Success");
}
}
我正在尝试制作一个可以将数据记录到数据库的程序。我需要将我在文本框中输入的用户名变为另一种形式,但用户名不会记录到ms访问数据库中。
答案 0 :(得分:2)
这是因为您在此行中创建了FrmMain
的新实例:
FrmMain Form = new FrmMain();
另一种方法是在调用Form2
时传递字符串。像
Form2 f2 = new Form2();
f2.Username = txtUsername.Text;
f2.ShowDialog();
或者另一种方法是将字符串Use
设为静态,并在不创建新实例的情况下从Form2
调用它:
// FrmMain
public static string Use { get; set; }
// Form2
string username = FrmMain.Use;