Good day! There are two datatable and data_list . datatable takes data from the sql query. And the data_list from the datatable table. If I add one more line to datatable , how can I make only new data from datatable? data_list added to datatable?

 using (SqlDataAdapter adapter = new SqlDataAdapter(query, cn)) { using (DataTable dt = new DataTable()) { adapter.Fill(dt); if (DataList == null) { adapter.Fill(DataList); } else { } 
  • Can you help? - propro17

1 answer 1

First, it is not necessary to read the same data from the database twice:

 adapter.Fill(dt); ... adapter.Fill(DataList); 

It is better to copy the data using the Copy method:

 if (DataList == null) DataList = dt.Copy(); 

If you need to add data from one DataTable to another or update it, you should use the Merge method:

 DataList.Merge(dt); 

In this case, primary keys must be specified in both datables. To do this, when creating an adapter, you need to set the MissingSchemaAction property:

 adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey; 

Perhaps you need to change the FillLoadOption property to a suitable one.

Secondly, you simply don't need two DataTable . Leave one in it and read the data. The Fill method, in the presence of primary keys, will update already existing data (or read completely if there is no data).

Naturally, primary keys must be specified in the database.

  • and how can I add a string (string) to datatable as row and update datatable? - propro17
  • @ propro17 - one topic - one question. Why update datatable if it already contains the necessary data (including the added line)? - Alexander Petrov
  • I have a timer that checks if there is an added line - propro17
  • help with the addition? - propro17
  • @ propro17 - I do not see a timer in your question! Want to ask about the timer - ask a new question. You already spawn a bunch of almost identical questions. They answered you there. If something is not clear - there and specify. - Alexander Petrov