您的位置:首页 > 其它

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

2011-09-08 01:15 441 查看
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
{
BindingList<Person> bList = new BindingList<Person>(); //数据源
public Form1()
{
InitializeComponent();
}

private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
DataGridView dgv = (DataGridView)sender;
int intCurRow = dgv.CurrentCellAddress.Y; //获取行号
int intTypeThreeIndex = GetTypeThreeIndex();
int intTypeFourIndex = GetTypeFourIndex();
string msg = "新增一行";
if (intTypeThreeIndex == intCurRow)
{
bList.Insert(intTypeThreeIndex+1,new Person("","","",3,23));
MessageBox.Show(msg);
}
else if (intTypeFourIndex==intCurRow)
{
bList.Insert(intTypeFourIndex+1,new Person("","","",4,23));
}

}

private void Form1_Load(object sender, EventArgs e)
{

bList.Add(new Person("wtq", "男", "13616009873", 1, 23));
bList.Add(new Person("wtm", "男", "13616009873", 1, 23));
bList.Add(new Person("wts", "男", "13616009873", 1, 23));
bList.Add(new Person("wss", "男", "13616009873", 2, 23));
bList.Add(new Person("wtt", "男", "13616009873", 2, 23));
bList.Add(new Person("waa", "男", "13616009873", 2, 23));
bList.Add(new Person("waa", "男", "13616009873", 3, 23));
bList.Add(new Person("waa", "男", "13616009873", 3, 23));
bList.Add(new Person(type:3));//采用命名参数的方法
bList.Add(new Person(type: 3));
bList.Add(new Person("waa", "男", "13616009873", 4, 23));
bList.Add(new Person("waa", "男", "13616009873", 4, 23));
bList.Add(new Person("waa", "男", "13616009873", 4, 23));
bList.Add(new Person(type: 4));
bList.Add(new Person(type: 4));
dataGridView1.DataSource = bList;
}
/// <summary>
/// 获取类型为3的最后的索引
/// </summary>
/// <returns></returns>
private int GetTypeThreeIndex()
{
return bList.Where(T => T.PType <= 3 && T.PType>=1).ToList().Count-2;
}

/// <summary>
/// 获取类型为4的最后的索引
/// </summary>
/// <returns></returns>
private int GetTypeFourIndex()
{
return bList.ToList().Count-2;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: