我决定在SQL中保存所有设置。 如果我想读取前。来自SQL DB的comport,而不是我收到错误: “c#名称”comportnumber“在当前上下文中不存在” 我应该改变什么来解决它?
SqlCeConnection conn = new SqlCeConnection("Data Source = \\Program Files\\myprogram\\db.sdf; Password ='mypassword'");
conn.Open();
SqlCeCommand cmd = new SqlCeCommand("SELECT * FROM [COMPORT]", conn);
SqlCeDataReader rdr = cmd.ExecuteReader();
cmd.Connection = conn;
cmd.ExecuteNonQuery();
while (rdr.Read())
{
string comportnumber = rdr.GetString(0);
}
serialPort1.PortName = comportnumber;
conn.Close();
serialPort1.Close();
if (!serialPort1.IsOpen)
serialPort1.Open();
答案 0 :(得分:2)
您的问题的问题是您的comportnumber变量的范围仅限于while循环中相对较小的括号部分。只需移动声明即可。但是你也有其他问题 - 请注意我是如何重组代码的。
string comportnumber = "";
using (SqlCeConnection conn = new SqlCeConnection("Data Source = \\Program Files\\myprogram\\db.sdf; Password ='mypassword'"))
using (SqlCeCommand cmd = new SqlCeCommand("SELECT * FROM [COMPORT]", conn))
{
conn.Open();
using (SqlCeDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
comportnumber = rdr.GetString(0);
}
}
}
serialPort1.PortName = comportnumber;
serialPort1.Close();
if (!serialPort1.IsOpen)
serialPort1.Open();
答案 1 :(得分:0)
如你所知,comportnumber只存在于while循环的范围内。尝试将其更改为:
string comportnumber = string.Empty;
while (rdr.Read())
{
comportnumber = rdr.GetString(0);
}
serialPort1.PortName = comportnumber;