private void InitDataGridView() { // Create an unbound DataGridView by declaring a column count. dataGridView1.ColumnCount = 3; dataGridView1.ColumnHeadersVisible = true; dataGridView1.AllowUserToAddRows = false; dataGridView1.AllowUserToDeleteRows = false; dataGridView1.AllowUserToOrderColumns = false; dataGridView1.MultiSelect = false; dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect; dataGridView1.ReadOnly = true; // Set the column header style. DataGridViewCellStyle columnHeaderStyle = new DataGridViewCellStyle(); columnHeaderStyle.BackColor = Color.Beige; columnHeaderStyle.Font = new Font("Verdana", 10, FontStyle.Regular); dataGridView1.ColumnHeadersDefaultCellStyle = columnHeaderStyle; // Set the column header names. dataGridView1.Columns[0].Name = "C1"; dataGridView1.Columns[1].Name = "C2"; dataGridView1.Columns[2].Name = "C3"; } private void AddDataGridViewData() { for (int i = 0; i < 3; i++) { int index = this.dataGridView1.Rows.Add(); this.dataGridView1.Rows[index].Cells[0].Value = i.ToString() + "1"; this.dataGridView1.Rows[index].Cells[1].Value = i.ToString() + "2"; this.dataGridView1.Rows[index].Cells[2].Value = i.ToString() + "3"; } } private string GetSelectedValue() { int index= dataGridView1.CurrentRow.Index; return dataGridView1.Rows[index].Cells["C2"].Value.ToString(); } //右键显示菜单 private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e) { if (e.Button == MouseButtons.Right) { if (e.RowIndex >= 0) { //若行已是选中状态就不再进行设置 if (dataGridView1.Rows[e.RowIndex].Selected == false) { dataGridView1.ClearSelection(); dataGridView1.Rows[e.RowIndex].Selected = true; } //只选中一行时设置活动单元格 if (dataGridView1.SelectedRows.Count == 1) { dataGridView1.CurrentCell = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex]; } //弹出操作菜单 contextMenuStrip1.Show(MousePosition.X, MousePosition.Y); } } }
//清除DataGridView数据 private void DataGridViewClear() { for (int i = 0; i < dataGridView1.RowCount; i++) { dataGridView1.Rows.Remove(dataGridView1.Rows[i]); i--; } }