[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 37961
  • Last Modified:

C#.NET Insert/Update values in DataTable Row

Hi all

This might have been answered before, but I have been unable to find an answer I can use, so here goes....

I have a DataTable filled with data from an Excel file. Using a for-loop I run through each row in this DataTable and extract 3 values, which I then run through an SQL statement which returns 3 new values. I now need to update the row I got the original 3 values from in the DataTable with the 3 new values.

How do I insert the 3 new values in the correct places in the row?

How do I insert then in the SAME row as I got the 3 original values from?

Thanks in advance

Søren Augustesen

0
poultarp
Asked:
poultarp
  • 2
1 Solution
 
Jai STech ArchCommented:
1)
for loop

'you get the values here
getvalue

'get the new value from the SQL server (using sme sql statement)
GetNewSQLValue

'Update the CURRENT row of the datatable with the new value

next

2) keep a record of what is the ID of the OLD values that you are retriving...
after fetching the records from the SQL table...use the ID that you have saved before and update the records accordingly...
0
 
poultarpAuthor Commented:
Hello jaiganeshsrinivasan

"Update the CURRENT row of the datatable with the new value"

How do I update the current row of the datatable with the new data in the correct places?

Regards
Søren Augustesen
0
 
Jai STech ArchCommented:
if dt is your data table and i is your LOOP int value
then
            DataRow dr;
            dr = new DataRow();
for(int i=0;i<dt.rows.count;i++)
{
            dr = dt.Rows(i); - gives you the specific row...
dr["colname"] = "some new value"
dr.AcceptChanges();
}
dt.AcceptChanges();
0
 
svdlCommented:

The solution proposed by jaiganeshrinivasan will work, but in my opinion a foreach() approach looks cleaner:

// dt is the name of the DataTable
 
foreach (DataRow dr in dt.Rows) {
   // send current values to SQL based update routine
   // and retrieve updated values
   // colname1, colname2 etc represent the column names of the
   // DataTable you want to update
 
   Object[] updatedValues=GetUpdatedValues(dr[colname1],dr[colname2],dr[colname3]);
   dr[colname1]=updatedValues[0]; //you might have to use Convert.ToXXX()
   dr[colname2]=updatedValues[1];
   dr[colname3]=updatedValues[2];
   dr.AcceptChanges();
}
dt.AcceptChanges();

Open in new window

0

Featured Post

What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now