我有标签:
<asp:Label ID="lbl1" runat="server"></asp:Label>
代码背后:
protected void Page_Load(object sender, EventArgs e)
{
lbl1.Text = ImageCheck().ToString();
}
和
protected int ImageCheck()
{
SqlConnection connection = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\***.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
string CommandText2 = "SELECT * FROM Machreta WHERE noImage = 1";
SqlCommand command2 = new SqlCommand(CommandText2, connection);
connection.Open();
int check = (int)command2.ExecuteScalar();
connection.Close();
return check;
}
我如何返回多个值?该标签仅显示单个值,但表中还有6个。
答案 0 :(得分:3)
试试这个:
protected string ImageCheck()
{
var result = new StringBuilder();
using(var connection = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\***.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"))
{
string CommandText2 = "SELECT * FROM Machreta WHERE noImage = 1";
SqlCommand command2 = new SqlCommand(CommandText2, connection);
connection.Open();
using(var reader = command2.ExecuteReader())
{
while (reader.Read())
{
result.Append(reader.GetString(0));
}
}
return result.ToString();
}
}
当然只是 一个例子并没有完全解决你的问题,但应该是一个起点:)
答案 1 :(得分:2)
以下是ExecuteScalar()方法的说明。 http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar%28v=vs.71%29.aspx
“执行查询,并返回查询返回的结果集中第一行的第一列。忽略额外的列或行。”
此外,SELECT *将获取所有列。您可能希望为单列显示多个值。然后在select语句中选择列名。
SELECT xyzColumn FROM Machreta WHERE noImage = 1
最后,您只能为label.text分配一个字符串。因此,您必须连接所有这些字符串(单列的多个值),然后将其分配给标签文本。使用reader和ExecuteReader()方法代替ExuecuteScalar()。