0

I want to Know How to create a button in code behind which contains Stackpanel as container and textblock inside stackpanel as child,when i was tried to create the button it throws Null Exception in Stackpanel.Kindly help me to solve this problem.

What I've tried is:

foreach (var pd in Query)
{
    Button b = new Button();
    b.HorizontalContentAlignment = HorizontalAlignment.Stretch;
    b.HorizontalAlignment = HorizontalAlignment.Left;
    b.VerticalAlignment = VerticalAlignment.Top;
    b.Height = 196;
    b.Width = 172;
    b.Margin = new Thickness(d, 0, 0, 0);
    b.Style = this.Resources["ButtonStyle1"] as Style;

    Grid st = new Grid();

    st.HorizontalAlignment = HorizontalAlignment.Stretch;
    st.Width = 160;
    st.Height = 188;

    TextBlock tb = new TextBlock();
    tb.TextWrapping = TextWrapping.Wrap;
    tb.VerticalAlignment = VerticalAlignment.Top;
    tb.HorizontalAlignment = HorizontalAlignment.Stretch;
    tb.FontSize = 14;
    tb.Margin = new Thickness(10, 0, 0, 0);
    tb.RenderTransformOrigin = new Point(0.5, 0.5);
    tb.FontSize = 14;
    tb.FontWeight = FontWeights.Bold;
    tb.Height = 35;

    TextBlock tb1 = new TextBlock();
    tb1.Height = 109;
    tb1.VerticalAlignment = VerticalAlignment.Bottom;
    tb1.HorizontalAlignment = HorizontalAlignment.Stretch;
    tb1.FontSize = 12;
    tb1.TextWrapping = TextWrapping.Wrap;

    b.Content = pd.ProductName;

    b.FontSize = 14;
    b.Background = new SolidColorBrush(Colors.Red);

    ContentPanel.Children.Add(b);

    b.Click += new RoutedEventHandler(b_Click);

    st.Children.Add(tb);
    st.Children.Add(tb1);

    st = b.Content as Grid;

    d += 140;
}
4
  • Can you show us your code? Commented Mar 30, 2013 at 8:55
  • For Reference See My Code in this link link Commented Mar 30, 2013 at 9:44
  • 1
    I've added the code to your answer. Which line is throwing the exception? Anyway, in your code you're not actually using the value of st. I believe what you wanted to do at the end is b.Content = st; rather than st = b.Content as Grid; Commented Mar 30, 2013 at 9:59
  • Thanks a Lot It works. Previously the line b.content as grid throws Null Exception,and now that is resolved Commented Mar 30, 2013 at 12:00

1 Answer 1

1

In your code you're not actually using the value of st. I believe what you wanted to do at the end is b.Content = st; rather than st = b.Content as Grid

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.