Пример показывает, как введённые данные (включая фото) в ячейки DataGridView можно сохранить в XML-файл, созданный приложением автоматически. При новом запуске вся таблица сохранённых данных будет отображена в ячейках DataGridView.
Инструкции
В колонке "Фото" применяется контексное меню,посредством клика правой кнопки мыши.
Код
Imports System.IO
Public Class Form1
Dim dt As DataTable = New DataTable("Таблица данных")
Dim ds As New Data.DataSet("mmyDataSet")
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Me.Size = New Size(880, 700)
''-----Внедряем колонку для отображения картинок
Dim cellPhoto(0) As Data.DataColumn
cellPhoto(0) = dt.Columns.Add("ФОТО", GetType(Byte()))
'-----------Добавляем другие столбцы данных
dt.Columns.Add("Номер", GetType(Integer))
dt.Columns.Add("Имя", GetType(String))
dt.Columns.Add("Дата", GetType(Date))
' Добавить объект dt в DataSet:
ds.Tables.Add(dt)
If IO.File.Exists("tabl.xml") = False Then
DataGridView1.DataSource = dt
dt.Rows.Add()
Else ' Если XML-файл ЕCТЬ:
ds.ReadXmlSchema("tablSchema.xml")
ds.ReadXml("tabl.xml")
DataGridView1.DataMember = "Таблица данных"
DataGridView1.DataSource = ds
End If
End Sub
Private Sub Save_bttn_Click(sender As System.Object, e As System.EventArgs) Handles Save_bttn.Click
'dt.TableName = "Таблица данных"
'ds.WriteXmlSchema("tablSchema.xml")
'ds.WriteXml("tabl.xml")
''-----Данные можно вывести в XML-файл из объекта DataTable напрямую,без применения объекта DataSet
dt.WriteXml("tabl.xml")
'-----Получить схему,соответствующую экспортируемым данным
dt.WriteXmlSchema("tablSchema.xml")
End Sub
Private Sub ЗагрузитьФотоToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles ЗагрузитьФотоToolStripMenuItem.Click
Dim myStream As Stream
Dim myopenFileDialog As New OpenFileDialog
myopenFileDialog.InitialDirectory = "C:\"
myopenFileDialog.Filter = "Images|*.GIF;*JPG;*JPEG;*.TIF;*BMP"
myopenFileDialog.FilterIndex = 2
myopenFileDialog.RestoreDirectory = True
If myopenFileDialog.ShowDialog() = Windows.Forms.DialogResult.OK Then
myStream = myopenFileDialog.OpenFile()
If Not (myStream Is Nothing) Then
Me.DataGridView1.CurrentCell.Value = Image.FromFile(myopenFileDialog.FileName)
myStream.Close()
End If
End If
End Sub
Private Sub Load_btn_Click(sender As System.Object, e As System.EventArgs) Handles Load_btn.Click
Dim myStream As Stream
Dim myopenFileDialog As New OpenFileDialog
myopenFileDialog.InitialDirectory = "C:\"
myopenFileDialog.Filter = "Images|*.GIF;*JPG;*JPEG;*.TIF;*BMP"
myopenFileDialog.FilterIndex = 2
myopenFileDialog.RestoreDirectory = True
If myopenFileDialog.ShowDialog() = Windows.Forms.DialogResult.OK Then
myStream = myopenFileDialog.OpenFile()
If Not (myStream Is Nothing) Then
Me.DataGridView1.CurrentCell.Value = Image.FromFile(myopenFileDialog.FileName)
myStream.Close()
End If
End If
End Sub
Private Sub dataGridView1_CellFormatting(ByVal sender As Object, _
ByVal e As DataGridViewCellFormattingEventArgs) _
Handles DataGridView1.CellFormatting
If Me.DataGridView1.Columns(e.ColumnIndex).Name = "Дата" Then
ShortFormDateFormat(e)
End If
End Sub
'Even though the date internaly stores the year as YYYY, using formatting, the
'UI can have the format in YY.
Private Shared Sub ShortFormDateFormat(ByVal formatting As DataGridViewCellFormattingEventArgs)
If formatting.Value IsNot Nothing Then
Try
Dim dateString As System.Text.StringBuilder = New System.Text.StringBuilder()
Dim theDate As Date = DateTime.Parse(formatting.Value.ToString())
dateString.Append(theDate.Month)
dateString.Append(".")
dateString.Append(theDate.Day)
dateString.Append(".")
dateString.Append(theDate.Year.ToString().Substring(0))
formatting.Value = dateString.ToString()
formatting.FormattingApplied = True
Catch notInDateFormat As FormatException
' Set to false in case there are other handlers interested trying to
' format this DataGridViewCellFormattingEventArgs instance.
formatting.FormattingApplied = False
End Try
End If
End Sub
Private Sub ВыходToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs)
MsgBox("Ну, что,- до свидания?")
Dim counter As Integer
For counter = 90 To 10 Step -10
Me.Opacity = counter / 100
Me.Refresh()
Threading.Thread.Sleep(50)
Next counter
Me.Close()
End Sub
End Class)
Dim ds As New Data.DataSet(tabl.xml
Добавлять комментарии могут только зарегистрированные пользователи сайта.
Если у Вас уже есть учетная запись на Kbyte.Ru, пройдите процедуру авторизации.
Если Вы еще не зарегистрированы на Kbyte.Ru - зарегистрируйтесь.