我正在显示我从数据库中获取的属性列表。我习惯于在经典 ASP 中工作,只需创建与数据库的连接,然后循环遍历结果并像这样显示它们。
我的问题是,我应该在 .NET 中做同样的事情还是应该将数据绑定到元素?我更喜欢循环遍历结果,因为我想在带有样式的 div 中显示结果。
这是我的代码:
SqlConnection conn = new SqlConnection(
"Data Source=xxxx;Initial Catalog=Rets_Full_local;Integrated Security=True");
SqlDataReader rdr = null;
try
{
conn.Open();
// 3. Pass the connection to a command object
SqlCommand cmd = new SqlCommand(
"select * from RETS_Listings_full" +
" WHERE 1 =1 " + sqlWhere
, conn);
rdr = cmd.ExecuteReader();
String resultsDiv = "";
while (rdr.Read())
{
String rdr_MLSNUM = (rdr["MLSNUM"]).ToString();
String rdr_SYSID = (rdr["SYSID"]).ToString();
String rdr_LISTPRICE = (rdr["LISTPRICE"]).ToString();
String rdr_PropType = (rdr["PROPTYPE"]).ToString();
String rdr_Beds = (rdr["beds"].ToString());
String rdr_BathsFull = (rdr["BATHSFULL"].ToString());
String rdr_BathsHalf = (rdr["BATHSHALF"].ToString());
String rdr_AREA = (rdr["AREA"]).ToString();
String rdr_STREETNUM = (rdr["STREETNUM"]).ToString();
String rdr_STREETNAME = (rdr["STREETNAME"]).ToString();
String rdr_City = (rdr["CITY"]).ToString();
String rdr_View = (rdr["VIEWDESC"]).ToString();
resultsDiv += "<div class='row-fluid'>";
resultsDiv += "<div class='span4'>";
resultsDiv += " <img src='http://www.hiltonheadrealestates.com/listings/Photo" + rdr_SYSID + "-1.jpeg' width='250px'>";
resultsDiv += "</div>";
resultsDiv += " <div class='span8' >";
resultsDiv += "List Price: $" + rdr_LISTPRICE +"<br />";
resultsDiv += "Property Type: " + rdr_PropType +"<br />";
resultsDiv += "Address : " + rdr_STREETNUM + " " + rdr_STREETNAME + "<br />";
resultsDiv += "Location : " + rdr_City + "<br />";
resultsDiv += "Area : " + rdr_AREA + "<br />";
resultsDiv += "Bedrooms: " + rdr_Beds + "<br />";
resultsDiv += "Full Baths: " +rdr_BathsFull+ "<br />";
resultsDiv += "Half Baths: " +rdr_BathsHalf+"<br />";
resultsDiv += "View: " + rdr_View + "<br />";
resultsDiv += " </div>";
resultsDiv += " </div> <hr>";
}
// print results to div
if (rdr == null || !rdr.HasRows)
{
div_Results.Text = "No Results - Please click <a href='/'>here</a> to search again";
}
else
{
div_Results.Text = resultsDiv;
}
// End print results to div
}
finally
{
// close the reader
if (rdr != null)
{
rdr.Close();
}
// 5. Close the connection
if (conn != null)
{
conn.Close();
}
}
}