C#中使用DataGridView控件显示数组中的内容


DataGridView控件可以将数组设置为数据源,显示数组数据。
1.网格中显示数组对象的所有属性;
2.如果数据源为字符串数组,则只会显示字符串长度,不会显示字符串内容,这是因为字符串只有Length一个属性;
3.显示字符串的解决方案是创建一个类,设置字符串类型的属性。

实例:在DataGridView中显示字符串数组

TestDataGridViewArray:

Form1.cs

01. usingSystem;
02. usingSystem.Collections.Generic;
03. usingSystem.ComponentModel;
04. usingSystem.Data;
05. usingSystem.Drawing;
06. usingSystem.Text;
07. usingSystem.Windows.Forms;
08.
09. namespaceTestDataGridViewDataSource
10. {
11. publicpartialclassForm1:Form
12. {
13. publicForm1()
14. {
15. InitializeComponent();
16. }
17.
18. //使用字符串数组,结果显示字符串的第一个公共属性Length
19. privatevoidbutton1_Click(objectsender,EventArgse)
20. {
21. string[]stuff=newstring[]{"One","Two","Three"};
22. dataGridView1.AutoGenerateColumns=true;
23. dataGridView1.DataSource=stuff;
24. }
25.
26. //使用类包装字符串,能正确显示字符串
27. privatevoidbutton2_Click(objectsender,EventArgse)
28. {
29. Item[]items=newItem[]{
30. newItem("One"),
31. newItem("Two"),
32. newItem("Three")
33. };
34. dataGridView1.AutoGenerateColumns=true;
35. dataGridView1.DataSource=items;
36. }
37. }
38.
39. publicclassItem
40. {
41. privatestringtext;
42.
43. publicItem(stringtext)
44. {
45. this.text=text;
46. }
47.
48. publicstringText
49. {
50. get
51. {
52. returntext;
53. }
54. }
55. }
56. }


  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值