Mahmoud Samy February 2016

Fill TextBlock within a Button with database records

lets say i have 10 rows in my database table. I want to create 10 Buttons and TextBlock inside Buttons filled with data rows. I already create the 10 Buttons and TextBlock inside it here is the code

for (int i = 0; i < 10; i++)
 {
        Button Btn = new Button();
            Style style = this.FindResource("MetroNewButton") as Style;
            Btn.Style = style;
            Btn.Width = 250;
            Btn.Height = 80;
            Btn.Name = "BtnCA" + i;
            Btn.FlowDirection = FlowDirection.LeftToRight;
            Btn.HorizontalAlignment = HorizontalAlignment.Left;
            Btn.VerticalAlignment = VerticalAlignment.Top;

             for (int j = 0; j < 10; j++)
               {
                        Grid GridContent = new Grid();
                GridContent.Width = 250;
                GridContent.Height = 80;

                TextBlock txtBlock = new TextBlock();
                txtBlock.Name = "txtBlock" + j;
                txtBlock.TextWrapping = TextWrapping.Wrap;
                txtBlock.FontSize = 14;
                txtBlock.FontWeight = FontWeights.Bold;
                //txtBlock1.FlowDirection = FlowDirection.RightToLeft;
                txtBlock.Padding = new Thickness(10, 20, 0, 0);
                txtBlock.VerticalAlignment = VerticalAlignment.Top;
                Grid.SetRow(txtBlock, 0);
                 GridContent.Children.Add(txtBlock);
                Btn.Content = GridContent;
               } 
  }

Okay and i have list carries data from database.I want to distribute data to text block, So how to put data in Text block ?

Answers


Василий Шапенко February 2016

I think, using ItemsControl with proper ItemTemplate would be better idea than creating all the controls in for loop. Just create a list of objects representing your data, bind it to ItemsCOntrol(ItemsSource={Binding your_path}), and set proper item template for grid. After that, put an ItemsControl inside a button. If i understood you right, that should solve your problem.


BKO February 2016

Instead of using this for loop, you can create buttons using XAML and MVVM binding.

<DataGrid ItemsSource="{Binding btnList}">
    <DataGrid.Columns>
      <DataGridTemplateColumn>
        <DataGridTemplateColumn.CellTemplate>
          <DataTemplate>
            <Button Content="{Binding  btn_NAME}"/>
          </DataTemplate>
        </DataGridTemplateColumn.CellTemplate>
      </DataGridTemplateColumn>
    </DataGrid.Columns>
  </DataGrid>

Then fetch content from db and fill it into btnList.

To get more idea about MVVM binding, please go through this and this.

Post Status

Asked in February 2016
Viewed 1,040 times
Voted 5
Answered 2 times

Search




Leave an answer