I have a query – “SELECT PK1 FROM users“;
I also have a datatable named myTable with three fields of type int;
-----------
| myTable |
-----------
| field1 |
| field2 |
| field3 |
-----------
For each row returned from my query, I would like to put the PK1 value into field2 in myTable leaving field1 and field3 null.
Here’s some sample code I have tried so far, but it doesn’t seem to be working. Instead, the field PK1 is appended to the end of myTable as a new field.
class Program
{
static void Main(string[] args)
{
string SQL = "SELECT PK1 FROM users";
SqlConnection connection = new SqlConnection([my connection string]);
DataTable myTable = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = new SqlCommand(SQL, connection);
myTable.Columns.Add("field1", typeof(Int32));
myTable.Columns.Add("field2", typeof(Int32));
myTable.Columns.Add("field3", typeof(Int32));
DataTableMapping dataMapping = adapter.TableMappings.Add("myTable", "users");
dataMapping.ColumnMappings.Add("PK1", "field2");
adapter.Fill(myTable);
foreach (DataRow row in myTable.Rows)
{
Console.WriteLine("------------");
foreach (DataColumn column in myTable.Columns)
{
Console.WriteLine(column.ColumnName + " : " + row[column]);
}
}
Console.ReadKey();
}
}
Is there an issue in my code, or is there another way I can map the fields across?
This is a simplified example for the purposes of this question, as such mapping the field names would be ideal rather than inserting the value at a given position.
I think if it is your requirement then there is nothing wrong with this approach.
Change your query to the following, and you don’t need the mapping.