[英]Displaying an IList of User Objects in a DataGridView
我們是Java開發人員,他們試圖用C#支持一個項目,但是似乎無法弄清楚如何將一個對象列表(該對象在UI中以及由UI不斷更新)綁定到DataGridView,因此一旦添加它們就可以看到它們。
UI要求跟蹤其使用並在數據網格中將其顯示回給用戶(用於人為因素分析)。 我們正在實現IList接口,並繼承我們的日志記錄類之一:
public class DataSourceAppender : Logger, IList<LogEvent>
{
private List<LogEvent> _events = new List<LogEvent>();
每次用戶單擊控件或執行某些感興趣的操作時,我們都會在列表中添加(附加)新的LogEvent對象,並按發生時的順序記錄交互的各種詳細信息。 此列表在用戶測試會話結束時轉儲到文件中以進行分析。 現在,我們需要在會話進行過程中在數據網格中向用戶顯示此信息。
我們的主要方法包括:
// create a new logger(appender) which holds all our log events
consoleSource = new DataSourceAppender();
consoleSource.Append("INIT", "Client Initialized");
// add the logger the the console data grid and wire-up the data binding
mainform.consoleDataGrid.AutoGenerateColumns = true;
mainform.consoleBinding.DataSource = typeof(LogEvent);
mainform.consoleBinding.DataSource = consoleSource;
consoleSource.Binding = mainform.consoleBinding;
DataSourceAppender(又名consoleSource)中的append方法包含:
public override void Append(string category, object entry)
{
long now = (System.DateTime.Now.Ticks - 621355968000000000) / 10000;
if (lastevent == 0) lastevent = now;
try
{
LogEvent logevent = new LogEvent(now, category, (now - lastevent), Log.Interval, entry);
// add the new log event to this data sorce
lock (_events)
{
_events.Add(logevent);
}
if (_binding != null) _binding.ResetBindings(false);
}
catch (Exception e)
{
System.Console.Error.WriteLine(this.GetType().FullName + " error: " + e + ":" + e.Message);
}
}
結果是第一個“ INIT”條目顯示在數據網格中,但DataSourceAppender(aka consoleSource)中沒有其他事件顯示。 它們都在以后寫入磁盤,因此我們知道Append方法正在被調用,否則可以正常工作。
一些目標:
我們一直在搜索論壇和MSDN頁面,並找到大量示例以綁定到數據庫並手動更新數據網格,但是關於通過編程將數據通過其后備數據存儲添加到數據網格的信息很少。
任何幫助將不勝感激。
由於看不到整個DataSourceAppender
類,因此無法確定您要做什么。
我看到您已將consoleSource
分配為您的數據源,因此您沒有在網格中看到任何新添加的項目這一事實表明,您沒有正確實現IList
來包裝_events
;
但是無論如何,通過嘗試實現IList
都會使生活變得不必要的艱辛。 只需將_events
分配為您的數據源。 如果願意,可以將其公開為DataSourceAppender
的屬性:
public IEnumerable<LogEvent> EventList { get { return _events; } }
然后:
mainform.consoleBinding.DataSource = consoleSource.EventList;
另外,您不需要此行:
mainform.consoleBinding.DataSource = typeof(LogEvent);
基本上,這就是全部:
events = new Collection<LogEvent>(); // or List<> if you want
bindingSource.DataSource = events;
dataGridView.DataSource = bindingSource;
然后添加以下內容:
events.Add(event);
bindingSource.ResetBindings(false);
或者簡單地:
bindingSource.Add(event);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.