c# - 试图从另一个表单中获取一个字符串,但我得到字符串值 null
问题描述
我的第一个表单上有comboBox1、comboBox2 和一个文本框。当我点击这个表单上的一个按钮时,我试图将一个文本值从这个项目发送到第二个表单,并在我的连接字符串中使用这个值。我将文本框和组合框的值保存在表单 2 的字符串中。到目前为止,我已经完成了此操作,但似乎第二种表单中的值为空:
//first form
private void button1_Click(object sender, EventArgs e)
{
Form1 f2 = new Form1();
f2.Text = comboBox2.Text;
Form1 f3 = new Form1();
f3.Text = comboBox1.Text;
Form1 f4 = new Form1();
f4.Text = textBox1.Text;
string selectedUser = this.comboBox1.GetItemText(this.comboBox1.SelectedItem);
if ((selectedUser == "admin") && (textBox1.Text == "password"))
{
Form1 form3 = new Form1();
form3.Show();
form3.Activate();
this.Hide();
}
}
//second form
public partial class Form1 : Form
{
private string text1;
public string Text1
{
get { return text1; }
set { Text1 = value; }
}
private string text2;
public string Text2
{
get { return text2; }
set { text2 = value; }
}
private string text3;
public string Text3
{
get { return text3; }
set { text3 = value; }
}
public Form1(Form1 frm1)
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string db = Text1;
string user = Text2;
string pass = Text3;
String strConnection = @"Data Source=SERVER;Initial Catalog ="+db+"; User ID ="+user+"; Password ="+pass+";";
SqlConnection con = new SqlConnection(strConnection);
try
{
con.Open();
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = con;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "Select table_name from information_schema.tables";
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd);
DataTable dtRecord = new DataTable();
sqlDataAdap.Fill(dtRecord);
dtRecord.DefaultView.Sort = "table_name ASC";
ComboBox1.DataSource = dtRecord;
ComboBox1.DisplayMember = "TABLE_NAME";
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
解决方案
您正在创建 的三个实例
Form1
,我认为这不是故意的。您正在设置
Text
新实例的属性,而不是您的自定义属性。
解决方案:将 body 替换为button1_Click
以下内容:
private void button1_Click(object sender, EventArgs e)
{
var nextForm = new Form1();
nextForm.Text1 = comboBox2.Text;
nextForm.Text2 = comboBox1.Text;
nextForm.Text3 = textBox1.Text;
string selectedUser = this.comboBox1.GetItemText(this.comboBox1.SelectedItem);
if ((selectedUser == "admin") && (textBox1.Text == "password"))
{
nextForm.Show();
nextForm.Activate();
this.Hide();
}
}
推荐阅读
- python - 将 JSON 坐标转换为 numpy 数组
- vue.js - 缺少 sass-loader、css-loader 依赖项 quasar/vue
- linux - 使用 awk 打印价格较低的第 1 列和第 4 列
- angular - 如何在 angular slickgrid 中立即渲染自定义角度组件
- datetime - Groovy:ISO 8601 格式的时间
- .net - MSAL。WPF 上的应用程序冻结
- python - 如何向 scattertext 添加词形还原和标记化
- spring-boot - Spring Boot:从 2.2.8 升级到 2.3.1
- python - 在 Python 3.x 中使用 snowflake-connector-python 的问题
- r - 从 CRAN 下载的包中记录的功能,但在加载包时不可用。来自 ACSNMineR 的函数 reverselog_trans