Home > Back-end >  C# / WPF : how can I programatically create as many texblocks as needed to show data from a table
C# / WPF : how can I programatically create as many texblocks as needed to show data from a table

Time:12-14

I'm trying to fill a combobox with textblock containing values from a table.

I would like to create as many textblocks as there is rows in the set of datarows returned by the select.

Then add those textblock to the combobox.

Can someone tell how this can be done, please?

Here is my code:

// instead of doing this I'd rather create them as needed.
TextBlock tbx1 = new TextBlock();
TextBlock tbx2 = new TextBlock();
TextBlock tbx3 = new TextBlock();

// Get all category 1 
DataRow[] cutProblemsRow = gediDataSet.CutProblems.Select("CutProbCategId= "   1);
        
// If there is any records
if (cutProblemsRow.Length > 0)
{
    // create as many texblock as there are rows here
            
    // cycle between rows
    for (int i = 0; i < cutProblemsRow.Count(); i  )
    {
        // Assign value to textblock
        TextBlock.Text = cutProblemsRow[i]["Problem"].ToString(); 
    }                
}
        
// Add the texblock created to the ComboBox
cmbxProblem.Items.Add(tbx1);
cmbxProblem.Items.Add(tbx2);
cmbxProblem.Items.Add(tbx3);

CodePudding user response:

As Clemens and zaggler suggested the best way is this:

private void AddProblemCategtoCombobox(int categ)
{
    // efface la liste de problème
    cmbxProblem.ItemsSource = null;
        
    // récupère la liste de problem de la catégorie
    cmbxProblem.ItemsSource = gediDataSet.CutProblems.Select("CutProbCategId= "   categ).Select(dr => dr["Problem"].ToString()).ToList();            
}

CodePudding user response:

Here is my final solution:

        cmbxProblem.Items.Clear();
        // Get category 1 records
        DataRow[] cutProblemsRow = gediDataSet.CutProblems.Select("CutProbCategId= "   1);

        // If there is any records
        if (cutProblemsRow.Length > 0)
        {
            // create as many texblock as there are rows
            TextBlock[] Textblocks = new TextBlock[cutProblemsRow.Count()];
            //cycle between rows
           for (int i = 0; i < cutProblemsRow.Count(); i  )
            {
                Textblocks[i] = new TextBlock();
                Textblocks[i].Text = cutProblemsRow[i]["Problem"].ToString();
                // Add the texblock created to the ComboBox
                cmbxProblem.Items.Add(Textblocks[i]);
            }                
        }
  • Related