C#实例:datagridview单元格合并

 这是替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[i].Cells[0].EditedFormattedValue.ToString();
                if (otherValue == "True")
                    MessageBox.Show(dataGridView1.Rows[i].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[i].Cells[0].EditedFormattedValue.ToString();
                                    if (otherValue == "True")
                                    {
                                        ((DataGridViewCheckBoxCell)dataGridView1.Rows[i].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;
                    }
                }
                


            }
        }


       
    }
}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: C# DataGridView控件可以通过设置单元格合并属性来实现单元格合并。具体步骤如下: 1. 设置需要合并单元格合并属性,可以通过设置单元格的RowSpan和ColumnSpan属性来实现。例如,将第1行第1列和第2列合并,可以设置第1行第1列的RowSpan属性为2,ColumnSpan属性为1,设置第1行第2列的Visible属性为false。 2. 在DataGridView的CellPainting事件中绘制合并后的单元格。在该事件中,可以通过判断当前单元格是否需要合并,如果需要合并,则绘制合并后的单元格。 3. 在DataGridView的CellFormatting事件中设置合并后的单元格的值。在该事件中,可以通过判断当前单元格是否需要合并,如果需要合并,则设置合并后的单元格的值。 示例代码如下: private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) { if (e.RowIndex == && e.ColumnIndex == ) { e.Graphics.FillRectangle(Brushes.LightGray, e.CellBounds); e.Graphics.DrawRectangle(Pens.Black, e.CellBounds); e.PaintContent(e.CellBounds); e.Handled = true; } else if (e.RowIndex == && e.ColumnIndex == 1) { e.Graphics.FillRectangle(Brushes.LightGray, e.CellBounds); e.Graphics.DrawRectangle(Pens.Black, e.CellBounds); e.PaintContent(e.CellBounds); e.Handled = true; } else if (e.RowIndex == 1 && e.ColumnIndex == 1) { e.Graphics.FillRectangle(Brushes.LightGray, e.CellBounds); e.Graphics.DrawRectangle(Pens.Black, e.CellBounds); e.PaintContent(e.CellBounds); e.Handled = true; } } private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { if (e.RowIndex == && e.ColumnIndex == ) { e.Value = "合并单元格"; e.FormattingApplied = true; } else if (e.RowIndex == && e.ColumnIndex == 1) { e.Value = ""; e.FormattingApplied = true; } else if (e.RowIndex == 1 && e.ColumnIndex == 1) { e.Value = ""; e.FormattingApplied = true; } } ### 回答2: 很抱歉,由于上下文不清,我无法准确理解"C"指的是什么。请您提供更多信息或者重新描述您的问题,这样我才能给出更准确的回答。 ### 回答3: C是计算机科学中非常重要的编程语言之一。它是由Dennis M. Ritchie在20世纪70年代初开发的,用于编写UNIX操作系统。C语言是一种通用的高级编程语言,可以用于开发各种类型的应用程序,例如操作系统、驱动程序、嵌入式系统、网络应用程序、游戏等。它被广泛用于编写高性能和低级别的程序。 C语言的优点之一是它具有非常高的可移植性。这是因为它的语法规则在各种计算机平台和操作系统中都非常相似,因此很容易将代码从一个平台移植到另一个平台上。C语言也非常高效,因为它允许程序员直接访问计算机硬件,从而使程序能够更快地执行,并且在计算机内存中占用更少的空间。 C语言还具有很强的可扩展性。程序员可以自己编写具有特定功能的库,并将其用于不同的应用程序中。这使得程序员能够更快地编写代码,并且可以更容易地进行调试和维护。C语言也支持面向对象编程和函数式编程,从而使得程序员可以使用不同的编程范式来解决问题。 尽管C语言的语法相对较为简单,但它需要程序员本身具有很高的技能水平。这是因为在C语言中,程序员需要自己管理内存和处理指针,这需要一定的专业知识。此外,C语言也缺乏内置的保护机制,例如有一些安全性问题:如果程序员不能正确处理输入输出和错误处理等测试,那么将会发生内存泄漏或缓冲区溢出等问题。 C语言在计算机科学领域中有着境广泛的应用。无论是个人计算机还是超级计算机,都可以用C语言来编写程序。它也被用于编写操作系统的内核、数据库、编译器、网络协议和游戏等。C语言在计算机科学教育中也是学习编程的基础,因为它能够使学生更好地理解编程的概念和原理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值