2015-07-28 39 views
0

我使用C#语言和Visual Studio 2013年我想在我的网站上显示多行,但是它只是显示的第一个结果我怎样才能显示mutlitple排在Visiual工作室2013网站项目

我米试图

String show = "Select Posts from userPosts where Username='John'"; 
SqlCommand com = new SqlCommand(show, con); 
String str = com.ExecuteScalar().ToString(); 
Response.Write(str); 

这仅显示与用户名JOHN的第一个结果,但我希望他们所有。

回答

0

您正在使用ExecuteScalar [执行查询,并返回查询返回的结果集中第一行的第一列。其他列或行将被忽略。 ]

尝试ExecuteReader

String show = "Select Posts from userPosts where Username='John'; 
using (SqlCommand command = new SqlCommand(show, connection)) 
    { 
    using (SqlDataReader reader = command.ExecuteReader()) 
    { 
     while (reader.Read()) 
     { 
     for (int i = 0; i < reader.FieldCount; i++) 
     { 
      Console.WriteLine(reader.GetValue(i)); 
     } 
     Console.WriteLine(); 
     } 
    } 
    } 

BTW你可以尝试轻ORM喜欢小巧玲珑https://github.com/StackExchange/dapper-dot-net。它真的很好地删除这些可怕的while循环

1

这是因为使用了ExecuteScalar()尝试像这样(的结果显示在DataGridView):

String show = "Select Posts from userPosts where Username='John'"; 
SqlConnection con = new SqlConnection(connStr); 
SqlDataAdapter da = new SqlDataAdapter(show,con); 
DataSet ds = new DataSet(); 
da.Fill(ds,"tbl"); 
dataGridView1.DataSource = ds.Tables[0]; 

如果你不想在DataGridView显示,只是存储在变量中使用List<string>这样的:

List<string> Posts = new List<string>(); 
foreach (DataRow item in ds.Tables[0].Rows) 
{ 
    Posts.Add(item[0].ToString()); 
} 

您也可以使用SqlDataReader作为另一种选择。