C# 在C中从另一个windows窗体问题调用#
我在Form1上有一个按钮,上面有这个代码C# 在C中从另一个windows窗体问题调用#,c#,winforms,datareader,C#,Winforms,Datareader,我在Form1上有一个按钮,上面有这个代码 // hide main form this.Hide(); // show other form Form2 form2 = new Form2(); form2.ShowDialog(); // close application this.Close(); 现在在Form2 load上,我有一段代码,它并没有显示结果,尽管读卡器有值
// hide main form
this.Hide();
// show other form
Form2 form2 = new Form2();
form2.ShowDialog();
// close application
this.Close();
现在在Form2 load上,我有一段代码,它并没有显示结果,尽管读卡器有值。
它显示了带有空文本字段的Form2
using (SqlConnection connection = new SqlConnection(connectionString))
{
string queryString = "SELECT * FROM test;";
SqlCommand command =
new SqlCommand(queryString, connection);
connection.Open();
SqlDataReader reader1 = command.ExecuteReader();
// Call Read before accessing data.
while (reader1.Read())
{
t1.Text = reader1.GetString(0);
t2.Text = reader1.GetString(1);
}
// Call Close when done reading.
reader1.Close();
}
避免这种情况:
t1.Text = reader1.GetString(0);
t2.Text = reader1.GetString(1);
不要提及类型,因为使用此查询时
select * from test ;
然后更改列的类型,将得到不好的结果
因此,您可以尝试以下方法:
t1.Text = reader1[0].ToString();
t2.Text = reader1[1].ToString();
您是否添加了一个断点来查看您得到了什么?您在哪里执行此代码?是的,它在reader中有值,但没有分配给textfields…当它到达那里时,它会再次执行Form1的按钮,而循环说读取直到最后一行获取的记录。在reader.reader1.GetString(0)的最后一次遍历中,索引0和1可能为空;表中的值是int,这有问题吗?