Search code examples
c#wpf-grid

Is there a way to check if a grid cell, NOT datagrid cell, contains an object


I'm assigning textboxes to cells in a grid but will like to confirm if an object already exists in the cell before assigning. Is it possible to query a row at a specific column that returns null if empty?

I could create a list of lists representing the grid which I modify as i add and remove objects but this sounds to be inefficient.

A sample code I've written:

TextBlock _text = new TextBlock()
                {
                    Text = _cont,
                    Background = new SolidColorBrush(_colo.disciplinecolor)
                }; TextBlockStyle(_text);
                int index = SearchDate((DateTime)_dt);
                Grid.SetRow(_text, 1); Grid.SetColumn(_text, index);
                Maindispgrid.Children.Add(_text);

Essentially this code block is called every time the user clicks a button with the TextBlock added to a dated column(pre-selected by the user), and hopefully, the next available row in the column . I've tried GetRow() but this searched by UIElement which didn't seem to work as all TextBlock are created with the same name.

I might have approached this all wrong so any leads as to what I need to read up on will be much appreciated.

Basically the end result should hopefully work as this:

TextBlock _text = new TextBlock()
                {
                    Text = _cont,
                    Background = new SolidColorBrush(_colo.disciplinecolor)
                }; TextBlockStyle(_text);
                int index = SearchDate((DateTime)_dt);
                //check for next available row at specific column index
                Grid.SetRow(_text, nextAvailableRow); Grid.SetColumn(_text, index);
                Maindispgrid.Children.Add(_text);

Solution

  • You can iterate over the children list via Maindispgrid.Children. For each child, retrieve the assigned Row and Column value (if assigned at all). Use this information to calculate the available row.

    IList<int[]> indices = new List<int[]>();
    foreach (var child in Maindispgrid.Children)
    {
        int rowIndex = Grid.GetRow(child);
        int columnIndex = Grid.GetColumn(child);
        indices.Add(new int[] {rowIndex, columnIndex});
    }
    // work with the "indices" list