简体   繁体   中英

How to retrieve multiple values of single column in session

Each user on my website has a reg_id . There are some emergency_contact_id 's associated with this reg_id .

For example:

EmerContact_id  Reg_id    
  91              1    
  92              1    
  93              1    
  94              1    
  95              1

Now I want to store these EmerContact_id 's into session like this:

Session["Emer1"]    
Session["Emer2"]    
Session["Emer3"]    
Session["Emer4"]    
Session["Emer5"]

How can I achieve this?

I am thinking of using:

while(reader.read()) { ... }

But I don't know how to use it.

You can store complete list or dataset in session, however its not recommended but you can do it.

When fetching you can cast it to the desired type.

Simple and easy

If I understood your question....

Please try this

string[] EmerContactList = new string[]{"Emer1","Emer2","Emer3"};
Session["values"] = EmerContactList ;

To access

string[] results= (string[])Session["values"];

You can use MySqlDataReader and iterate through your results using an index marker, like this.

using (MySqlConnection dbConnection = new MySqlConnection("connectionstring"))
{
    dbConnection.Open();

    using (MySqlCommand dbCommand = new MySqlCommand("select EmerContact_id from [Table] order by EmerContact_id asc;", dbConnection))
    {
        using (MySqlDataReader dbReader = dbCommand.ExecuteReader())
        {
            int index = 1;

            while (dbReader.Read())
            {
                Session["Emer" + index.ToString()] = dbReader[0].ToString();

                index++;
            }
        }
    }

    dbConnection.Close();
}

You could also use a collection object like List and serialize this into the session.

You could also use one session object to store the values...

List<int> EmerContacts = new List<int>();

using (MySqlConnection dbConnection = new MySqlConnection("connectionstring"))
{
    using (MySqlCommand dbCommand = new MySqlCommand("select EmerContact_id from [Table];", dbConnection))
    {
        using (MySqlDataReader dbReader = dbCommand.ExecuteReader())
        {

            while (dbReader.Read())
            {
                EmerContacts.Add((int)dbReader[0].ToString());

             }
        }
    }
}

Session["EmerContacts"] = EmerContacts;

When you need to use the list then, you can just convert the session back to List...

List<int> myList = (List<int>)Session["EmerContacts"];

I hand typed some of it, so it may not compile, but you should get the gist of it.

When you use this approach, you can then easily itterate over the collection. Using your approach makes this a bit more difficult.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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