最近一直在弄DatagridView,前一篇文章弄了一复选框删除,但是后来想想,如果我每就删除一行,那么我每次删除的时候都得先选中,然后再区单机删除,太麻烦了,于是就想起来弄一个右键删除,然后又加了一个右键变色,反正就是一个右键菜单,下边吧代码给大家,很简单的代码,确是非常的实用。
/// <summary> /// 添加一个表格 /// </summary> public void addDatatable() { DataColumn dc = new DataColumn("ID"); dt.Columns.Add(dc); dc = new DataColumn("name"); dt.Columns.Add(dc); dc = new DataColumn("age"); dt.Columns.Add(dc); dc = new DataColumn("sex"); dt.Columns.Add(dc); //为datatable赋值 for (int i = 0; i < 6; i++) { DataRow row = dt.NewRow(); row["ID"] = i; row["name"] = "menghaibin"; row["age"] = i + 10; row["sex"] = "男"; dt.Rows.Add(row); } } /// <summary> /// 获取当前选中单元的坐标 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void dataGridView1_CellMouseEnter(object sender, DataGridViewCellEventArgs e) { var dgv = (DataGridView)sender; CurrentRow = e.RowIndex; CurrentColumn = e.ColumnIndex; } /// <summary> /// 单击右键菜单中的变色按钮 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void 修改ToolStripMenuItem_Click(object sender, EventArgs e) { if (CurrentRow > -1 && CurrentColumn > -1) { if (dataGridView1.Rows[CurrentRow].Cells[CurrentColumn].Selected) { DataGridViewCell aa = dataGridView1.Rows[CurrentRow].Cells[CurrentColumn]; aa.Style.ForeColor = Color.Red; aa.Style.BackColor = Color.Pink; this.dataGridView1.Rows[CurrentRow].DefaultCellStyle.ForeColor = Color.Blue; this.dataGridView1.Columns[CurrentColumn].DefaultCellStyle.BackColor = Color.Brown; //aa.Style.Font = Font.Underline; } } else { MessageBox.Show(this,"请选择数据表中的内容","提示信息",MessageBoxButtons.OKCancel,MessageBoxIcon.Information); return; } } /// <summary> /// 单击右键菜单中的删除按钮 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void 删除ToolStripMenuItem_Click(object sender, EventArgs e) { //获得当前行 DataGridViewRow row = dataGridView1.Rows[CurrentRow]; //删除行 dataGridView1.Rows.Remove(row); dataGridView1.CurrentCell = dataGridView1[0, CurrentRow]; }<pre name="code" class="csharp"> DataTable dt = new DataTable(); //定义变量存储选中行数 private int CurrentRow { get; set; } private int CurrentColumn { get; set; } private void Form1_Load(object sender, EventArgs e) { addDatatable(); dataGridView1.DataSource = dt; }
不难,就是几行的嗲吗,但是却让我们的代码非常的人性化,说是话,做出这个的时候,感觉比那一堆实现功能的代码带来的喜悦都大。
时间: 2024-12-29 07:10:10