将新成员插入数据库后,我想刷新 DataGridView。我在 mainform_load 上的主窗体上创建了一个方法。在另一个表单(addmember)中,单击 SaveMemberButton 后,我正在调用该方法来刷新 datagridview,但它不会发生。
这是我在主窗体上的代码:
private void MainForm_Load(object sender, EventArgs e)
{
//ShowLoginForm();
ListMembers();
}
public void ListMembers()
{
MembersDataGridView.Columns.Clear();
MembersDataGridView.DataSource = Connection.ListMembers();
MembersDataGridView.ClearSelection();
}
这是我的另一种形式的代码:
private MainForm mainForm = new MainForm();
private void SaveMemberButton_Click(object sender, EventArgs e)
{
try
{
if (IsValid())
{
var member = new Member
{
Name = AddNewNameTextBox.Text,
Surname = AddNewSurnameTextBox.Text,
EntryDate = DateTime.ParseExact(AddNewEntryDateTextBox.Text, "dd.MM.yyyy", CultureInfo.InvariantCulture),
};
Connection.InsertMember(member);
MessageBox.Show("Member registration successful!");
}
mainForm.ListMembers();
this.Close();
}
catch (Exception exception)
{
MessageBox.Show(exception.Message);
}
}
这是从数据库中获取数据的代码:
public List<Member> ListMembers()
{
List<Member> list = new List<Member>();
string SelectMembers = "SELECT * FROM Members";
sqlConnection.Open();
using (sqlCommand = new SqlCommand(SelectMembers, sqlConnection))
{
var sqlReader = sqlCommand.ExecuteReader();
while (sqlReader.Read())
{
var member = new Member
{
Id = Convert.ToInt32(sqlReader["Id"]),
Name = sqlReader["Name"].ToString(),
Surname = sqlReader["Surname"].ToString(),
EntryDate = Convert.ToDateTime(sqlReader["EntryDate"])
};
list.Add(member);
}
}
sqlConnection.Close();
return list;
}
在 MainForm_Load 上,gridview 完美地列出了数据。但是我无法刷新gridview,我必须重新启动应用程序才能刷新它。有什么建议么 ?