當前位置:編程學習大全網 - 編程語言 - c# devexpress 中的Gridcontrol 添加行問題

c# devexpress 中的Gridcontrol 添加行問題

1)向Form1中拖入壹個GridControl,兩個Button

2)後臺代碼

using?System;

using?System.Collections.Generic;

using?System.Linq;

using?System.Windows.Forms;

namespace?WindowsFormsApplication1

{

public?partial?class?Form1?:?Form

{

List<Student>?studentList;?

int?studentId?=?1;

public?Form1()

{

InitializeComponent();

button1.Text?=?"添加新行";

button2.Text?=?"刪除選定行";

BuildDataSource();

}

//為gridcontrol1準備數據源

private?void?BuildDataSource()

{

studentList?=?new?List<Student>();

studentList.Add(new?Student(studentId++)

{?Name?=?"張三",?Course?=?"數學",?Score?=?100?});

studentList.Add(new?Student(studentId++)

{?Name?=?"李四",?Course?=?"數學",?Score?=?90?});

studentList.Add(new?Student(studentId++)

{?Name?=?"王五",?Course?=?"數學",?Score?=?91?});

//綁定!

gridControl1.DataSource?=?studentList;

}

//添加行

private?void?button1_Click(object?sender,?EventArgs?e)

{

//添加行,實際上是向數據源(List<Student>集合)添加新的元素

Student?stu?=?new?Student(studentId++)?

{?Name?=?"錢七",?Course?=?"外語",?Score?=?34?};

studentList.Add(stu);

//向數據源中新加行後,GridControl中自動會添加新行

gridControl1.RefreshDataSource();

}

//刪除行

private?void?button2_Click(object?sender,?EventArgs?e)

{

//獲取所有被選行

int[]?rowIds?=?gridView1.GetSelectedRows();

if?(rowIds.Length?==?0)?return;

//刪除

foreach?(int?rowId?in?rowIds)

{

int?stuId?=?(int)gridView1.GetRowCellValue(rowIds[0],?"Id");

Student?stu?=?studentList.First(s?=>?s.Id?==?stuId);

studentList.Remove(stu);

}

//從數據源中刪除行後,GridControl中自動會刪除對於的行

gridControl1.RefreshDataSource();

}

}

//----------------------------------------

//學生成績類

class?Student

{

public?Student(int?id)

{

Id?=?id;

}

//學號

public?int?Id?{?get;?private?set;?}

//姓名

public?string?Name?{?get;?set;?}

//課程

public?string?Course?{?get;?set;?}

//成績

public?float?Score?{?get;?set;?}

}

}

3)可直接在GridControl中修改行,不需要額外編程(除非妳想校驗輸入數據的合法性)

------

總結: 對 Devexpress GridControl中增、刪、修改,實際上是對數據源(數據集合)的增、刪、修改。也就是說:對數據源修改會"反映"到界面的控件上。

  • 上一篇:幼師發朋友圈文案可愛
  • 下一篇:誰能給我講明白這段代碼?
  • copyright 2024編程學習大全網