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


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

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

TestDataGridViewArray:

Form1.cs

01. using System;
02. using System.Collections.Generic;
03. using System.ComponentModel;
04. using System.Data;
05. using System.Drawing;
06. using System.Text;
07. using System.Windows.Forms;
08.  
09. namespace TestDataGridViewDataSource
10. {
11. public partial class Form1 : Form
12. {
13. public Form1()
14. {
15. InitializeComponent();
16. }
17.  
18. //使用字符串数组,结果显示字符串的第一个公共属性Length
19. private void button1_Click(object sender, EventArgs e)
20. {
21. string[] stuff = new string[] { "One""Two""Three" };
22. dataGridView1.AutoGenerateColumns = true;
23. dataGridView1.DataSource = stuff;
24. }
25.  
26. //使用类包装字符串,能正确显示字符串
27. private void button2_Click(object sender, EventArgs e)
28. {
29. Item[] items = new Item[] {
30. new Item("One"),
31. new Item("Two"),
32. new Item("Three")
33. };
34. dataGridView1.AutoGenerateColumns = true;
35. dataGridView1.DataSource = items;
36. }
37. }
38.  
39. public class Item
40. {
41. private string text;
42.  
43. public Item(string text)
44. {
45. this.text = text;
46. }
47.  
48. public string Text
49. {
50. get
51. {
52. return text;
53. }
54. }
55. }
56. }


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值