dpaul1994
dpaul1994

Reputation: 320

Insert in list values from database

I have a function that selects from database some column values. I would like those selected values to be inserted in a list with maximum 26 items. How can I do that? One "row" from list contains the question with answer1,answer2,answer2,option1,option2,option3. How can I do that? I don't really know how to work with lists.

private void select()
{
    if (index.connect.State == ConnectionState.Open) {
        index.connect.Close(); 
    }

    MySqlCommand cmd = new MySqlCommand(dataA, index.connect);
    cmd.CommandType = CommandType.Text;
    using (index.connect)
    {
        index.connect.Open();
        MySqlDataReader rdr = cmd.ExecuteReader();
        try
        {
            if (rdr.Read())
            {
                label2.Text = rdr["question"].ToString();
                label3.Text = rdr["answer1"].ToString();
                label4.Text = rdr["answer2"].ToString();
                label5.Text = rdr["answer3"].ToString();
                r1 = (int)rdr["option1"];
                r2 = (int)rdr["option2"];
                r3 = (int)rdr["option3"];
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            index.connect.Close();
        }
    }
}

Upvotes: 1

Views: 150

Answers (1)

A. Abramov
A. Abramov

Reputation: 1865

There are a couple ways to implenet what you ask for.

In the SQL level, there's a simple solution - you can select a certain amount of items, I.E 26, by using the keyword "Top".

for example,

SELECT TOP 26 Grade FROM StudentsTable;

In the Application level, you can programmatically select the 26 items you want; For example, if you're getting them from an ASP application in textboxes and the database interaction is activated from a button_Click event, you can Select them in the function itself ; To illustrate, let's say you want to select the maximum 26 values out of 50 labels named Label, you'll have in the button.Click:

List<int> MyLabels = FindMaxValues(<Your array of labels>, 26)
//Database stuff with MyLabels

And the function itself:

private static List<int> FindMaxValues(Labels[] myLbls, int AmountOutOfMax)
{
int LabelValue=0
for(int i=0;i<AmountOutOfMax;i++)
 {
  for(int k=0;k<50;k++)
  {
  LabelValue=int.Parse(myLbls[k])
   // find max, etc.
   }
 }
}

My point is - There are many solutions, this question is somewhat vague - You should find what is right for you depending on your application, and go for it;

Good luck :)

Upvotes: 1

Related Questions