2010年4月10日

[C#] - GridView使用ContextMenu

GridView要加上右鍵選單,如下圖結果所示











第一步:宣告ContextMenu選單需要的物件
private ContextMenuStrip contextMenu;//宣告一個右鍵選單的物件
private ToolStripMenuItem toolstrip = new ToolStripMenuItem();//宣告一個選單item物件

第二步:使用Gridview的RowContextMenuStripNeeded事件

private void DataShow_RowContextMenuStripNeeded(object sender, DataGridViewRowContextMenuStripNeededEventArgs e)
        {
            if (contextMenu == null)
            {
                contextMenu = new ContextMenuStrip();
                toolstrip.Text = "刪除";
                contextMenu.Items.Add(toolstrip);
            }
            e.ContextMenuStrip = contextMenu;
            seqno = int.Parse(DataShow["seqno", e.RowIndex].Value.ToString());//取得table上的seqno
            DataShow.Rows[e.RowIndex].Selected = true;//選擇該列(使它整列變藍色選取樣子)
        }

第三步:設定toolstrip的Click事件(將事件的宣告放在MainForm()裡)

public MainForm()
        {
            InitializeComponent();
            toolstrip.Click += new EventHandler(toolstrip_Click);
        }

第四步:撰寫toolstrip的click事件內容

private void toolstrip_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("確定要刪除該筆資料?", "警告!!", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                     //如果按下yes就會執行刪除指令,這邊就看個人發揮囉!!
            }
        }

資料來源:
http://msdn.microsoft.com/zh-tw/library/system.windows.forms.datagridview.cellcontextmenustripneeded%28VS.80%29.aspx

沒有留言:

張貼留言