为DataGridView控件实现复选功能
2024-09-29 17:23:21
实现效果:
知识运用:
DataGridViewCheckBoxColumn类
实现代码:
private class Fruit
{
public int Price { get; set; }
public string Name { get; set; }
public bool ft;
} private List<Fruit> P_fruit;
private void Form1_Load(object sender, EventArgs e)
{
DataGridViewCheckBoxColumn dgvc = new DataGridViewCheckBoxColumn(); //创建列对象
dgvc.HeaderText = "状态"; //设置列标题
dataGridView1.Columns.Add(dgvc); //添加列
P_fruit = new List<Fruit>() //创建数据集合
{
new Fruit(){Price=21,Name="水蜜桃"},
new Fruit(){Price=33,Name="榴莲"},
new Fruit(){Price=24,Name="柑橘"},
new Fruit(){Price=22,Name="黄柠檬"},
new Fruit(){Price=21,Name="紫葡萄"}
};
dataGridView1.DataSource = P_fruit; //绑定数据集合
dataGridView1.Columns[0].Width = 50; //设置列宽
dataGridView1.Columns[1].Width = 140; //设置列宽
dataGridView1.Columns[2].Width = 150; //设置列宽
} private void btn_remove_Click(object sender, EventArgs e)
{
for (int i = 0; i < dataGridView1.Rows.Count; i++) //遍历行集合
{
if (dataGridView1.Rows[i].Cells[0].Value != null && dataGridView1.Rows[i].Cells[1].Value != null &&
dataGridView1.Rows[i].Cells[2].Value != null) //判断值是否为空
{
if (Convert.ToBoolean(dataGridView1.Rows[i].Cells[0].Value.ToString())) //判断是否选中项
{
P_fruit.RemoveAll( //标记集合中的指定项
(pp) =>
{
if (pp.Name == dataGridView1.Rows[i].Cells[2].Value.ToString() &&
pp.Price == Convert.ToSingle(dataGridView1.Rows[i].Cells[1].Value.ToString()))
pp.ft = true; //开始标记
return false; //不删除项
});
}
}
}
P_fruit.RemoveAll( //删除集合中的指定项
(pp) =>
{
return pp.ft;
});
dataGridView1.DataSource = null; //绑定为空
dataGridView1.DataSource = P_fruit; //绑定到数据集合
dataGridView1.Columns[0].Width = 50; //设置列宽
dataGridView1.Columns[1].Width = 140; //设置列宽
dataGridView1.Columns[2].Width = 150; //设置列宽
}
最新文章
- Python 基础之一变量和赋值
- 解析大型.NET ERP系统数据访问 对象关系映射框架LLBL Gen Pro
- jsp+servlet+mysql 实现简单的银行登录转账功能
- SQL 获取查询IO信息
- SPOJ PHRASES 后缀数组
- List,Set,Map用法以及区别(转)
- 使用 jQuery Mobile 与 HTML5 开发 Web App —— HTML5 离线缓存
- 关于Android中混淆的问题
- C++11用于元编程的类别属性
- (剑指Offer)面试题35:第一个只出现一次的字符
- C/C++编译过程理解【转】
- 在word中使用notepad++实现代码的语法高亮
- 去除scons构建动态库的前缀lib
- 洛谷 U4704 函数
- java中读取配置文件ResourceBundle和Properties两种方式比较
- 位运算之——按位与(&;)操作——(快速取模算法)
- linux基础命令--rmdir 删除空目录
- Centos7使用yum快速安装ansible
- 自从硬派网倒闭后,就没有什么好看的IT硬件网站了
- 教你用ActiveReports分析京东双十一数据的价值