我有網格,一種列型別是按鈕列。我希望當用戶點擊按鈕時選單應該顯示在按鈕下方,但我無法實作這一點。dgList是 datagridview 的名稱。如果沒有空間顯示選單,則選單位置將動態調整。
這是我嘗試過的代碼
private void Form1_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Salary", typeof(int));
DataRow dr = null;
dr = dt.NewRow();
dr[0] = 1;
dr[1] = "Joydip";
dr[2] = 5200;
dt.Rows.Add(dr);
dr = dt.NewRow();
dr[0] = 2;
dr[1] = "Salim";
dr[2] = 3200;
dt.Rows.Add(dr);
dr = dt.NewRow();
dr[0] = 3;
dr[1] = "Sukumar";
dr[2] = 6000;
dt.Rows.Add(dr);
dgList.AutoGenerateColumns = false;
dgList.DataSource = dt;
dgList.Columns[0].DataPropertyName = "ID";
dgList.Columns[1].DataPropertyName = "Name";
dgList.Columns[2].DataPropertyName = "Salary";
}
private void dgList_MouseClick(object sender, MouseEventArgs e)
{
int currentMouseOverRow = dgList.HitTest(e.X, e.Y).RowIndex;
if (currentMouseOverRow >= 0)
contextMenuStrip1.Show(dgList, new Point(e.X, e.Y));
}
我也試過這段代碼,但沒有運氣。
private void dgList_MouseClick(object sender, MouseEventArgs e)
{
DataGridViewCell currentCell = (sender as DataGridView).CurrentCell;
if (currentCell != null)
{
ContextMenuStrip cms = currentCell.ContextMenuStrip;
Rectangle r = currentCell.DataGridView.GetCellDisplayRectangle(currentCell.ColumnIndex, currentCell.RowIndex, false);
Point p = new Point(r.X r.Width, r.Y r.Height);
contextMenuStrip1.Show(currentCell.DataGridView, p);
}
}
請指導我在我的代碼中有什么錯誤。如何實作我正在尋找的東西。
謝謝
uj5u.com熱心網友回復:
問題已修復。這里是作業代碼
private void dgList_MouseClick(object sender, MouseEventArgs e)
{
DataGridViewCell currentCell = (sender as DataGridView).CurrentCell;
if (currentCell != null && currentCell.ColumnIndex==3)
{
ContextMenuStrip cms = currentCell.ContextMenuStrip;
Rectangle r = currentCell.DataGridView.GetCellDisplayRectangle(currentCell.ColumnIndex, currentCell.RowIndex, false);
Point p = new Point(r.X, r.Y r.Height);
contextMenuStrip1.Show(currentCell.DataGridView, p);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/339212.html
