我在windowform中有这个datagridview,我有一个按钮,它应该向datagridview添加一个新行,所以当我点击它时会打开一个新的窗口表单,如何保存我的数据当前窗口形式并更新datagrid视图?
数据网格从列表中填充,如下所示:
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;
}
如何保存我在新表单中插入的数据,关闭后,datagridview中会出现一个新行。
请提供任何帮助。
答案 0 :(得分:0)
您可以在FormClosing事件中执行此操作。
以下是向数据网格视图添加列,行和单元格的示例。
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
答案 1 :(得分:0)
使用BindingList<xml.UserDescriptor>
,而不是List<xml.UserDescriptor>
。
将此users
变量传递给新表单,并在新表单中更新它。
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(){...});
}
}