2009-05-22 110 views
0

我有下面的代碼,我認爲應該綁定DataTable到DataGridView,但DataGridView顯示爲空。 DataTable肯定有行,所以我假設我不正確地綁定DataSource的一些方法。有誰看到什麼是錯的:DataGridView不顯示數據表

DataBase db = new DataBase(re.OutputDir+"\\Matches.db"); 
MatchDBReader reader = new MatchDBReader(db.NewConnection()); 

BindingSource bindingSource = new BindingSource(); 
bindingSource.DataSource = reader.GetDataTable(); 

this.dataGridView1.DataSource = bindingSource.DataSource; 
  • 第一行只是獲取一個句柄,我是從提取數據的數據庫。
  • 下一行是提供了一個從同一個數據庫讀取的類 - 特別是它暴露了GetDataTable方法,並返回了我打算放入DataGridView的數據表。
  • 下一行是無趣...
  • 第四行試圖搶在數據表 - 快速監視表明,這是工作...
  • 的最後一行是我認爲我已經搞砸了......我的理解是,它將DataTable綁定到DataGridView GUI,但沒有任何顯示。

有什麼想法?

回答

0

這一切都沒有爲我工作,但它似乎都是很好的建議。我最終做的是世界上最大最糟糕的黑客攻擊。我希望完成的工作就是簡單地從SQLite數據庫加載數據庫表,並在DataGridView中顯示它(只讀,可排序的列)。實際的數據庫將在運行時以編程方式指定。我通過向表單添加DataGridView並使用嚮導來靜態定義數據庫連接字符串來定義DataSet。然後,我走進了Settings.Designer.cs文件,並添加了set訪問到數據庫連接字符串屬性:

namespace FormatDetector.Properties { 


    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] 
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "9.0.0.0")] 
    internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { 

     private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); 

     public static Settings Default { 
      get { 
       return defaultInstance; 
      } 
     } 

     [global::System.Configuration.ApplicationScopedSettingAttribute()] 
     [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] 
     [global::System.Configuration.SpecialSettingAttribute(global::System.Configuration.SpecialSetting.ConnectionString)] 
     [global::System.Configuration.DefaultSettingValueAttribute("data source=E:\\workspace\\Test\\Matches.db;useutf16encoding=True")] 
     public string MatchesConnectionString { 
      get { 
       return ((string)(this["MatchesConnectionString"])); 
      } 
      set 
      { 
       (this["MatchesConnectionString"]) = value; 
      } 
     } 
    } 
} 

這是一個klugey黑客,但它的作品。關於如何清理這個爛攤子的建議不僅值得歡迎。

布賴恩

1

在獲取數據表之前,您需要將BindingSource附加到您的網格。

嘗試切換代碼的​​最後兩行:

DataBase db = new DataBase(re.OutputDir+"\\Matches.db"); 
MatchDBReader reader = new MatchDBReader(db.NewConnection()); 
BindingSource bindingSource = new BindingSource(); 
this.dataGridView1.DataSource = bindingSource.DataSource; 
bindingSource.DataSource = reader.GetDataTable(); 
2

嘗試直接綁定的DataGridView到BindingSource,而不是的BindingSource的DataSource:

this.dataGridView1.DataSource = bindingSource; 
1

除了上述解決方案還修復了「 bindingSource「datamember屬性。像:

bindingSource.DataMember = yourDataSet.DataTable; 

我有同樣的問題與sql數據庫和datagrid視圖。在經歷了很多麻煩之後,我發現我忘了設置綁定源的dataMember屬性。

祝你好運。

+0

這實際上是什麼即時通訊在這裏做這行: bindingSource.DataSource = reader.GetDataTable(); – 2009-05-25 16:36:55

0

DataGridView需要DataTable作爲基礎。 DataTable列將其類型保存爲屬性。

如果這種類型是一個接口,所有你會看到是空單元格。