简体   繁体   English

在选择的陈述中使用多个行

[英]Use more than one row in a select statment

I have a select satement in C# and i was wondering if it is possible to use diaplay email and username in two diffrent label. 我在C#中有一个选择,我想知道是否可以在两个不同的标签中使用diaplay电子邮件和用户名。

Below is the query: 下面是查询:

SqlDataReader reader;
string sendMessage = "SELECT Email, username FROM aspnet_Membership WHERE UserId = @UserId";
using (SqlConnection myConnection = new SqlConnection(connectionString))
{
    myConnection.Open();
    SqlCommand myCommand = new SqlCommand(sendMessage, myConnection);
    myCommand.Parameters.AddWithValue("@UserId", newUserId);
    ArrayList emailArray = new ArrayList();
    label1 = myCommand.ExecuteReader();
    label2 = myCommand.ExecuteReader();
}

Thank you 谢谢

Yes, of course, but you need to call just one time the ExecuteReader and then use the SqlDataReader returned to get the field values of the current record. 是的,当然可以,但是您只需要调用一次ExecuteReader,然后使用返回的SqlDataReader来获取当前记录的字段值。 (Of course the text returned by the reader should be assigned to the Text property of the label, not to the label itself) (当然,阅读器返回的文本应该分配给标签的Text属性,而不是标签本身)

string sendMessage = "SELECT Email, username FROM aspnet_Membership WHERE UserId = @UserId";
using (SqlConnection myConnection = new SqlConnection(connectionString))
using (SqlCommand myCommand = new SqlCommand(sendMessage, myConnection))
{
    myConnection.Open();
    myCommand.Parameters.AddWithValue("@UserId", newUserId);
    using(SqlDataReader reader = myCommand.ExecuteReader())
    {
         while(reader.Read())
         {
              label1.Text = reader.GetString(reader.GetOrdinal("EMail"));
              label2.Text = reader.GetString(reader.GetOrdinal("UserName"));
         } 
   }

} }

Also, do not forget to put the disposable objects like the command and the reader inside the appropriate using statement 同样,不要忘记将诸如命令和阅读器之类的一次性对象放在适当的using语句中

Just call ExecuteReader once, and call Read method.Then you can get the values using indexer: 只需调用一次ExecuteReader ,然后调用Read方法即可使用索引器获取值:

reader = myCommand.ExecuteReader();
reader.Read();
label1.Text = reader["Email"].ToString();
label2.Text = reader["username"].ToString();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM