在MSSQL中写了这个查询:
SELECT Code, Description,LEAD(Code, 1) OVER (ORDER BY code) AS next_code FROM Liguanea_Lane WHERE code LIKE '%88%'
在我的C#代码中回写相同的查询,这次它接受来自组合框名称“search”的输入并在按钮单击上执行。如下所示:
private void button1_Click(object sender, EventArgs e)
{
try
{
string connectionString = "Data Source=JAVY26;Initial Catalog=Pharmacies;Integrated Security=True";
SqlConnection con = new SqlConnection(connectionString);
con.Open();
string query = "SELECT Code, Description,LEAD(Code, 1) OVER (ORDER BY code) AS next_code FROM Liguanea_Lane WHERE code LIKE '%" + search.Text+"%'; ";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
string scode = dr.GetString(dr.GetOrdinal("next_code"));
textBox2.Text = scode;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
我的问题是我不断得到:“数据是空的。无法在空值上调用此方法或属性。”我的代码中的查询错了吗?它在我的SQL Server中运行良好。
答案 0 :(得分:0)
我认为问题是因为:
public class Location
{
public int LocationId { get; set; }
public int NextLocationId { get; set; }
public int PreviousLocationId { get; set; }
[ForeignKey("PreviousLocationId")]
public Location PreviousLocation { get; set; }
[ForeignKey("NextLocationId")]
public Location NextLocation { get; set; }
}
这是一个没有用户干预的循环,假设查询返回3行:
while (dr.Read())
{
string scode = dr.GetString(dr.GetOrdinal("next_code"));
textBox2.Text = scode;
}
在循环的第一遍中,它将881分配给textbox2.Text; 在第二遍,它将882分配给textbox2.Text 在第三次传递时它出错,因为next_code为null。
答案 1 :(得分:0)
private void button1_Click(object sender, EventArgs e)
{
try
{
string connectionString = "Data Source=JAVY26;Initial Catalog=Pharmacies;Integrated Security=True";
SqlConnection con = new SqlConnection(connectionString);
con.Open();
string query = "SELECT Code, Description, Next_Code FROM Liguanea_Lane WHERE code LIKE '%" + search.Text+"%'; ";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
string scode = dr.GetString(dr.GetOrdinal("next_code"));
textBox2.Text = scode;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
现在返回我需要的值。感谢大家的反馈。感谢您尝试和协助的时间。