Search code examples
c#wpfcomboboxtextblockprogrammatically-created

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


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);

Solution

  • As Clemens and zaggler suggested the best way is this:

    private void AddProblemCategtoCombobox(int categ)
    {
        // clear list
        cmbxProblem.ItemsSource = null;
            
        // get list
        cmbxProblem.ItemsSource = gediDataSet.CutProblems.Select("CutProbCategId= " + categ).Select(dr => dr["Problem"].ToString()).ToList();            
    }