日期:2014-05-18  浏览次数:20904 次

怎么在DataGridView实现删除功能
想点DataGridView中显示的一行,然后点删除按钮实现删除
求代码

------解决方案--------------------
Private Sub Del_Data()
Dim i As Integer = DataGridView1.Rows.Count
For i = 0 To DataGridView1.Rows.Count - 1
If DataGridView1.Rows(i).Selected Then
Del_Record_DataBase(DataGridView1.Rows(i).Cells(0).Value)
i = DataGridView1.Rows.Count + 1
End If
Next
End Sub
Private Sub Del_Record_DataBase(ByVal id As String)
Dim Conn As OleDbConnection = New OleDbConnection(strCon)
plConn.Open()
Dim strDele As String = "DELETE FROM file WHERE xh= " + id.Trim() + ""
Dim Command As OleDbCommand = New OleDbCommand(strDele, Conn)

Command.ExecuteNonQuery()
Conn.Close()


End Sub
------解决方案--------------------
C# code

  private void button1_Click(object sender, EventArgs e)
        {
            DataRowView rowView = this.dataGridView1.CurrentRow.DataBoundItem as DataRowView;
            if (rowView != null)
            {
                DataRow currentRow = rowView.Row;

                //获取主键
                string id = currentRow["ID"];
                //调用数据库里的删除方法:
                string sql = "DELETE FROM TABLE_NAME WHERE ID='" + id + "'";
                //数据库操作
            }
        }

------解决方案--------------------
C# code
if (dataGridViewX1.Rows.Count > 0)
                {
                    if (dataGridViewX1.CurrentRow != null)
                    {
                        if (dataGridViewX1.SelectedRows.Count == 0)
                        {
                            dataGridViewX1.Rows.Remove(dataGridViewX1.CurrentRow);
                            dt.AcceptChanges();//绑定datagridview的表
                        }
                        else
                        {
                            try
                            {
                                for (int i = dataGridViewX1.SelectedRows.Count; i > 0; i--)
                                {
                                    dataGridViewX1.Rows.RemoveAt(dataGridViewX1.SelectedRows[i - 1].Index);
                                    
                                }
                                dt.AcceptChanges();//绑定datagridview的表
                            }
                            catch (Exception)
                            {

                                MessageBox.Show("无法删除空行!", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                            }
                        }
                    }
                    else
                    {
                        MessageBox.Show("请选择删除的行!","提示信息", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    }


                }
                else
                {
                    MessageBox.Show("没有可删除数据!", "提示信息",MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                }