Click here to Skip to main content
15,896,154 members

WPF SelectedItem binding between two datagrids

BuBa1947 asked:

Open original thread
I am developing a User Interface for a host monitoring application, which is already being monitored on database level. I have displayed 2 datagrids on my UI which will populate on run time.These two datagrids are connected by the HostID ( HostID is the Foreign Key in the LogDatagrid).

The First datagrid displays the list of Host with their Status(either Running or Stopped). I would like to display the Log Status of the respective HostID when a user wants to know the status in detail. How to achieve this when a user selects the Host ID in the HostDatagrid ? I have added my XAML and screenshot of my UI. ( the datagrid data is populated from a Database-kindly have a look in the ViewModel code).May I know how do I the binding between the selected Item in the Host datagrid to the respective details getting displayed in the Log datagrid? Kindly help
May I know how I do the binding between selected Item in grid and controls in the detail UI?

here is the Model of my class

C#
public LogFileModel()
    {

    }
    private int _hostID;
    public int HostID
    {
        get { return _hostID; }
        set { _hostID= value; OnpropertyChanged("HostID"); }
    }

    private string _logid;
    public string LogID
    {
        get { return _logid; }
        set { _logid= value; OnpropertyChanged("LogID"); }
    }

    private string _logpath;
    public string LogPath
    {
        get { return _logPath; }
        set { _logPath = value; OnpropertyChanged("LogPath"); }
    }

    private DateTime _date;
    public DateTime Date;
    {
        get { return _date; }
        set { _date= value; OnpropertyChanged("Date"); }
    }

    private bool _activity;
    public bool LastActivity
    {
        get { return _activity; }
        set { _activity= value; OnpropertyChanged("LastActivity"); }
    }


ViewModel for my log table

C#
LogModel _myModel = new LogModel();
private ObservableCollection<LogFileModel> _logData = new  ObservableCollection<LogFileModel>();
  public ObservableCollection<LogFileModel> LogData
    {
        get { return _logData; }
        set { _logData = value; OnPropertyChanged("LogData"); }
    }
   public LogViewModel()
    {
        initializeload();
        timer.Tick += new EventHandler(timer_Tick);
        timer.Interval = new TimeSpan(0, 0, 3);
        timer.Start();
    }

    ~LogViewModel()
    {
        Dispose(false);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (!disposed)
        {
            if (disposing)
            {
                timer.Stop();
                timer.Tick -= new EventHandler(timer_Tick);
            }
            disposed = true;
        }
    }

    private void timer_Tick(object sender, EventArgs e)
    {
        try
        {
            LogData.Clear();
            initializeload();
        }
        catch (Exception ex)
        {
            timer.Stop();
            Console.WriteLine(ex.Message);

        }
    }

    private void initializeload()
    {
        try
        {
            DataTable table = _myModel.getData();

            for (int i = 0; i < table.Rows.Count; ++i)
                LogData.Add(new LogFileModel
                {
                   HostID= Convert.ToInt32(table.Rows[i][0]),
                   LogID = table.Rows[i][1].ToString(),
                   LogPath = table.Rows[i][2].ToString(),
                   Date = Convert.ToDateTime(table.Rows[i][3]),
                   LastAcivity= table.Rows[i][4].ToString(),                   
                });
        }

        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
    }
    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged(string propertyname)
    {
        var handler = PropertyChanged;
        if (handler != null)
            handler(this, new PropertyChangedEventArgs(propertyname));
    }

    public class LogModel
    {
        public DataTable getData()
        {
            DataTable ndt = new DataTable();
            SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
            sqlcon.Open();
            SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM [LocalDB].[dbo].[LogFiles]", sqlcon);
            da.Fill(ndt);
            da.Dispose();
            sqlcon.Close();
            return ndt;
        }
    }
}



EDIT
I have added a new MainViewModel to my existing program

C#
public class MainViewModel : ViewModel
{
    private LogViewModel _SubLogViewModel = new LogViewModel();
    public LogViewModel SubLogViewModel
    {
        get
        {
            return _SubLogViewModel;
        }
        set
        {
            if (_SubLogViewModel != value)
            {
                _SubLogViewModel = value;
                OnpropertyChanged("SubLogViewModel");
            }
        }
    }

    private HostViewModel _SubHostViewModel = new HostViewModel();
    public HostViewModel SubHostViewModel
    {
        get
        {
            return _SubHostViewModel;
        }
        set
        {
            if (_SubHostViewModel != value)
            {
                _SubHostViewModel = value;
                OnpropertyChanged("SubHostViewModel");
            }
        }
    }

    private Host _SelectedHost;
    public Host SelectedHost
    {
        get
        {
            return _SelectedHost;
        }
        set
        {
            if (_SelectedHost!= value)
            {
                _SelectedHost= value;
                OnpropertyChanged("SelectedHost");
                if(this.SelectedHost != null && this.SubLogViewModel != null)
                {
// I dont know how to get the values for Log grid. here Loadlogs is just an imaginary method I have added , it is not defined in my program.
 
                    this.SubLogViewModel.LoadLogs(this.SelectedHost);
                }
            }
        }
    }
}



EDIT : New Xaml

XML
<Grid>
    <Grid.DataContext>
        <host:MainViewModel />
    </Grid.DataContext>

    <DataGrid Name="hostDataGrid" DataContext="{Binding SubHostViewModel}" SelectedItem="{Binding SelectedHost, Mode=TwoWay}">
        ...
    </DataGrid>

    <DataGrid Name="LogDatagrid" DataContext="{Binding SubLogViewModel}">

    </DataGrid>
</Grid>




Kindly help me to proceed further.
Thanks to whom ever it may concern.
Tags: C#, XAML, WPF

Plain Text
ASM
ASP
ASP.NET
BASIC
BAT
C#
C++
COBOL
CoffeeScript
CSS
Dart
dbase
F#
FORTRAN
HTML
Java
Javascript
Kotlin
Lua
MIDL
MSIL
ObjectiveC
Pascal
PERL
PHP
PowerShell
Python
Razor
Ruby
Scala
Shell
SLN
SQL
Swift
T4
Terminal
TypeScript
VB
VBScript
XML
YAML

Preview



When answering a question please:
  1. Read the question carefully.
  2. Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
  3. If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.
  4. Don't tell someone to read the manual. Chances are they have and don't get it. Provide an answer or move on to the next question.
Let's work to help developers, not make them feel stupid.
Please note that all posts will be submitted under the http://www.codeproject.com/info/cpol10.aspx.



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900