The next sequence seems to work:
dtTag.Clear( );
dtTag.Columns.Clear( );
Use it instead of dtTag.Reset( ), which appears to cause issues.
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Hi,
My Winform application has a datagridview dgvTag and a button btnGen in a User Control. Clicking the button will generate the data in a datatable dtTag which is set as the data source of the datagridview. The code is like this:
private void btnGen_Click(object sender, EventArgs e)
{
dtTag.Reset();
dtTag.Columns.Add("A", typeof(string));
dtTag.Columns.Add("B", typeof(string));
dtTag.Columns.Add("C", typeof(string));
dtTag.Columns.Add("D", typeof(string));
dtTag.Columns.Add("E", typeof(string));
dtTag.Columns.Add("F", typeof(string));
dtTag.Columns.Add("G", typeof(string));
//put the code here to generate the tags
dgvTag.DataSource = dtTag;
MessageBox.Show("Database generated.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
Somehow, this code only works for the first time. If the button was clicked for the 2nd time, the datagridview becomes empty while only column headers are still there. I am sure the datatable dtTag is not not empty. Could you please help on this? Thanks.
The next sequence seems to work:
dtTag.Clear( );
dtTag.Columns.Clear( );
Use it instead of dtTag.Reset( ), which appears to cause issues.
Hi PengfeiLiu-9437,
I made a test with your code and it worked fine.
Please refer to the following code:
private void button1_Click(object sender, EventArgs e)
{
DataTable dtTag = new DataTable();
dtTag.Reset();
dtTag.Columns.Add("A", typeof(string));
dtTag.Columns.Add("B", typeof(string));
dtTag.Columns.Add("C", typeof(string));
dtTag.Columns.Add("D", typeof(string));
dtTag.Columns.Add("E", typeof(string));
dtTag.Columns.Add("F", typeof(string));
dtTag.Columns.Add("G", typeof(string));
//put the code here to generate the tags
String connectionString = "your connectionString";
// Create a new data adapter based on the specified query.
SqlDataAdapter dataAdapter = new SqlDataAdapter("select * from test", connectionString);
// Create a command builder to generate SQL update, insert, and
// delete commands based on selectCommand.
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
// Populate a new data table and bind it to the BindingSource.
dataAdapter.Fill(dtTag);
dgvTag.DataSource = dtTag;
MessageBox.Show("Database generated.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
Best Regards,
Daniel Zhang
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.