问题
I want to refresh the DataGridView after inserting a new member into the database. I created a method on the main form which occurs on the mainform_load. From the other form (addmember), after I click on SaveMemberButton I'm calling that method to refresh the datagridview but It wont happen.
This is my code on the main form:
private void MainForm_Load(object sender, EventArgs e)
{
//ShowLoginForm();
ListMembers();
}
public void ListMembers()
{
MembersDataGridView.Columns.Clear();
MembersDataGridView.DataSource = Connection.ListMembers();
MembersDataGridView.ClearSelection();
}
This is my code on the other form:
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);
}
}
This is the code which gets the data from the database:
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;
}
On the MainForm_Load the gridview lists the data perfectly. But I can't refresh the gridview, I have to restart the application to refresh it. Any suggestions ?
回答1:
MainForm always stay opened during processes ?
If so, you create a new instance of 'MainForm' at
private MainForm mainForm = new MainForm();
So you refreshing the second instance of 'MainForm' and you can not see it in the first instance of 'MainForm'. You must send your 'MainForm' instance to the other form. Don't create a new instance.To do this where you create the other form send 'MainForm' instance to the other form :
private void ShowForm2()
{
Form2 form = new Form2(this);
form.Show();
}
Make your Form2 constructor like this:
private MainForm mainForm;
public Form2(MainForm form)
{
InitializeComponent();
mainForm = form;
}
And call your method.
Sorry for bad English..
回答2:
after code that you insert a new member .. add this
MembersDataGridView.DataSource = Connection.ListMembers();
来源:https://stackoverflow.com/questions/16980077/refreshing-datagridview-from-another-form-on-button-click