以下是行为的摘要:while循环迭代到记录集的末尾,检索值。然后将值显示在各自的位置。
问题是,我只想显示一组值。使用while显示的值与正在查询的表中的记录一样多。以下示例:
应显示的内容:
<div>
<div>Service One is Stopped</div>
<div>Service Two is Running</div>
<div>Service Three is Stopped</div>
</div>
实际发生的事情:
<div>
<div>Service One is </div>
<div>Service Two is Running</div>
<div>Service Three is </div>
<div>Service One is </div>
<div>Service Two is </div>
<div>Service Three is Running</div>
<div>Service One is Stopped</div>
<div>Service Two is </div>
<div>Service Three is </div>
</div>
以下是有问题的代码。如果这是一个微不足道的问题,我道歉。我正在摆脱2年多的生锈而不是编写代码,有时甚至简单的事情都会让你:-)。非常感谢您的帮助!!!
@using System.Configuration;
@using System.Data.SqlClient;
@using System.Data;
@using System.Linq;
@{
System.Data.SqlClient.SqlConnection cn = null;
cn = new System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings["sqlConn"].ToString());
cn.Open();
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("SELECT DISTINCT * FROM servicehealth", cn);
var myreader = cmd.ExecuteReader();
}
@{
int rowCount = 0;
}
@while (myreader.Read())
{
rowCount++;
string service1status = "";
string service2status = "";
string service3status = "";
string servicename = @myreader["servicename"].ToString();
switch (servicename.ToLower())
{
case "serviceone":
service1status = @myreader["servicestate"].ToString();
break;
case "servicetwo":
service2status = @myreader["servicestate"].ToString();
break;
case "service3":
service3status = @myreader["servicestate"].ToString();
break;
}
<div>
<div>Service One is @service1status</div>
<div>Service Two is @service2status</div>
<div>Service Three is @service3status</div>
</div>
}
编辑:这是相关表格的缩略图:
ServiceId | ServiceName | ServiceState | StartTrackTime | LastUpdated
1111-11111-111111-11111111 | ServiceOne | Stopped | 1/30/2012 0:00 | 1/30/2012 17:57
2222-22222-222222-22222222 | ServiceTwo | Running | 1/30/2012 0:00 | 1/30/2012 17:57
3333-33333-333333-33333333 | ServiceThree | Running | 1/30/2012 0:00 | 1/30/2012 17:57
答案 0 :(得分:2)
看起来您可以在while的每次迭代中输出服务及其状态,并将其放在包含div标签之间。您应该为每个找到的服务获得一行。
<div>
@while (myreader.Read())
{
string servicestatus = servicestatus = @myreader["servicestate"].ToString();
string servicename = @myreader["servicename"].ToString();
<div>@servicename is @servicestatus</div>
}
</div>
答案 1 :(得分:0)
您需要在while循环之外移动字符串声明和div标记:
@{
int rowCount = 0;
string service1status = "";
string service2status = "";
string service3status = "";
while (myreader.Read())
{
rowCount++;
string servicename = @myreader["servicename"].ToString();
switch (servicename.ToLower())
{
case "serviceone":
service1status = @myreader["servicestate"].ToString();
break;
case "servicetwo":
service2status = @myreader["servicestate"].ToString();
break;
case "service3":
service3status = @myreader["servicestate"].ToString();
break;
}
}
}
<div>
<div>Service One is @service1status</div>
<div>Service Two is @service2status</div>
<div>Service Three is @service3status</div>
</div>