Fixing various problems with your method:
private static void PrepareCommand(SqlCommand command, string query, object[] parameters)
{
if (parameters != null && parameters.Length != 0)
{
string[] names = new string[parameters.Length];
for (int index = 0; index < parameters.Length; index++)
{
string name = $"@p{index}";
command.Parameters.AddWithValue(name, parameters[index]);
names[index] = name;
}
query = string.Format(CultureInfo.InvariantCulture, query, names);
}
command.CommandText = query;
command.CommandType = CommandType.Text;
}
public static DataTable filldt(string query, params object[] parameters)
{
if (string.IsNullOrWhiteSpace(query)) throw new ArgumentNullException(nameof(query));
var connection = ConfigurationManager.ConnectionStrings["ConString"];
if (connection == null) throw new InvalidOperationException("Connection string not found!");
using (var con = new SqlConnection(connection.ConnectionString))
using (var command = new SqlCommand(string.Empty, con))
{
PrepareCommand(command, query, parameters);
using (var dataAdapter = new SqlDataAdapter(command))
{
var dt = new DataTable();
dataAdapter.Fill(dt);
return dt;
}
}
}
Usage:
string someValue = SomeTextBox.Text;
DateTime someOtherValue = DateTime.Now;
DataTable dt = filldt("SELECT * FROM SomeTable WHERE SomeColumn = {0} And SomeOtherColumn = {1}", someValue, someOtherValue);