Indhi
Indhi

Reputation: 1694

SelectedItem of DataGrid

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.

UI Design

XAML

 <DataGrid DataContext="{Binding Path=HostData,NotifyOnTargetUpdated=True,Mode=OneWay}" 
    AutoGenerateColumns="False" Name="hostDatagrid" Margin="171,32,235,230">
    <DataGrid.Columns>
    <DataGridTextColumn Header="Host" Width="auto" Binding="{Binding HostID}" />
     <DataGridTextColumn Header="Status" Width="auto" Binding="{Binding HostStatus}"/> 
     </DataGrid.Columns>
  </DataGrid>
 <DataGrid DataContext="{Binding Path=LogData,NotifyOnTargetUpdated=True,Mode=OneWay}"
   AutoGenerateColumns="False" Name="LogDatagrid" Margin="103,108,102,145">
    <DataGrid.Columns>
    <DataGridTextColumn Header="Host ID" Width="auto"  Binding="{Binding HostID}" />
    <DataGridTextColumn Header="Logs" Width="auto"  Binding="{Binding LogID}" />
    <DataGridTextColumn Header="Log Path" Width="auto"  Binding="{Binding LogPath}"/>
    <DataGridTextColumn Header="Date" Width="auto"  Binding="{Binding Date}"/>
    <DataGridTextColumn Header="Last Activity" Width="auto"  Binding="{Binding LastActivity}"/>
  </DataGrid.Columns>

code behind for the LogFile Model:

    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"); }
    }

Code behind for the LogFile ViewModel :

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

    ~LogFileViewModel()
    {
        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
        {
            LogFileData.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)
                LogFileData.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;
        }
    }
}

}

I have followed the same pattern for the Host Model and ViewModel too.

Upvotes: 3

Views: 732

Answers (4)

Joseph Devlin
Joseph Devlin

Reputation: 1800

You will have to have the following in your code viewmodel

A SelectedItem which will hold the selected item in the first DataGrid. A collection HostData that holds all of your hosts. An empty collection Log Data which will display the logs for a particular host

//populate with all your hosts and this will bind to your first datagrid
private ObservableCollection<HostModel> _hostData= new ObservableCollection<Host>();

public ObservableCollection<HostModel> HostData
{
    get { return _hostData; }
    set { _hostData= value; OnPropertyChanged("HostData"); }
}

//populate with all the logs for the selected item and bind this to your second datagrid
private ObservableCollection<LogFileModel> _logFileData = new ObservableCollection<LogFileModel>();

public ObservableCollection<LogFileModel> LogFileData
{
    get { return _logFileData; }
    set { _logFileData = value; OnPropertyChanged("LogFileData"); }
}

//when the user selects an item in the first datagrid this property will hold the value
//so you will bind it to the selected item property of your first datagrid
private Host _selectedHost; //initialise to avoid null issues

public HostModelSelectedHost
{
    get{ return _selectedItem; } 
    set 
    {
        //call a method to populate you second collection
        _selectedHost = value;
        logFileData = GetLogsForSelectedHost(_selectedHost);
        OnPropertyChanged("SelectedHost");
    { 
}

//the method for populating your second collection could look like this
private ObservableCollection<LogFileModel> GetLogsForSelectedHost(_selectedHost)
{
    ObservableCollection<LogFileModel> filteredLogs = new ObservableCollection<LogFileModel>;

    filteredLogs = //fill the collection with all the logs that match the host ID of
                   //your selected item
    return filteredLogs ;
}

I am not sure from your code which class is which but I hope the code above can show you the way of doing this.

Upvotes: 2

Zardaloop
Zardaloop

Reputation: 1624

DO something like this :

creat a method in your main datamodel called search. Search has a query to search your other databse which holds the data log and returns a data table. Then add a CellClick listener method for your Host Status Datagrid and do something like below. I hope I am undrestanding what you need .

private void hostDatagrid_CellClick(object sender, DataGridViewCellEventArgs e)
    {
        string cellValue = hostDatagrid[e.ColumnIndex,e.RowIndex].Value.ToString();
        LogFileViewModel logFileViewModel = new LogFileViewModel();
        DataTable table = logFileViewModel.search(cellValue);
        BindingSource bs = new BindingSource();
        bs.DataSource = table;
        logDataGrid.Datasource = table;
        logDataGrid.Update();
        logDataGrid.Refresh();
    }

   // and add this method to  LogFileViewModel



 public DataTable Search(string hostID)
    {
        DataTable ndt = new DataTable();
        SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
        sqlcon.Open();
        SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM whatever WHERE hostid ="+hostID, sqlcon);
        da.Fill(ndt);
        da.Dispose();
        sqlcon.Close();
        return ndt;


    }

Upvotes: 1

Bob.
Bob.

Reputation: 4002

1) Bind your SelectedItem to a Host property in your ViewModel from your Host DataGrid

SelectedItem = {Binding SelectedHost, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}

2) Assuming LogData is an ObservableCollection, in the setter for SelectedHost property, update LogData to show the logs for the Host.

public Host SelectedHost {
    get;
    set {
        SelectedHost = value;
        UpdateLogData();
        OnPropertyChanged("SelectedHost");
    }

Upvotes: 1

TYY
TYY

Reputation: 2716

You will have to bind your the selected time to an object in your viewmodel and whenever this value changes you can change the collection LogData to show what you want.

Upvotes: 0

Related Questions