且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从Vb .Net中的Datagridview中删除选定的行

更新时间:2022-10-23 10:51:01

 私人  Sub  Button1_Click( ByVal  sender  As 系统。对象 ByVal  e  As  System.EventArgs)句柄 Button1.Click 
如果 .DataGridView1.SelectedRows.Count> 0 然后
GetValueByQuery( delete * from table1 where id =& Me .DataGridView1.SelectedRows( 0 )。单元格( 0 )。值)
结束 如果
结束 Sub


实际上,getValuebyQuery是我自己的函数,我将它放在这里,以便您可以使用它。在此功能中,您可以根据需要使用select / insert / update / delete查询..



< pre lang =   vb> 公共 oCon 作为  System.Data。 OleDb.OleDbConnection(  provider = microsoft.jet.OLEDB.4.0; data source =& Application .StartupPath&   \ Data\mydata.mdb

函数 GetValueByQuery( ByVal 查询作为 String ) As String
Dim temp As String
Dim ocom As OleDbCommand
Dim n> oRead As OleDbDataReader
如果 oCon.State = ConnectionState.Closed 然后
oCon.Open()
结束 如果

ocom.Connection = oCon
ocom.CommandText = Query

oRead = ocom.ExecuteReader
如果 oRead.HasRows = True 那么
oRead.Read()
如果 IsDBNull(oRead( 0 ))= 然后
temp =& quot; 0& quot;
其他
temp = oRead( 0
结束 如果
oRead.Close()

Else
temp =& quot; 0& quot;
oRead.Close()
结束 如果
返回 temp
结束 功能 < / pre >


Hai guys, I created a form to insert, update, delete.
And i am using datagridview control to view the database updation.
Here what i actually need is,
If i click a row from datagridview and click delete it should delete.
i need code for this
Help me,

Regards Sissy Ram

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If Me.DataGridView1.SelectedRows.Count > 0 Then
            GetValueByQuery("delete * from table1 where id=" & Me.DataGridView1.SelectedRows(0).Cells(0).Value)
        End If
    End Sub


Ohh actually getValuebyQuery is my own function I am enclosing here with so that you can use it. In this function you can use select/insert/update/delete query as you required..

<pre lang="vb">   Public oCon As New System.Data.OleDb.OleDbConnection("provider=microsoft.jet.OLEDB.4.0;data source=" & Application.StartupPath & "\Data\mydata.mdb")

Function GetValueByQuery(ByVal Query As String) As String
        Dim temp As String
        Dim ocom As New OleDbCommand
        Dim oRead As OleDbDataReader
        If oCon.State = ConnectionState.Closed Then
            oCon.Open()
        End If

        ocom.Connection = oCon
        ocom.CommandText = Query

        oRead = ocom.ExecuteReader
        If oRead.HasRows = True Then
            oRead.Read()
            If IsDBNull(oRead(0)) = True Then
                temp = &quot;0&quot;
            Else
                temp = oRead(0)
            End If
            oRead.Close()

        Else
            temp = &quot;0&quot;
            oRead.Close()
        End If
        Return temp
    End Function</pre>