Filling the DataGridView
Dim str(Me.DataGridView1.ColumnCount - 1) As String
str(cName.Index) = "Peter"
str(cSalary.Index) = "30 000$"
str(cCity.Index) = "Toronto"
str(cPhone.Index) = "123-456-7890"
Using the column name and his index to make sure you are putting the right information under the right column.
You could make a loop to fill your DatagridView faster, here is and example using random value:
Dim oRandom As Random
oRandom = New Random()
Dim str(Me.DataGridView1.ColumnCount - 1) As String
For index1 As Integer = 0 To 10
str(cName.Index) = oRandom.Next(100).ToString
str(cSalary.Index) = oRandom.Next(100).ToString
str(cCity.Index) = oRandom.Next(100).ToString
str(cPhone.Index) = oRandom.Next(100).ToString
DataGridView1.Rows.Add(str)
Next
|
Delete a row
Here is a basic example to clear all your rows:
Me.DataGridView1.Rows.Clear()
|
Insert a ContextMenuStrip
Using a ContextMenuStrip1 make the job easier for the user. Naturally, the user will right click the DataGridView to add, delete, move, copy, cut and paste inside the DataGridView. To do so, you need the get the rows number and the column number from the user.
Here is an example that displays the rows number and the column of the MouseClick cell. It will also display a ContextMenuStrip right at the place where the user clicks.
Private Sub DataGridView1_CellMouseClick(sender As Object, e AsSystem.Windows.Forms.DataGridViewCellMouseEventArgs) Handles DataGridView1.CellMouseClick
Me.Text = ("[" & e.RowIndex & " ; " &
e.ColumnIndex & "]")
Dim pt As Point = MousePosition
ContextMenuStrip1.Show(pt)
End Sub
End Sub
Save your DataGridView
There is many ways to save your DatagridView. You could send the sata inside a SQL database. You could use a DataSet to save it inside a XML file. I will only show you how to save it inside a text file. Each value will be separated by a TAB.
Why am I showing you this way? Because is the simplest way and because most reader wan something simple.
Private Sub SaveDataGridView()
Dim strLine As String = ""
Using oSaveFileDialog As New SaveFileDialog
oSaveFileDialog.Title = "save
your DataGridView inside a text file"
oSaveFileDialog.AddExtension = True
oSaveFileDialog.DefaultExt = "txt"
If oSaveFileDialog.ShowDialog
= Windows.Forms.DialogResult.OK Then
Using oFile As New IO.StreamWriter(oSaveFileDialog.FileName, False)
For index1 As Integer = 0 To Me.DataGridView1.RowCount
- 1
strLine = ""
For index2 As Integer = 0 To Me.DataGridView1.Rows(index1).Cells.Count
- 1
strLine = strLine & vbTab & Me.DataGridView1.Rows(index1).Cells(index2).Value
Next
oFile.WriteLine(strLine)
Next
End Using
End If
End Using
No comments:
Post a Comment