
1: 数据增加一行 重新绑定
DataTable dt = new DataTable() //---全局数据源
在窗体中load时 设定数据源绑定
点击按钮增加一条数据代码
DataRow dr = dt.NewRow()
dr["ID"] = 2
dr["Names"] = "程序直接对数据源 *** 作"
dt.Rows.Add(dr)
2:直接增加一行
此方式不可与1相混合使用,只能适合不是数据源绑定的方式 代码如下
int index = dgv.Rows.Add()
DataGridViewRow dgvr = dgv.Rows[index]
dgvr.Cells[0].Value = 3
dgvr.Cells[1].Value = "直接添加一行"
你可以试试,不知道是否是你想要的
点gridview编辑列,添加TemplateField,位置可以自己调动,确定,再点编辑模板,在模板的ItemTemplate中丢入Button控件,这样就能自动生成每行的按钮,如果是你想做成删除按钮
把Button的属性CommandArgument="delete",它是激活gridview
的RowDeleting事件!设置gridview
属性
DataKeyNames
:"你要获取的字段值",如:ID
你添加gridview
RowDeleting事件后
GridView1.DataKeys[e.RowIndex].Value.ToString()就能获取该行的ID值!然后就是删除语句了~
1)向Form1中拖入一个GridControl,两个Button
2)后台代码
using Systemusing 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中增、删、修改,实际上是对数据源(数据集合)的增、删、修改。也就是说:对数据源修改会"反映"到界面的控件上。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)