Can I use DataGridView without using database data?

时光总嘲笑我的痴心妄想 提交于 2019-12-08 04:23:27

问题


I have a client-server program and the server receives [Process ID, Hostname, App Name, File Path] and I want to put them in a table. As of now they are sent in one string. Is DataGridView applicable to use even if they are not inside a database or is there another option?

Thanks.


回答1:


The short answer is Yes.

  • You can use a List<T> as DataSource
  • You can use a DataTable as DataSource (DataTable not related to db)
  • You can use it without DataSource and only defining columns and adding rows

Use with List<T> as DataSource for example:

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;

And the result will be a dataGridView with 2 columns (Property1, property2) and 3 rows.

In above example, DataClass is a class like the following:

public class DataClass { public int Property1 {get; set;} public string Property2 {get; set;} }

For more advance scenarios you can use DataSource window to add new DataSource to your project. You can add Object datasource as well.

use with a DataTable as DataSource

You can create a DataTable and add your columns to it using dataTable.Columns.Add then add your rows using dataTable.Rows.Add and then set it as DataSource of grid.

Use without DataSource

DataGridView can work even without datasource. It's enough that you add some columns to DataGidView, then using datGridView1.Rows.Add add new rows to it.



来源:https://stackoverflow.com/questions/32576160/can-i-use-datagridview-without-using-database-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!