在实际项目中,有时需要将数据表中的数据删除,因此需要使用DataGridView控件中删除行的功能。
控件:
ContextMenuStrip.
方法:
指定的屏幕位置定位
public void Show(Point screenLocation);
指定的控件位置定位
public void Show(Control control, Point position);
控件:
DataGridView.
方法:
从集合中移除指定位置处的行。
public virtual void RemoveAt(int index);
- 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 Test_DataGridView
- {
- public partial class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
- }
-
- //全局变量
- int rowIndex;
-
-
- private void Form1_Load(object sender, EventArgs e)
- {
- dataGridView1.DataSource = Source();
- }
-
- //数据表资源
- private DataTable Source()
- {
- DataTable mydt = new DataTable();
- mydt.Columns.Add("姓名");
- mydt.Columns.Add("年龄");
- mydt.Columns.Add("分数");
- String[,] str = new String[,] { { "张三", "21", "90" }, { "李四", "22", "93" }, { "王五", "23", "99" } };
-
- for (int i = 0; i < 3; i++)
- {
- DataRow dr = mydt.NewRow();
- dr[0] = str[i, 0];
- dr[1] = str[i, 1];
- dr[2] = str[i, 2];
- mydt.Rows.Add(dr);
- }
- return mydt;
-
- }
-
- //获取单元格信息
- private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
- {
- //获取单元格坐标
- int col = dataGridView1.CurrentCellAddress.X + 1;
- int row = dataGridView1.CurrentCellAddress.Y + 1;
-
- //获取单元格内容
- String content = dataGridView1.CurrentCell.Value.ToString();
-
- MessageBox.Show("行:" + row.ToString() + " 列:" + col.ToString() + " 内容:" + content);
-
- }
-
- //隐藏年龄
- private void button1_Click(object sender, EventArgs e)
- {
- String bts = button1.Text;
- if (bts == "隐藏年龄")
- {
- dataGridView1.Columns[1].Visible = false;
- bts = "显示年龄";
- button1.Text = bts;
- }
- else
- {
- dataGridView1.Columns[1].Visible = true;
- bts = "隐藏年龄";
- button1.Text = bts;
- }
-
- }
-
- //右键点击事件
- private void dataGridView1_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e)
- {
- if (e.Button == MouseButtons.Right)
- {
- this.dataGridView1.Rows[e.RowIndex].Selected = true;
- this.dataGridView1.CurrentCell = this.dataGridView1.Rows[e.RowIndex].Cells[0];
- this.contextMenuStrip1.Show(this.dataGridView1, e.Location);
- contextMenuStrip1.Show(Cursor.Position);
- rowIndex = e.RowIndex;
-
- }
-
- }
-
- //删除行事件的内容
- private void 删除行ToolStripMenuItem_Click(object sender, EventArgs e)
- {
- if (!this.dataGridView1.Rows[this.rowIndex].IsNewRow)
- {
- this.dataGridView1.Rows.RemoveAt(rowIndex);
- }
-
- }
-
-
- }
- }