我试图将另一个表单中的文本框的值写入到.csv文件。目前我有一个引用本地数据库的“登录”表单,然后登录成功后,他们可以输入记录到.csv文件的数据。我想还包括“登录用户”,我能想到的最好方式就是抓住第一个表单上的文本框的值。有没有简单的方法来做到这一点?我曾尝试将textbox.Text写入另一个表单
string currentUser = Form2.textBox1.Text;
但这返回“Form2.textBox1是无法访问由于其保护级别”
谢谢!
我试图将另一个表单中的文本框的值写入到.csv文件。目前我有一个引用本地数据库的“登录”表单,然后登录成功后,他们可以输入记录到.csv文件的数据。我想还包括“登录用户”,我能想到的最好方式就是抓住第一个表单上的文本框的值。有没有简单的方法来做到这一点?我曾尝试将textbox.Text写入另一个表单
string currentUser = Form2.textBox1.Text;
但这返回“Form2.textBox1是无法访问由于其保护级别”
谢谢!
我能够结合你的答案来解决这个问题。我想我会在这里发布。感谢你的帮助!添加了评论以显示我最终添加的内容。
"LOGIN FORM"
Namespace Project1
public partial class AuthenicationForm : Form
{
public AuthenicationForm()
{
InitializeComponent();
}
//Added currentUser
public static string currentUser;
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(@"blahbalhbalhablh");
con.Open();
SqlCommand sqlcmd = new SqlCommand(blahblahblah);
SqlDataReader sqldr;
sqldr = sqlcmd.ExecuteReader();
int count = 0;
while (sqldr.Read())
{
count += 1;
}
if(count == 1)
{
//Grabbed textBox text on buttonclick after filled out
currentUser = textBox1.Text;
this.Hide();
Form1 ss = new Form1();
ss.Show();
}
"Recorder Form"
namespace Project1
{
public partial class RecordForm: Form
{
public string newFile = "Place to save" + DateTime.Now.ToString("MM-dd-yyyy") + ".csv";
public RecordForm()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var UPC = textBox1.Text;
var APCUPC = "00000";
if (UPC.Length == 9 && UPC.Contains(APCUPC))
{
//grabbed the currentUser from the previous form
File.AppendAllText(newFile, LoginForm.currentUser + "," + UPC + "," + DateTime.Now.ToString() + Environment.NewLine);
this.BackColor = System.Drawing.Color.Green;
this.label1.Text = "Scan successful, continue!";
textBox1.Text = "";
}
else
{
this.BackColor = System.Drawing.Color.Red;
this.label1.Text = "Scan unsuccessful, try again!";
}
}
我不是说这是做到这一点的正确方法,但您可以将TextBox
更改为公开。然后你将能够在另一个地方访问它。更清晰的方法是将公共财产添加到名为UserName
的表单中。我还建议将Form2
的名称更改为LogonForm
,将TextBox
的值从textBox1
更改为UserNameText
或者比textBox1
更有意义。
public string UserName
{
get
{
return textBox1.Text;
}
}
// Then you can use it like this (where Form2 is an instance of the logon form)
string currentUser = Form2.UserName;
请记住,您将需要登录窗体的实例。看看你的问题中的代码,它几乎看起来像你试图静态访问文本框的值。
您可以创建一个公共属性读/写Form 2上文本框内容:
public class Form2
{
public string User
{
get { return textBox1.Text; }
set { textBox1.Text = value; }
}
}
然后你就可以通过form2.User
有很多方法可以做到这一点访问textBox1的文本。我通常会创建一个全局类Session
,我将存储记录的用户信息(会话信息),并在需要时检索信息。
在登录:
//...
Session.LoggedUser = user; // Adapt it for your use case
//...
最后,在你窗体2:
string currentUser = Session.LoggedUser;
如果你想我个人的看法,我会在所有的时间避免私人控制的一种形式公开到另一个。但是,在某些情况下,我确实是这样做的。我会让你决定我提出的方法。 ;)
在form2设计中,将“Modifiers”属性更改为“internal”。 – Graffito