Skip to content

Instantly share code, notes, and snippets.

@pedroinfo
Created March 23, 2026 14:41
Show Gist options
  • Select an option

  • Save pedroinfo/c17826d54a7b5667c4580a8f98210b63 to your computer and use it in GitHub Desktop.

Select an option

Save pedroinfo/c17826d54a7b5667c4580a8f98210b63 to your computer and use it in GitHub Desktop.
DataTableWithParameters
public DataTable ExecuteQuery(string sql, string connectionString, object param = null)
{
using var conn = new SqlConnection(connectionString);
using var cmd = new SqlCommand(sql, conn);
if (param != null)
{
foreach (var prop in param.GetType().GetProperties())
{
var value = prop.GetValue(param);
cmd.Parameters.AddWithValue("@" + prop.Name, value ?? DBNull.Value);
}
}
using var adapter = new SqlDataAdapter(cmd);
var dt = new DataTable();
adapter.Fill(dt);
return dt;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment