给DataGridView添加右键菜单

本人以前用PB做过一些开发,挺喜欢DATAWINDOW的。在学习C#时发现给DataGirdView加上右键菜单的效果和PB中的DATAWINDOW有相同的效果。其中数据库的操作应用的SQLDataAdatper,下面源码奉上,欢迎朋友们提出指正和意见。

 

首先,先建立一个Form窗口取名为DataGridViewDemo 从工具箱中选择控件,并设置属性如下

DataGridView   name属性 dataGridView

TextBox            name属性 txtContent

Button              name属性  btSave   Text 属性  保存

Button              name 属性 btExit     Text属性  退出

 

 

DataGridViewDemo 类代码如下

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace C15Demo
{
    public partial class DataGridViewDemo : Form
    {
        //全局变量
        private SqlDataAdapter adapter = null;
        private DataTable dt = null;
        public DataGridViewDemo()
        {
            InitializeComponent();
        }
        ///


        /// 初始化SQLDataAdapter类添加对数据表的增删改操作
        ///

        private void InitAdapter()
        {
            SqlConnection connection = new SqlConnection();
            connection.ConnectionString = "Persist Security Info=false;Integrated Security=SSPI;Initial Catalog=Northwind;server=(local)";
            adapter = new SqlDataAdapter("select ProductID,ProductName,UnitPrice,Discontinued from Products", connection);
            adapter.FillLoadOption = LoadOption.OverwriteChanges;
            //添加修改命令
            SqlCommand UpdataCommand = new SqlCommand();
            UpdataCommand.Connection = connection;
            UpdataCommand.CommandText = "Update Products set ProductName = @ProductName,UnitPrice=@UnitPrice,Discontinued = @Discontinued where ProductID=@Productid ";
            UpdataCommand.Parameters.Add("@ProductID", SqlDbType.Int, 4, "ProductID");
            UpdataCommand.Parameters.Add("@ProductName", SqlDbType.VarChar, 50, "ProductName");
            UpdataCommand.Parameters.Add("@UnitPrice", SqlDbType.Money, 20, "UnitPrice");
            UpdataCommand.Parameters.Add("@Discontinued", SqlDbType.Bit, 1, "Discontinued");
            adapter.UpdateCommand = UpdataCommand;
            //添加新增
            SqlCommand InsertCommand = new SqlCommand();
            InsertCommand.Connection = connection;
            InsertCommand.CommandText = "Insert into Products (ProductName,UnitPrice,Discontinued)values(@ProductName,@UnitPrice,@Discontinued) ";
            InsertCommand.Parameters.Add("@ProductName", SqlDbType.VarChar, 50, "ProductName");
            InsertCommand.Parameters.Add("@UnitPrice", SqlDbType.Money, 20, "UnitPrice");
            InsertCommand.Parameters.Add("@Discontinued", SqlDbType.Bit, 1, "Discontinued");
            adapter.InsertCommand = InsertCommand;
            //添加删除
            SqlCommand DeleteCommand = new SqlCommand();
            DeleteCommand.Connection = connection;
            DeleteCommand.CommandText = "Delete Products where ProductID=@ProductID ";
            DeleteCommand.Parameters.Add("@ProductID", SqlDbType.Int, 4, "ProductID");
            adapter.DeleteCommand = DeleteCommand;

        }
        ///


        /// 初始化DataGridView并绑定列,给DataGridView添加右键菜单
        ///

        /// DataGrivView控件
        private void InitDataGridView(DataGridView dataGridView)
        {
            dataGridView.AutoGenerateColumns = false;
            dataGridView.AllowUserToAddRows = false  ;
            dataGridView.AllowUserToDeleteRows = false  ;
            dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            dataGridView.EditMode = DataGridViewEditMode.EditOnEnter;
            dataGridView.MultiSelect = false;
            dataGridView.ScrollBars = ScrollBars.Vertical;
            dataGridView.VirtualMode = true;
            //添加列
            DataGridViewTextBoxColumn Column1 = new DataGridViewTextBoxColumn();
            Column1.DataPropertyName = "ProductID";
            Column1.HeaderText = "产品 ID";
            Column1.Name = "Column1";
            //Column1.ReadOnly = true;
            DataGridViewTextBoxColumn Column2 = new DataGridViewTextBoxColumn();
            Column2.DataPropertyName = "ProductName";
            Column2.HeaderText = "产品名称";
            Column2.Name = "Column2";
            Column2.Width = 165;
            DataGridViewTextBoxColumn Column3 = new DataGridViewTextBoxColumn();
            Column3.DataPropertyName = "UnitPrice";
            Column3.HeaderText = "价格";
            Column3.Name = "Column3";
            DataGridViewCheckBoxColumn Column4 = new DataGridViewCheckBoxColumn();
            Column4.DataPropertyName = "Discontinued";
            Column4.HeaderText = "是否使用";
            Column4.Name = "Column4";

            dataGridView.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { Column1, Column2, Column3 ,Column4 });
            //添加右键菜单
            ContextMenuStrip contextMenuStrip = new ContextMenuStrip();
            contextMenuStrip.ShowCheckMargin = false;
            contextMenuStrip.ShowImageMargin = false;
            contextMenuStrip.ShowItemToolTips = true;
            contextMenuStrip.TextDirection = ToolStripTextDirection.Horizontal;
            contextMenuStrip.Opening += new CancelEventHandler(contextMenuStrip_Opening);
            dataGridView.ContextMenuStrip = contextMenuStrip;
            dataGridView.CurrentCellChanged += new EventHandler(dataGridView_CurrentCellChanged);
        }
        ///


        /// 右键菜单委拖的Opening事件
        ///

        ///
        ///

        void contextMenuStrip_Opening(object sender, CancelEventArgs e)
        {
            //throw new NotImplementedException();
            ContextMenuStrip contextMenuStrip = sender as ContextMenuStrip;
            if (contextMenuStrip != null)
            {
                //判断是否有菜单项,如果没有就添加
                if (contextMenuStrip.Items.Count == 0)
                {
                    ToolStripMenuItem addMenuItem = new ToolStripMenuItem();
                    addMenuItem.Text = "添加";
                    //addMenuItem.ImageIndex = 0 //添加图片
                    //将菜单单击事件委托
                    addMenuItem.Click += new EventHandler(addMenuItem_Click);
                    ToolStripMenuItem deleteMenuItem = new ToolStripMenuItem();
                    deleteMenuItem.Text = "删除";
                    deleteMenuItem.Click += new EventHandler(deleteMenuItem_Click);
                    ToolStripMenuItem insertMenuItem = new ToolStripMenuItem();
                    insertMenuItem.Text = "插入";
                    insertMenuItem.Click += new EventHandler(insertMenuItem_Click);
                    contextMenuStrip.Items.Add(addMenuItem);
                    contextMenuStrip.Items.Add(deleteMenuItem);
                    contextMenuStrip.Items.Add(insertMenuItem);
                }
            }
        }
        ///


        /// 插入菜单的委拖事件
        ///

        ///
        ///
        void insertMenuItem_Click(object sender, EventArgs e)
        {
            //throw new NotImplementedException();
            //throw new NotImplementedException();
            ToolStripMenuItem toolStripMenuItem = sender as ToolStripMenuItem;
            ContextMenuStrip contextMenuStrip = toolStripMenuItem.Owner as ContextMenuStrip;
            if (contextMenuStrip != null)
            {
                //获取目标控件
                DataGridView dataGridView = contextMenuStrip.SourceControl as DataGridView;
                if (dataGridView.CurrentRow.Index > 0)
                {
                    //因为不能直接在dataGridView1上添加一个空行,所以给dt数据源添加一个空行然后重新绑定
                    DataRow dr = dt.NewRow ();
                    dt.Rows.InsertAt (dr,dataGridView.CurrentRow.Index );
                    dataGridView.DataSource = dt;
                }
            }
        }

        void deleteMenuItem_Click(object sender, EventArgs e)
        {
            //throw new NotImplementedException();
            ToolStripMenuItem toolStripMenuItem = sender as ToolStripMenuItem;
            ContextMenuStrip contextMenuStrip = toolStripMenuItem.Owner as ContextMenuStrip;
            if (contextMenuStrip != null)
            {
                //获取目标控件
                DataGridView dataGridView = contextMenuStrip.SourceControl as DataGridView;
                if (dataGridView.CurrentRow.Index > 0)
                {
                    dataGridView.Rows.RemoveAt(dataGridView.CurrentRow.Index);
                }
            }
        }
        ///


        /// 添加菜单的委拖事件
        ///

        ///
        ///
        void addMenuItem_Click(object sender, EventArgs e)
        {
            //throw new NotImplementedException();
            ToolStripMenuItem toolStripMenuItem = sender as ToolStripMenuItem;
            ContextMenuStrip contextMenuStrip = toolStripMenuItem.Owner as ContextMenuStrip;
            if (contextMenuStrip != null)
            {
                //获取目标控件
                DataGridView dataGridView = contextMenuStrip.SourceControl as DataGridView;
                //dataGridView.Rows.Add();
                //因为不能直接在dataGridView1上添加一个空行,所以给dt数据源添加一个空行然后重新绑定
                DataRow dr = dt.NewRow();
                dt.Rows.Add(dr);
                dataGridView.DataSource = dt;
            }
        }
        ///
        /// 删除菜单的委拖事件
        ///

        ///
        ///
        void dataGridView_CurrentCellChanged(object sender, EventArgs e)
        {
            //throw new NotImplementedException();
            if (this.dataGridView1.CurrentCell != null)
            {
                this.txtContent.Text = this.dataGridView1.CurrentCell.Value.ToString();
               
               
            }
        }
        ///
        /// 保存按钮的单击事件
        ///

        ///
        ///
        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                adapter.Update(dt);
                MessageBox.Show("更新成功!");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        ///
        /// 窗口控件加载事件
        ///

        ///
        ///
        private void DataGridViewDemo_Load(object sender, EventArgs e)
        {
            //初始化Adapter全局变量
            this.InitAdapter();
            //初始化dataGridView1控件
            this.InitDataGridView(dataGridView1);
            dt = new DataTable();
           
            try
            {
                //获取数据并填充到DataTable
                adapter.Fill(dt);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            //给dataGridView1控件绑定数据源
            this.dataGridView1.DataSource = dt;
        }
    }
}

你可能感兴趣的:(C#学习笔记)