我試圖將另一個表單中的文本框的值寫入到.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