0
votes

I have this datagridview in a windowform, i do have a button that is supposed to add a new row to the datagridview, so when i click on it it opens up a new window form, how do i save the data from my current window form and update the datagrid view?

The datagrid is populated from a list, like this:

 public void GetUserDetails()
        {   
                        List<xml.UserDescriptor> users = new List<xml.UserDescriptor>();
                        foreach (xml.UserDescriptor dbList in xmlData.Users)
                        {
                            if (dbList.DatabaseDescriptorName == name)
                            {
                                users.Add(new xml.UserDescriptor() { DatabaseDescriptorName = dbList.DatabaseDescriptorName, Username = dbList.Username, Password = dbList.Password, IsAdmin = dbList.IsAdmin });

                            }
                        }

                        dataGridView3.DataSource = users;

            }

How do i save the data i inserted in the new form and after closing it a new row should appear in the datagridview.

Please any help would be appreciated.

2

2 Answers

0
votes

You can do it in your FormClosing event.

Here is an example of adding columns, rows, and cells to a datagridview.

Option Strict On
Option Explicit On
Option Infer Off
Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        DataGridView1.Columns.Add(New DataGridViewTextBoxColumn)
        DataGridView1.Columns.Add(New DataGridViewTextBoxColumn)
        DataGridView1.Columns.Add(New DataGridViewTextBoxColumn)
        DataGridView1.Columns.Add(New DataGridViewTextBoxColumn)
        For i As Integer = 0 To 100 Step 4
            Dim row As New DataGridViewRow
            Dim cell1 As New DataGridViewTextBoxCell
            Dim cell2 As New DataGridViewTextBoxCell
            Dim cell3 As New DataGridViewTextBoxCell
            Dim cell4 As New DataGridViewTextBoxCell
            cell1.Value = i.ToString
            cell2.Value = (i + 1).ToString
            cell3.Value = (i + 2).ToString
            cell4.Value = (i + 3).ToString
            row.Cells.AddRange({cell1, cell2, cell3, cell4})
            DataGridView1.Rows.Add(row)
        Next
    End Sub
End Class
0
votes

Use BindingList<xml.UserDescriptor>, not List<xml.UserDescriptor>.

Pass this users variable to the new Form, and update it within the new Form.

MainForm.cs

new NewForm(users).ShowDialog();

NewForm.cs

public class NewForm : Form
{
    BindingList<xml.UserDescriptor> _users;
    public NewForm(BindingList<xml.UserDescriptor> users)
    {
        _users = users;
    }

    private void btnAddUser_Click(object sender, EventArgs e)
    {
       _users.Add(new xml.UserDescriptor(){...});
    }
}