一个信息管理系统(MIS)的小例子(C#.NET+MS SQL2K)

本文介绍了如何使用C#.NET和MS SQL 2000创建一个简单信息管理系统,包括创建数据表、浏览并存储图片、数据库连接、以及增删查改操作的代码实现。示例提供了Windows Form应用中处理图片管理和数据交互的详细步骤。
前一段时间写了个编写XML的小东西,当时没怎么整理,也没涉及到图片的处理。

今天这个是可以存储和管理的例子,增加了图片管理的这一功能

测试环境:Windows XP Pro +VS.NET 2003+ MS SQL 2000 (均为英文版)

PS:学习中,望不吝赐教!

偶就简单的介绍下代码
1,包含的命名空间

Option Strict On
Imports System.IO
Imports System.Data.SqlClient
Imports System.Text
2,一些共有变量的声明:

Protected Const SQL_CONNECTION_STRING As String = _
        "Server=localhost;" & _
        "DataBase=Northwind;" & _
        "Integrated Security=SSPI"

    Protected Const CONNECTION_ERROR_MSG As String = _
        "You must have SQL with the Northwind database installed.  "

    Protected da As SqlDataAdapter
    Protected cbd As SqlCommandBuilder
    Protected dsPictures As DataSet
    Protected didPreviouslyConnect As Boolean = False
    Protected connectionString As String = SQL_CONNECTION_STRING
3,略去Windows Form Designer Generate Code这个部分,可参见偶贴图
4,创建数据表的代码

Private Sub btnCreate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCreate.Click
        Dim strSQL As String = _
            "IF EXISTS (" & _
            "SELECT * " & _
            "FROM northwind.dbo.sysobjects " & _
            "WHERE NAME = 'Picture' " & _
            "AND TYPE = 'u')" & vbCrLf & _
            "BEGIN" & vbCrLf & _
            "DROP TABLE northwind.dbo.picture" & vbCrLf & _
            "END" & vbCrLf & _
            "CREATE TABLE Picture (" & _
            "PictureID Int IDENTITY(1,1) NOT NULL," & _
            "[FileName] Varchar(255) NOT NULL," & _
            "Picture Image NOT NULL," & _
            "Name nvarchar(20) NOT NULL," & _
            "UID Varchar(20) NOT NULL," & _
            "UG nvarchar(10) NOT NULL," & _
            "Gender nvarchar(10) NOT NULL," & _
            "Score nvarchar(50) NOT NULL," & _
            "SelfIntr Varchar(255) NOT NULL," & _
            "CONSTRAINT [PK_Picture] PRIMARY KEY CLUSTERED" & _
            "(PictureID))"
        Dim frmMessage As New status
        If Not didPreviouslyConnect Then
            frmMessage.Show("Connecting to SQL Server")
        End If
        Dim isConnecting As Boolean = True
        While isConnecting
            Try
                ' communicate with SQL Server
                Dim northwindConnection As New SqlConnection(connectionString)
                ' A SqlCommand object is used to execute the SQL commands.
                Dim cmd As New SqlCommand(strSQL, northwindConnection)
                ' Open ,execute the command, and close the connection.
                northwindConnection.Open()
                cmd.ExecuteNonQuery()
                northwindConnection.Close()
                ' Data has been successfully submitted
                isConnecting = False
                didPreviouslyConnect = True
                frmMessage.Close()
                MessageBox.Show("Table successfully created.", "Table Creation Status", _
                    MessageBoxButtons.OK, MessageBoxIcon.Information)
            Catch sqlExc As SqlException
                MessageBox.Show(sqlExc.ToString, "SQL Exception Error!", _
                    MessageBoxButtons.OK, MessageBoxIcon.Error)
                Exit While
            Catch exc As Exception
                ' Unable to connect to SQL Server
                frmMessage.Close()
                MessageBox.Show(CONNECTION_ERROR_MSG, _
                        "Connection Failed!", MessageBoxButtons.OK, _
                        MessageBoxIcon.Error)
                End
            End Try
        End While
        frmMessage.Close()
    End Sub
这里为了节省版面就删了一些格式的东西
5,浏览文件,按钮的代码,这里用到openfiledialog

Private Sub btnBrowse_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBrowse.Click
        With OpenFileDialog1
            .InitialDirectory = "C:/"
            .Filter = "All Files|*.*|Bitmap|*.bmp|GIF|*.gif|JPEG|*.jpg"
            .FilterIndex = 4
        End With

        If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
            With picImage
                .Image = Image.FromFile(OpenFileDialog1.FileName)
                .SizeMode = PictureBoxSizeMode.CenterImage
                .BorderStyle = BorderStyle.Fixed3D
            End With
            lblFilePath.Text = OpenFileDialog1.FileName
        End If
    End Sub
6,存储数据的按钮事件

Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
        If picImage.Image Is Nothing Then
            MessageBox.Show("No Image is loaded", "Erro")
        End If

        Dim arrFilename() As String = Split(lblFilePath.Text, "/")
        arrFilename.Reverse(arrFilename)   /让数组中的数据反过来

        Dim ms As New MemoryStream
        picImage.Image.Save(ms, picImage.Image.RawFormat)
        Dim arrImage() As Byte = ms.GetBuffer

        ms.Close()


        Dim frmMessage As New status
        If Not didPreviouslyConnect Then
            frmMessage.Show("Connecting to SQL Server")
        End If
        ' connect to the SQL server
        Dim isConnecting As Boolean = True
        While isConnecting
            Try
                'communicate with SQL Server and uses Integrated Security
                Dim northwindConnection As New SqlConnection(connectionString)
                Dim strSQL As String = _
                    "INSERT INTO Picture (Filename, Picture, Name, UID, UG, Gender, Score, SelfIntr)" & _
                    "VALUES (@Filename, @Picture, @Name, @UID, @UG, @Gender, @Score, @SelfIntr)"

                'execute SQL statement.
                Dim cmd As New SqlCommand(strSQL, northwindConnection)
                With cmd
                    .Parameters.Add(New SqlParameter("@Filename", _
                        SqlDbType.NVarChar, 50)).Value = arrFilename(0)
                    .Parameters.Add(New SqlParameter("@Picture", _
                        SqlDbType.Image)).Value = arrImage
                    .Parameters.Add(New SqlParameter("@Name", _
                        SqlDbType.NVarChar)).Value = txtName.Text
                    .Parameters.Add(New SqlParameter("@UID", _
                        SqlDbType.NVarChar)).Value = txtUID.Text
                    .Parameters.Add(New SqlParameter("@UG", _
                        SqlDbType.NVarChar)).Value = cmbUG.Text
                    .Parameters.Add(New SqlParameter("@Gender", _
                        SqlDbType.NVarChar)).Value = cmbGender.Text
                    .Parameters.Add(New SqlParameter("@Score", _
                        SqlDbType.NVarChar)).Value = txtScore.Text
                    .Parameters.Add(New SqlParameter("@SelfIntr", _
                       SqlDbType.VarChar)).Value = txtSelf.Text
                End With

                ' Open, execute, and close connection.
                northwindConnection.Open()
                cmd.ExecuteNonQuery()
                northwindConnection.Close()

                isConnecting = False
                didPreviouslyConnect = True
                frmMessage.Close()
                MessageBox.Show(arrFilename(0) & " has been stored to the database.", _
                    "Save Image", MessageBoxButtons.OK, _
                    MessageBoxIcon.Information)

            Catch sqlExc As SqlException
                MessageBox.Show(sqlExc.ToString, "SQL Exception Error!", _
                    MessageBoxButtons.OK, MessageBoxIcon.Error)
                Exit While
            Catch exc As Exception

                ' Unable to connect to SQL Server
                frmMessage.Close()
                MessageBox.Show(CONNECTION_ERROR_MSG, _
                        "Connection Failed!", MessageBoxButtons.OK, _
                        MessageBoxIcon.Error)
                End

            End Try
        End While
    End Sub
7,显示信息按钮事件,读取数据

Private Sub btnDisplay_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisplay.Click
        If lstPictures.SelectedIndex < 0 Then
            MessageBox.Show("There are no images in the database to display.", _
                "Empty Database!", MessageBoxButtons.OK, MessageBoxIcon.Information)
        Else
            ' first create a stream object containing the binary data. Then generate the image by calling Image.FromStream().
            Dim arrPicture() As Byte = _
             CType(dsPictures.Tables(0).Rows(lstPictures.SelectedIndex)("Picture"), _
             Byte())
            Dim ms As New MemoryStream(arrPicture)

            With PictureBox2
                .Image = Image.FromStream(ms)
                .SizeMode = PictureBoxSizeMode.CenterImage
                .BorderStyle = BorderStyle.Fixed3D
            End With

            lblFileName.Text = _
             dsPictures.Tables(0).Rows(lstPictures.SelectedIndex)("FileName").ToString
            TextBox4.Text = _
             dsPictures.Tables(0).Rows(lstPictures.SelectedIndex)("Name").ToString
            TextBox3.Text = _
            dsPictures.Tables(0).Rows(lstPictures.SelectedIndex)("UID").ToString
            TextBox5.Text = _
            dsPictures.Tables(0).Rows(lstPictures.SelectedIndex)("UG").ToString
            TextBox6.Text = _
            dsPictures.Tables(0).Rows(lstPictures.SelectedIndex)("Gender").ToString
            TextBox2.Text = _
            dsPictures.Tables(0).Rows(lstPictures.SelectedIndex)("Score").ToString
            TextBox1.Text = _
            dsPictures.Tables(0).Rows(lstPictures.SelectedIndex)("SelfIntr").ToString
            ' Close the stream object
            ms.Close()
        End If
    End Sub
8,删除按钮的事件

Private Sub btnDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelete.Click
        ' When nothing is selected in the ListBox, the SelectedIndex = -1.
        If lstPictures.SelectedIndex < 0 Then
            MessageBox.Show("There are no images in the database to delete.", _
                "Empty Database!", MessageBoxButtons.OK, MessageBoxIcon.Information)
        Else
            dsPictures.Tables(0).Rows(lstPictures.SelectedIndex).Delete()
            da.UpdateCommand = cbd.GetDeleteCommand
            da.Update(dsPictures)

            lblFileName.Text = ""
            PictureBox2.Image = Nothing
        End If
    End Sub
9,控制单转换时自动加载

Private Sub TabControl1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TabControl1.SelectedIndexChanged

        If TabControl1.SelectedIndex = 2 Then
            Dim frmStatusMessage As New status
            If Not didPreviouslyConnect Then
                frmStatusMessage.Show("Connecting to SQL Server")
            End If
            Dim isConnecting As Boolean = True
            While isConnecting

                Try
                    Dim northwindConnection As New SqlConnection(connectionString)
                    Dim cmd As New SqlCommand("SELECT * " & _
                                              "FROM Picture", _
                                              northwindConnection)

                    da = New SqlDataAdapter(cmd)
                    cbd = New SqlCommandBuilder(da)
                    dsPictures = New DataSet
                    da.Fill(dsPictures)

                    isConnecting = False
                    didPreviouslyConnect = True
                    frmStatusMessage.Close()

                    With lstPictures
                        .DataSource = dsPictures.Tables(0)
                        .DisplayMember = "FileName"
                    End With



                Catch sqlExc As SqlException
                    MessageBox.Show(sqlExc.ToString, "SQL Exception Error!", _
                        MessageBoxButtons.OK, MessageBoxIcon.Error)
                    Exit While
                Catch exc As Exception
                    frmStatusMessage.Close()
                    MessageBox.Show(CONNECTION_ERROR_MSG, _
                            "Connection Failed!", MessageBoxButtons.OK, _
                            MessageBoxIcon.Error)

                End Try
            End While
        End If
    End Sub
另外,心定一类,为测试安装的SQL服务器
代码

Public Class status
    Inherits System.Windows.Forms.Form

#Region " Windows Form Designer generated code "

    Public Sub New()
        MyBase.New()

        'This call is required by the Windows Form Designer.
        InitializeComponent()

        'Add any initialization after the InitializeComponent() call

    End Sub

    'Form overrides dispose to clean up the component list.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
    Friend WithEvents lblStatus As System.Windows.Forms.Label
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Me.lblStatus = New System.Windows.Forms.Label
        Me.SuspendLayout()
        '
        'lblStatus
        '
        Me.lblStatus.Dock = System.Windows.Forms.DockStyle.Fill
        Me.lblStatus.Location = New System.Drawing.Point(0, 0)
        Me.lblStatus.Name = "lblStatus"
        Me.lblStatus.Size = New System.Drawing.Size(232, 86)
        Me.lblStatus.TabIndex = 0
        Me.lblStatus.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
        '
        'status
        '
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
        Me.ClientSize = New System.Drawing.Size(232, 86)
        Me.Controls.Add(Me.lblStatus)
        Me.MaximizeBox = False
        Me.MinimizeBox = False
        Me.Name = "status"
        Me.Text = "status"
        Me.ResumeLayout(False)

    End Sub

#End Region
    Public Overloads Sub Show(ByVal Message As String)
        lblStatus.Text = Message
        Me.Show()
        Application.DoEvents()
    End Sub
End Class


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值