DB: Riempire un DataTable tramite un DataAdapter (Fill) in C#
Esempio in C# di come interrogare SQL Server per riempire un DataTable tramite una stringa contenete una istruzione di SELECT.
C#
// using System.Data.SqlClient;
int id= 10;
DataTable dt = new DataTable();
string sql = "SELECT [IDObject] AS [ID], [IDObjectParent] AS [IDParent], [IDObjectType], [IDOrderType], [position], [title] "
+ " FROM [TbObjects] "
+ " WHERE [IDObject] =@ID;
+ " ORDER BY [IDObjectParent], [position], [title]"
;
SqlConnection cnn = new SqlConnection("<connectonString>");
SqlCommand cmd = cnn.CreateCommand();
cmd.CommandText = sql;
cmd.Parameters.Add("@ID", SqlDbType.Int);
cmd.Parameters["@ID"].Value = id;
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt); // riempie il DataTable
da = null;
cnn.Close();
cnn = null;