不使用数据库数据可以使用DataGridView吗?

Can I use DataGridView without using database data?

我有一个客户端-服务器程序,服务器收到 [进程 ID、主机名、应用程序名称、文件路径],我想将它们放在 table 中。截至目前,它们以一串形式发送。即使 DataGridView 不在数据库中也可以使用,还是有其他选择?

谢谢。

简短的回答是肯定的。

  • 您可以将 List<T> 用作 DataSource
  • 您可以将 DataTable 用作 DataSource(与数据库无关的 DataTable)
  • 您可以在没有 DataSource 且仅定义列和添加行的情况下使用它

List<T>一起使用作为DataSource例如:

var data= new List<DataClass>();
data.Add(new DataClass(){Property1=1 , Property2= "One"   });
data.Add(new DataClass(){Property1=2 , Property2= "Two"   });
data.Add(new DataClass(){Property1=3 , Property2= "Three" });

dataGridView1.DataSource= data;

结果将是一个具有 2 列(Property1、property2)和 3 行的 dataGridView。

在上面的示例中,DataClass 是一个 class,如下所示:

public class 数据类 { public int Property1 {get;放;} public string Property2 {get;放;} }

对于更高级的场景,您可以使用 DataSource window 将新的 DataSource 添加到您的项目中。您也可以添加对象数据源。

使用 DataTable 作为 DataSource

您可以创建一个 DataTable 并使用 dataTable.Columns.Add 添加列,然后使用 dataTable.Rows.Add 添加行,然后将其设置为网格的 DataSource

不使用DataSource

DataGridView 即使没有数据源也可以工作。您只需向 DataGidView 添加一些列,然后使用 datGridView1.Rows.Add 添加新行即可。