1

In my WPF application, I displayed some Checkbox dynamically. The Name and Content of these Checkbox come from a Table in the Database.

...
StackPanel innerStack = new StackPanel();
        List<Course> courses = ldc.Courses.ToList();
        var count = courses.Count();
        var b = ldc.Books.Single(x=>x.BookID==1);
        foreach (var c in courses)
        {
            CheckBox cb = new CheckBox();
            cb.Name = c.CourseID.ToString();
            cb.Content = c.CourseID.ToString();
            var x = from bc in ldc.CourseAndBooks
                    where bc.BookID == b.BookID
                    select bc.CourseID;
            if (x.Contains(c.CourseID))
            {
                cb.IsChecked = true;
            }

            cb.AddHandler(CheckBox.CheckedEvent, new RoutedEventHandler(course_Checked));
            cb.AddHandler(CheckBox.UncheckedEvent, new RoutedEventHandler(course_Unchecked));
            innerStack.Children.Add(cb);
        }
        Grid.SetColumn(innerStack,0);
        Grid.SetRow(innerStack,0);
        Grid.SetColumnSpan(innerStack,1);
        Grid.SetRowSpan(innerStack,1);
        grid.Children.Add(innerStack);
        ...

I added Checked and Unchecked event too to manipulate the checked item in the Database.

 private void course_Checked(object sender, RoutedEventArgs e)
    { 
        MessageBox.Show("checked"); // it works
        // How to identify cb.Name here to perform some database query?
    }
    private void course_Unchecked(object sender, RoutedEventArgs e)
    {
        MessageBox.Show("Unchecked"); // it works
        // How to identify cb.Name here to perform some database query?
    }

So, how can I get the name of the checked/unchecked Checkbox name in the Checked/Unchecked` event method. Any suggession ? Thankyou.

3
  • 1
    Can't you directly access it on the sender ? ((CheckBox)sender).Name Commented Dec 20, 2012 at 11:23
  • Is there any reasonable argument why you're sticking controls in a procedural code? Commented Dec 20, 2012 at 11:46
  • 1
    @PiotrPtak He's dynamically generating them based on the courses. How else might you do that? Commented Dec 20, 2012 at 13:13

1 Answer 1

1

Fairly sure you can cast the sender to a CheckBox and it will be what you're looking for.

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.