Show values of a List in Labels

0

I want to show the values that I get from a query, I keep them in a 'List' but it does not show me anything:

private void getValues2()
{
    List<string> list2 = new List<string>();
    cn.Open();
    SqlCommand cmd = new SqlCommand("SELECT  SUM(Qty) AS QTY FROM    tbl_Kanban GROUP BY Part_Num", cn);
    SqlDataReader leer;
    leer = cmd.ExecuteReader();
    while (leer.Read() == true)
    {      
        list2.Add(leer[0].ToString());
    }
    if (list2.Count > 0)
    {   

    }

    cn.Close();
}
    
asked by CarlosR93 14.06.2017 в 22:11
source

2 answers

1

It does not show you anything because you're simply storing the data in a variable list2 . To show the data you must include the data in a control within a form.

Look at this example:

    private void getValues2()
    {
        List<string> list2 = new List<string>();
        cn.Open();
        SqlCommand cmd = new SqlCommand("SELECT  SUM(Qty) AS QTY FROM    tbl_Kanban GROUP BY Part_Num", cn);
        SqlDataReader leer;
        leer = cmd.ExecuteReader();
        while (leer.Read() == true)
        {
            list2.Add(leer[0].ToString());
        }
        if (list2.Count > 0)
        {
            ShowData(list2);
        }
        cn.Close();
    }

    private void ShowData(List<string> data)
    {
        var form = new Form();
        var listbox = new ListBox();
        form.Controls.Add(listbox);
        listbox.Items.AddRange(data.ToArray());
        form.Show();
    }

The ShowData method receives a list of strings, creates a form, adds a ListBox control to the form, and includes the list data in the ListBox. Finally show the form.

    
answered by 14.06.2017 в 22:31
0

The correct thing would be for the function to return the list as an answer:

private List<string> getValues2()
{
    cn.Open();
    SqlCommand cmd = new SqlCommand("SELECT  SUM(Qty) AS QTY FROM tbl_Kanban GROUP BY Part_Num", cn);
    SqlDataReader leer = cmd.ExecuteReader();

    List<string> lista = new List<string>();
    while(leer.Read())
    {
        lista.Add(leer[0].ToString());
    }

    cn.Close();

    return lista;
}

Then later in the form you would use:

List<string> lista = getValues2();

foreach(var item in lista)
{
    ListBox1.Items.Add(item);
}

I do not know if getValues2() define it within a class or in the same form , but the idea is to separate responsibilities, on the one hand you get the data and on the other you assign these to ListBox .

If that function is in a class you should create the instance to invoke its functionality.

    
answered by 14.06.2017 в 23:22