C#datagridview右键单击选择行和显示菜单以调用表单以编辑所选行

时间:2012-02-13 15:33:29

标签: sql-server winforms datagrid edit right-click

我搜索每个地方,但我找不到解决问题的方法 我只是想知道如何在数据网格视图中创建一个右键菜单来编辑SQL中的数据

这是我的代码,用于创建右键单击的上下文菜单,但我无法调用表单从行中获取数据,我右键单击它并编辑数据。

public void Rightclick()
   {
       ContextMenu Rmnu = new ContextMenu();
       MenuItem mnuCCS = new MenuItem("Change Class Size");
       MenuItem mnuDeactv = new MenuItem("Deactivate");

       mnuCCS.Click += new EventHandler(radGridView_Class_View_Click);
       mnuDeactv.Click += new EventHandler(radGridView_Class_View_Click);

       Rmnu.MenuItems.AddRange(new MenuItem[] { mnuCCS, mnuDeactv });
       radGridView_Class_View.ContextMenu = Rmnu;



   }
   private void radGridView_Class_View_Click(object sender, EventArgs e)
   {
       Rightclick();
   }

我想创建一个用于编辑的表单...从datagrid获取数据并使用右键菜单编辑... ...

有人可以帮助我......谢谢......

1 个答案:

答案 0 :(得分:3)

我想,你应该看看这个MSDN-article。它显示了如何使用ContextMenuStrip解决问题。

以下示例:

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;

namespace test1
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        // Test-Data
        dataGridView1.DataSource = GetTestData();

        // Add menu
        AddContextMenu(dataGridView1);

        // remember mouse location
        AddMouseEnterEvent();
    }

    private DataTable GetTestData()
    {
        DataTable tab = new DataTable();
        DataColumn c1 = new DataColumn("col1");
        DataColumn c2 = new DataColumn("col2");
        tab.Columns.AddRange(new DataColumn[] { c1, c2 });
        DataRow r1 = tab.NewRow(); r1[c1] = "cell 1"; r1[c2] = "cell 2";
        DataRow r2 = tab.NewRow(); r2[c1] = "cell 3"; r2[c2] = "cell 4";
        tab.Rows.Add(r1);
        tab.Rows.Add(r2);

        return tab;
    }

    private void AddContextMenu(DataGridView dgv)
    {
        var strip = new ContextMenuStrip();
        var menu1 = strip.Items.Add("Change Class Size");
        var menu2 = strip.Items.Add("Deactivate");

        menu1.Click += new EventHandler(menu1_Click);
        menu2.Click += new EventHandler(menu2_Click);
        foreach (DataGridViewColumn column in dgv.Columns)
        {
            column.ContextMenuStrip = strip;
        }
    }

    DataGridViewCellEventArgs mouseLocation;
    void AddMouseEnterEvent()
    {
        dataGridView1.CellMouseEnter += (s,e) => { mouseLocation = e; };
    }

    void menu2_Click(object sender, EventArgs e)
    {
        var cell = dataGridView1.Rows[mouseLocation.RowIndex].Cells[mouseLocation.ColumnIndex];
        // do something stupid
        cell.Style.BackColor = Color.Red;
    }

    void menu1_Click(object sender, EventArgs e)
    {
        var cell = dataGridView1.Rows[mouseLocation.RowIndex].Cells[mouseLocation.ColumnIndex];
        // do something even more stupid
        cell.Style.BackColor = Color.Blue;
    }
}
}