找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 1866|回复: 12

C#实例:datagridview单元格合并

 火.. [复制链接]
  • 打卡等级:即来则安
  • 打卡总天数:29
  • 打卡月天数:1
  • 打卡总奖励:7791
  • 最近打卡:2025-12-13 17:25:16

2540

主题

1355

回帖

2万

积分

管理员

积分
21304
发表于 2021-8-3 19:43:52 | 显示全部楼层 |阅读模式
来源:zls365 CSharp编程大全
这是替C#微信交流群群友做的一个小实例,目的就是在datagridview选择对应行以后,点击button后获取对应行的ip,并执行相应的操作,其实我觉得这样的话button没必要非放置到datagridview里面的!但是为了满足群友的需求,还是这么做了。
先看一下运行效果:


1. DataGridView 添加一列checkbox

DataGridViewCheckBoxColumn newColumn = new DataGridViewCheckBoxColumn();
newColumn.HeaderText = "选择";
dataGridView1.Columns.Add(newColumn);

这样添加的列是放在最后一列,也许你希望它在其它列,例如第二列,那么可以:

dataGridView1.Columns.Insert(1, newColumn);
2. DataGridView 添加一个button
btn1.Name = "btnRun";
btn1.Text = "Run";
btn1.Visible = true;
btn1.Location = new Point(550, 80);
btn1.Size = new Size(80, 50);
btn1.Parent = this;
btn1.Click += new EventHandler(btn1_Click);
//this.Controls.Add(btn1);
dataGridView1.Controls.Add(btn1);
3. datagridview合并单元格,详见完整代码.
完整代码:
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;namespace WindowsFormsApp28{    public partial class Form1 : Form    {        public Form1()        {            InitializeComponent();        }        Button btn1 = new Button();        private void Form1_Load(object sender, EventArgs e)        {            DataTable dt = new DataTable();            dt.Columns.Add("IP");            dt.Columns.Add("Option");            dt.Columns.Add("button");            dt.Rows.Add("192.168.1.10", null, null);            dt.Rows.Add("192.168.1.11", null, null);            dt.Rows.Add("192.168.1.12", null, null);            dt.Rows.Add("192.168.1.13", null, null);            dt.Rows.Add("192.168.1.14", null, null);            dt.Rows.Add("192.168.1.15", null, null);            dt.Rows.Add("192.168.1.16", null, null);            dt.Rows.Add("192.168.1.17", null, null);            dt.Rows.Add("192.168.1.18", null, null);            dt.Rows.Add("192.168.1.19", null, null);            dataGridView1.DataSource = dt;            //var list = new List<Object>();            //list.Add(new { IP = "192.168.1.10", Option = "null", button = "null" });            //list.Add(new { IP = "192.168.1.11", Option = "null", button = "null" });            //list.Add(new { IP = "192.168.1.12", Option = "null", button = "null" });            //list.Add(new { IP = "192.168.1.13", Option = "null", button = "null" });            //list.Add(new { IP = "192.168.1.14", Option = "null", button = "null" });            //list.Add(new { IP = "192.168.1.15", Option = "null", button = "null" });            //dataGridView1.DataSource = list;            DataGridViewCheckBoxColumn newColumn1 = new DataGridViewCheckBoxColumn();            newColumn1.HeaderText = "选择";            //dataGridView1.Columns.Add(newColumn);            dataGridView1.Columns.Insert(3, newColumn1);            DataGridViewButtonColumn newColumn2 = new DataGridViewButtonColumn();            newColumn2.HeaderText = "控件";            //dataGridView1.Columns.Add(newColumn);            dataGridView1.Columns.Insert(4, newColumn2);            dt.Columns.Add("action");            dataGridView1.Rows[0].Cells[0].Value = true;            //dataGridView1.Rows[0].Cells[1].Value = true;                       btn1.Name = "btnRun";            btn1.Text = "Run";            btn1.Visible = true;            btn1.Location = new Point(550, 80);            btn1.Size = new Size(80, 50);            btn1.Parent = this;            btn1.Click += new EventHandler(btn1_Click);            //this.Controls.Add(btn1);            dataGridView1.Controls.Add(btn1);        }        private void btn1_Click(object sender, EventArgs e)        {            // MessageBox.Show("123");            for (int i = 0; i < dataGridView1.Rows.Count; i++)            {                string otherValue = dataGridView1.Rows.Cells[0].EditedFormattedValue.ToString();                if (otherValue == "True")                    MessageBox.Show(dataGridView1.Rows.Cells[2].Value.ToString());            }        }        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)        {            if (e.ColumnIndex == dataGridView1.Columns[1].Index)                MessageBox.Show(dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString());        }        /// <summary>        /// 将当前单元格中的更改提交到数据缓存,但不结束编辑模式,及时获得其状态是选中还是未选中            /// </summary>        /// <param name="sender"></param>        /// <param name="e"></param>        private void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)        {            if (dataGridView1.IsCurrentCellDirty)            {                dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);            }        }        private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)        {            try            {                if (dataGridView1.Rows.Count > 0)                {                    int rowIndex = dataGridView1.CurrentCell.RowIndex;                    int colIndex = dataGridView1.CurrentCell.ColumnIndex;                    if (colIndex == 0) //第一列                    {                        string _selectValue = dataGridView1.CurrentCell.EditedFormattedValue.ToString();                        if (_selectValue == "True")                        {                            for (int i = 0; i < dataGridView1.Rows.Count; i++)                            {                                if (i != rowIndex)                                {                                    string otherValue = dataGridView1.Rows.Cells[0].EditedFormattedValue.ToString();                                    if (otherValue == "True")                                    {                                        ((DataGridViewCheckBoxCell)dataGridView1.Rows.Cells[0]).Value = false;                                    }                                                                  }                            }                        }                    }                }            }            catch (Exception ex)            { }        }        private void button1_Click(object sender, EventArgs e)        {        }        private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)        {            // 对第5列相同单元格进行合并             if (e.ColumnIndex == 5 && e.RowIndex != -1)            {                using                (                Brush gridBrush = new SolidBrush(this.dataGridView1.GridColor),                backColorBrush = new SolidBrush(e.CellStyle.BackColor)                )                {                    using (Pen gridLinePen = new Pen(gridBrush))                    {                        // 清除单元格                         e.Graphics.FillRectangle(backColorBrush, e.CellBounds);                        // 画 Grid 边线(仅画单元格的底边线和右边线)                         // 如果下一行和当前行的数据不同,则在当前的单元格画一条底边线                         if (e.RowIndex < dataGridView1.Rows.Count - 1 &&                        dataGridView1.Rows[e.RowIndex ].Cells[e.ColumnIndex].Value.ToString() !=                        e.Value.ToString())                            e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left + 2,                            e.CellBounds.Bottom - 1, e.CellBounds.Right - 1,                            e.CellBounds.Bottom - 1);                        //画最后一条记录的底线                         if (e.RowIndex == dataGridView1.Rows.Count - 1)                            e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left + 2,                            e.CellBounds.Bottom - 1, e.CellBounds.Right - 1,                            e.CellBounds.Bottom - 1);                        // 画右边线                         e.Graphics.DrawLine(gridLinePen, e.CellBounds.Right - 1,                        e.CellBounds.Top, e.CellBounds.Right - 1,                        e.CellBounds.Bottom);                        // 画左边线                         e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left ,                        e.CellBounds.Top, e.CellBounds.Left ,                        e.CellBounds.Bottom);                        // 画(填写)单元格内容,相同的内容的单元格只填写第一个                         if (e.Value != null)                        {                            if (e.RowIndex > 0 &&                            dataGridView1.Rows[e.RowIndex - 1].Cells[e.ColumnIndex].Value.ToString() ==                            e.Value.ToString())                            {                            }                            else                            {                                //e.Graphics.DrawString((String)e.Value, e.CellStyle.Font,                                //Brushes.Black, e.CellBounds.X + 2,                                //e.CellBounds.Y + 5, StringFormat.GenericDefault);                            }                        }                        e.Handled = true;                    }                }                            }        }           }}

工控课堂 www.gkket.com

0

主题

106

回帖

390

积分

注册会员

积分
390
发表于 2021-8-5 02:35:50 | 显示全部楼层
强烈支持楼主ing……
工控课堂 www.gkket.com

0

主题

516

回帖

2233

积分

高级会员

积分
2233
发表于 2021-8-5 04:47:49 | 显示全部楼层
看到这帖子真是高兴!
工控课堂 www.gkket.com

0

主题

111

回帖

169

积分

新手上路

积分
169
发表于 2025-11-16 16:58:02 | 显示全部楼层
楼主辛苦啦,期待下一篇分享!
工控课堂 www.gkket.com

0

主题

420

回帖

2557

积分

高级会员

积分
2557
发表于 2025-11-16 17:35:02 | 显示全部楼层
救命!这波发言太秀了,直接原地封神~
疯狂认同!楼主说出了我不敢说的话
工控课堂 www.gkket.com

0

主题

85

回帖

136

积分

新手上路

积分
136
发表于 2025-11-16 17:49:53 | 显示全部楼层
画面感太强了,仿佛身临其境!
工控课堂 www.gkket.com

0

主题

531

回帖

2056

积分

高级会员

积分
2056
发表于 2025-11-16 17:52:06 | 显示全部楼层
笑不活了,评论区比正文还精彩
已转发给朋友,一起快乐一下
工控课堂 www.gkket.com

0

主题

112

回帖

171

积分

新手上路

积分
171
发表于 2025-11-16 17:55:09 | 显示全部楼层
路过打卡,为优质内容疯狂打 call
工控课堂 www.gkket.com

0

主题

103

回帖

457

积分

注册会员

积分
457
发表于 2025-11-16 17:59:34 | 显示全部楼层
已转发给朋友,一起感受这份快乐~
工控课堂 www.gkket.com

0

主题

64

回帖

93

积分

新手上路

积分
93
发表于 2025-11-16 19:41:32 | 显示全部楼层
原来还有这种操作,长见识了!
工控课堂 www.gkket.com
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关闭

站长推荐上一条 /1 下一条

QQ|手机版|免责声明|本站介绍|工控课堂 ( 沪ICP备20008691号-1 )

GMT+8, 2025-12-23 03:58 , Processed in 0.091590 second(s), 26 queries .

Powered by Discuz! X3.5

© 2001-2025 Discuz! Team.

快速回复 返回顶部 返回列表