vb.net,datagridview怎么用?怎么弄成下面的效果?修改和删除怎么弄?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了vb.net,datagridview怎么用?怎么弄成下面的效果?修改和删除怎么弄?相关的知识,希望对你有一定的参考价值。

Imports System
Imports System.Drawing
Imports System.Windows.Forms

Public Class Form1
    Inherits System.Windows.Forms.Form

    Private buttonPanel As New Panel
    Private WithEvents songsDataGridView As New DataGridView
    Private WithEvents addNewRowButton As New Button
    Private WithEvents deleteRowButton As New Button

    Private Sub Form1_Load(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles MyBase.Load

        SetupLayout()
        SetupDataGridView()
        PopulateDataGridView()

    End Sub

    Private Sub songsDataGridView_CellFormatting(ByVal sender As Object, _
        ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) _
        Handles songsDataGridView.CellFormatting

        If e IsNot Nothing Then

            If Me.songsDataGridView.Columns(e.ColumnIndex).Name = _
            "Release Date" Then
                If e.Value IsNot Nothing Then
                    Try
                        e.Value = DateTime.Parse(e.Value.ToString()) _
                            .ToLongDateString()
                        e.FormattingApplied = True
                    Catch ex As FormatException
                        Console.WriteLine("0 is not a valid date.", e.Value.ToString())
                    End Try
                End If
            End If

        End If

    End Sub

    Private Sub addNewRowButton_Click(ByVal sender As Object, _
        ByVal e As EventArgs) Handles addNewRowButton.Click

        Me.songsDataGridView.Rows.Add()

    End Sub

    Private Sub deleteRowButton_Click(ByVal sender As Object, _
        ByVal e As EventArgs) Handles deleteRowButton.Click

        If Me.songsDataGridView.SelectedRows.Count > 0 AndAlso _
            Not Me.songsDataGridView.SelectedRows(0).Index = _
            Me.songsDataGridView.Rows.Count - 1 Then

            Me.songsDataGridView.Rows.RemoveAt( _
                Me.songsDataGridView.SelectedRows(0).Index)

        End If

    End Sub

    Private Sub SetupLayout()

        Me.Size = New Size(600, 500)

        With addNewRowButton
            .Text = "Add Row"
            .Location = New Point(10, 10)
        End With

        With deleteRowButton
            .Text = "Delete Row"
            .Location = New Point(100, 10)
        End With

        With buttonPanel
            .Controls.Add(addNewRowButton)
            .Controls.Add(deleteRowButton)
            .Height = 50
            .Dock = DockStyle.Bottom
        End With

        Me.Controls.Add(Me.buttonPanel)

    End Sub

    Private Sub SetupDataGridView()

        Me.Controls.Add(songsDataGridView)

        songsDataGridView.ColumnCount = 5
        With songsDataGridView.ColumnHeadersDefaultCellStyle
            .BackColor = Color.Navy
            .ForeColor = Color.White
            .Font = New Font(songsDataGridView.Font, FontStyle.Bold)
        End With

        With songsDataGridView
            .Name = "songsDataGridView"
            .Location = New Point(8, 8)
            .Size = New Size(500, 250)
            .AutoSizeRowsMode = _
                DataGridViewAutoSizeRowsMode.DisplayedCellsExceptHeaders
            .ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.Single
            .CellBorderStyle = DataGridViewCellBorderStyle.Single
            .GridColor = Color.Black
            .RowHeadersVisible = False

            .Columns(0).Name = "Release Date"
            .Columns(1).Name = "Track"
            .Columns(2).Name = "Title"
            .Columns(3).Name = "Artist"
            .Columns(4).Name = "Album"
            .Columns(4).DefaultCellStyle.Font = _
                New Font(Me.songsDataGridView.DefaultCellStyle.Font, FontStyle.Italic)

            .SelectionMode = DataGridViewSelectionMode.FullRowSelect
            .MultiSelect = False
            .Dock = DockStyle.Fill
        End With

    End Sub

    Private Sub PopulateDataGridView()

        Dim row0 As String() = "11/22/1968", "29", "Revolution 9", _
            "Beatles", "The Beatles [White Album]"
        Dim row1 As String() = "1960", "6", "Fools Rush In", _
            "Frank Sinatra", "Nice 'N' Easy"
        Dim row2 As String() = "11/11/1971", "1", "One of These Days", _
            "Pink Floyd", "Meddle"
        Dim row3 As String() = "1988", "7", "Where Is My Mind?", _
            "Pixies", "Surfer Rosa"
        Dim row4 As String() = "5/1981", "9", "Can't Find My Mind", _
            "Cramps", "Psychedelic Jungle"
        Dim row5 As String() = "6/10/2003", "13", _
            "Scatterbrain. (As Dead As Leaves.)", _
            "Radiohead", "Hail to the Thief"
        Dim row6 As String() = "6/30/1992", "3", "Dress", "P J Harvey", "Dry"

        With Me.songsDataGridView.Rows
            .Add(row0)
            .Add(row1)
            .Add(row2)
            .Add(row3)
            .Add(row4)
            .Add(row5)
            .Add(row6)
        End With

        With Me.songsDataGridView
            .Columns(0).DisplayIndex = 3
            .Columns(1).DisplayIndex = 4
            .Columns(2).DisplayIndex = 0
            .Columns(3).DisplayIndex = 1
            .Columns(4).DisplayIndex = 2
        End With

    End Sub


    <STAThreadAttribute()> _
    Public Shared Sub Main()
        Application.EnableVisualStyles()
        Application.Run(New Form1())
    End Sub

End Class


送你段更全的,这个是官方的,可以参考着改成自己的东西

参考技术A 前台:(加·的地方就是修改和删除)
<asp:datagrid id="myDataGrid" runat="server"
OnPageIndexChanged="PageIndexChanged"
·OnCancelCommand="DataGrid_CancelCommand"
· OnEditCommand="DataGrid_EditCommand"
·OnDeleteCommand="DataGrid_DeleteCommand"
·OnUpdateCommand="DataGrid_UpdateCommand" BackColor="#99ffff"
PageSize="5" CellSpacing="1"
BorderStyle="Ridge" AutoGenerateColumns="False" CellPadding="3"
Width="800px" DataKeyField="sid"
HorizontalAlign="Center" BorderWidth="2px" BorderColor="#99ffff"
GridLines="None">
<SelectedItemStyle Font-Bold="True"
ForeColor="#F7F7F7" BackColor="#738A9C"></SelectedItemStyle>
<EditItemStyle
BackColor=#ccff33></EditItemStyle>
<AlternatingItemStyle
BackColor="#F7F7F7"></AlternatingItemStyle>
<ItemStyle HorizontalAlign="Center"
Font-Size="X-Small" ForeColor="#4A3C8C" BackColor="#E7E7FF"></ItemStyle>
<HeaderStyle Font-Size="Small"
Font-Bold="True" HorizontalAlign="Center" ForeColor="#F7F7F7"
BackColor="#4A3C8C"></HeaderStyle>
<FooterStyle ForeColor="#4A3C8C"
BackColor="#B5C7DE"></FooterStyle>
<Columns>
<asp:TemplateColumn HeaderText="学
号">
<ItemTemplate>

<%#Container.DataItem("sid")%>
</ItemTemplate>
<EditItemTemplate>

<%#Container.DataItem("sid")%>
</EditItemTemplate>
</asp:TemplateColumn>
<asp:BoundColumn DataField="sname"
HeaderText="姓名">
</asp:BoundColumn>
<asp:BoundColumn DataField="sex"
HeaderText="性别">
</asp:BoundColumn>
<asp:BoundColumn DataField="class"
HeaderText="班级">
</asp:BoundColumn>
<asp:BoundColumn DataField="age"
HeaderText="年龄">
</asp:BoundColumn>
<asp:TemplateColumn HeaderText="录入
时间">
<ItemTemplate>

<%#Container.DataItem("edttime")%>
</ItemTemplate>
<EditItemTemplate>

<%#Container.DataItem("edttime")%>
</EditItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="录入
人">
<ItemTemplate>

<%#Container.DataItem("edtperson")%>
</ItemTemplate>
<EditItemTemplate>

<%#Container.DataItem("edtperson")%>
</EditItemTemplate>
</asp:TemplateColumn>
· <asp:EditCommandColumn
·ButtonType="LinkButton" UpdateText="更新" HeaderText="操作" CancelText="取消"
·EditText="编辑">
· </asp:EditCommandColumn>
· <asp:ButtonColumn Text="删除"
·CommandName="Delete" HeaderText="功能">
· </asp:ButtonColumn>
</Columns>
<PagerStyle HorizontalAlign="Right"
ForeColor="#4A3C8C" BackColor="#E7E7FF" Mode="NumericPages" />
</asp:datagrid>

后台:
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If Not IsPostBack Then
BindList()
End If
End Sub
Sub BindList()
CreateDataSet("Select * from Students", "Students")
myDataGrid.DataSource = ds.Tables("Students")
myDataGrid.DataBind()
End Sub
Dim ConnString As String
Dim ds As New DataSet
Dim SqlCmd As SqlDataAdapter
Sub CreateDataSet(ByVal strSql As String, ByVal TableName As String)
ConnString = "Persist Security Info=true;Initial Catalog=Data;uid=sa;pwd=123456;Data Source=.;"
SqlCmd = New SqlDataAdapter(strSql, ConnString)
SqlCmd.Fill(ds, TableName)
End Sub
Sub DataGrid_DeleteCommand(ByVal sender As Object, ByVal e As DataGridCommandEventArgs)
Dim SqlConn As New SqlConnection
SqlConn.ConnectionString = "Persist Security Info=true;Initial Catalog=Data;Data Source=.;uid=sa;pwd=123456; "
SqlConn.Open()
Dim SqlCmd As New SqlCommand
SqlCmd.Connection = SqlConn
SqlCmd.CommandText = "delete from students where sid='" & myDataGrid.DataKeys(e.Item.ItemIndex) & "'"
SqlCmd.ExecuteNonQuery()
BindList()
End Sub
'此过程用来进入数据编辑模式
Sub DataGrid_EditCommand(ByVal sender As Object, ByVal e As DataGridCommandEventArgs)
myDataGrid.EditItemIndex = e.Item.ItemIndex
BindList()
End Sub
'此过程用来离开数据编辑模式
Sub DataGrid_CancelCommand(ByVal sender As Object, ByVal e As DataGridCommandEventArgs)
myDataGrid.EditItemIndex = -1
BindList()
End Sub
'此过程用来更新数据
Sub DataGrid_UpdateCommand(ByVal sender As Object, ByVal e As DataGridCommandEventArgs)
Dim Name As String = CType(e.Item.Cells(1).Controls(0), TextBox).Text
Dim Sex As String = CType(e.Item.Cells(2).Controls(0), TextBox).Text
Dim Sclass As String = CType(e.Item.Cells(3).Controls(0), TextBox).Text
Dim Age As Integer = CType(e.Item.Cells(4).Controls(0), TextBox).Text
Dim strSql As String = "update students set sname='" & Name & "',sex='" & Sex & "',class='" & Sclass & "',age=" & Age & " where " & myDataGrid.DataKeyField & "='" & myDataGrid.DataKeys(e.Item.ItemIndex) & "'"
Dim SqlConn As New SqlConnection
SqlConn.ConnectionString = "Persist Security Info=true;Initial Catalog=Data;Data Source=.;uid=sa;pwd=123456; "
SqlConn.Open()
Dim SqlCmd As New SqlCommand(strSql, SqlConn)
SqlCmd.ExecuteNonQuery()
myDataGrid.EditItemIndex = -1
BindList()
End Sub

关于VB.NET中 datagridview 刷新问题

参考技术A 把连接数据库和显示数据的过程写成在一个方法里(如showdata),在点击录入按钮时,先写你的录入代码,写完后在调用一下showdata()

以上是关于vb.net,datagridview怎么用?怎么弄成下面的效果?修改和删除怎么弄?的主要内容,如果未能解决你的问题,请参考以下文章

vb.net Datagridview添加行

关于VB.NET中 datagridview 刷新问题

vb.net中,怎么删除DataGridView控件中选定一行记录,并把数据库里的对应记录也删除掉,求解代码

vb.net 如何让datagridview添加图片列

VB.NET中DataGridView谁帮忙?

vb.net datagridview 无法添加行