现在的位置: 首页 > 综合 > 正文

winform datagridview 如何根据类别来自动添加行。

2012年10月06日 ⁄ 综合 ⁄ 共 2795字 ⁄ 字号 评论关闭

1.思路。如果添加类别3的数据,则在类别3的下面自动添加一行。如果是在类别4下添加数据,则在类别4下自动添加一行。

代码如下:

 

View Code
 1 1.根据实际业务需要,根据类型添加行。当在type为3、4的地方插入插入数据时,自动添加行。如下图:
 2 
 3  
 4 
 5 画圈部分是要插入的数据。思路:在插入数据时,判断所插入的数据是否处于类型3或者是类型4的范围。如果是就执行插入,如果不是,就不插入。
 6 
 7 代码如下:
 8 
 9   public partial class Form1 : Form
10     {
11         BindingList<Person> bList = new BindingList<Person>(); //数据源
12         public Form1()
13         {
14             InitializeComponent();
15         }
16 
17         private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
18         {
19             DataGridView dgv = (DataGridView)sender;
20             int intCurRow = dgv.CurrentCellAddress.Y; //获取行号
21             int intTypeThreeIndex = GetTypeThreeIndex();
22             int intTypeFourIndex = GetTypeFourIndex();
23             string msg = "新增一行";
24             if (intTypeThreeIndex == intCurRow)
25             {
26                 bList.Insert(intTypeThreeIndex+1,new Person("","","",3,23));
27                 MessageBox.Show(msg);
28             }
29             else if (intTypeFourIndex==intCurRow)
30             {
31                 bList.Insert(intTypeFourIndex+1,new Person("","","",4,23));
32             }
33 
34         }
35 
36         private void Form1_Load(object sender, EventArgs e)
37         {
38            
39             bList.Add(new Person("wtq""""13616009873"123));
40             bList.Add(new Person("wtm""""13616009873"123));
41             bList.Add(new Person("wts""""13616009873"123));
42             bList.Add(new Person("wss""""13616009873"223));
43             bList.Add(new Person("wtt""""13616009873"223));
44             bList.Add(new Person("waa""""13616009873"223));
45             bList.Add(new Person("waa""""13616009873"323));
46             bList.Add(new Person("waa""""13616009873"323));
47             bList.Add(new Person(type:3));//采用命名参数的方法
48             bList.Add(new Person(type: 3));
49             bList.Add(new Person("waa""""13616009873"423));
50             bList.Add(new Person("waa""""13616009873"423));
51             bList.Add(new Person("waa""""13616009873"423));
52             bList.Add(new Person(type: 4));
53             bList.Add(new Person(type: 4));
54             dataGridView1.DataSource = bList;
55         }
56         /// <summary>
57         /// 获取类型为3的最后的索引
58         /// </summary>
59         /// <returns></returns>
60         private int GetTypeThreeIndex()
61         {
62             return bList.Where(T => T.PType <= 3 && T.PType>=1).ToList().Count-2;
63         }
64 
65         /// <summary>
66         /// 获取类型为4的最后的索引
67         /// </summary>
68         /// <returns></returns>
69         private int GetTypeFourIndex()
70         {
71             return bList.ToList().Count-2;
72         }
73     }

 

 

 

抱歉!评论已关闭.