0

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);
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Nico D
  • 7
  • 4
  • 2
    Assign a collection of strings to the ItemsSource property of the ComboBox. You don't need to create any TextBlock at all. – Clemens Dec 10 '21 at 19:27
  • 1
    Maybe something like this: `cmbxProblem.ItemsSource = gediDataSet.CutProblems.Select("CutProbCategId= " + 1).Select(dr => dr["Problem"].ToString()).ToList();` – Trevor Dec 10 '21 at 19:38
  • Thank you for your suggestions. I found the solution while brainstorming with another programmer. – Nico D Dec 10 '21 at 20:03
  • How can I add CutProbCategId as the selected value instead of the text in the combobox? I would like to add key, value pair to the combobox. – Nico D Dec 16 '21 at 15:02

1 Answers1

0

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();            
}
Nico D
  • 7
  • 4