为什么只有else条件运行? Postalcode列为float
,City列为nvarchar
。我认为失败的是字符串可能是错误的。
private void txt_st_postalcode_Leave(object sender, EventArgs e)
{
using (var connection = new SqlConnection("Data Source=mypublicip\\SQLEXPRESS2017;Initial Catalog=studentreg; User = myusername; Password=mypassword;"))
{
connection.Open();
using (var command = new SqlCommand("SELECT City FROM Cities WHERE Postcode=@Postcode", connection))
{
command.Parameters.AddWithValue("@Postcode", "10101");
using (var reader = command.ExecuteReader())
{
string txt_st_postalcode = reader.Read() ?
reader[1] as string : ("City");
if (reader.Read())
{
txt_st_city.Text = reader.GetString(reader.GetOrdinal("City"));
}
else
{
MessageBox.Show("Sh*t!");
}
}
}
}
}
答案 0 :(得分:0)
不太确定这些邮政编码是如何工作的(英国不同),但鉴于您使用ExecuteReader
,您似乎期待多个结果。正如评论所指出的那样,您目前正在阅读两次结果;但是,你应该有某种形式的循环;例如:
using (var command = new SqlCommand("SELECT City FROM Cities WHERE Postcode=@Postcode", connection))
{
command.Parameters.AddWithValue("@Postcode", "10101");
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
string txt_st_postalcode = reader[0] as string;
//txt_st_city.Text = reader.GetString(reader.GetOrdinal("City"));
// Depends what you're doing here?
}
}
}
如果您只期望单个结果,请尝试使用ExecuteScalar()
,这将返回单个结果;例如:
using (var command = new SqlCommand("SELECT City FROM Cities WHERE Postcode=@Postcode", connection))
{
command.Parameters.AddWithValue("@Postcode", "10101");
txt_st_city.Text = command.ExecuteScalar();
}
答案 1 :(得分:0)
首先,如果您需要从阅读器阅读PostCode,您必须先选择。因此,请更改您的查询。
using (var command = new SqlCommand("SELECT City, PostCode FROM Cities WHERE Postcode=@Postcode", connection))
其次,在获取数据之前每行调用一次read
。
if (reader.Read())
{
txt_st_postalcode .Text = reader.GetString(reader.GetOrdinal("PostCode"));
txt_st_city.Text = reader.GetString(reader.GetOrdinal("City"));
}
else
{
MessageBox.Show("Sh*t!");
}