The following code
- Creates a parameter as a parameter should be done and as recommended by @Olivier Rogier.
- Does not use a DataAdapter, seeing you have it as a local var indicates this. Use a command object instead.
- Note the return type carries the DataTable if no errors while if a runtime exception is raised the Exception is passed back to the caller.
- Recommend not using SELECT * (not part of the question but better to ask for that which is needed and no more).
Code
public class DataOperations
{
private static string connection = "Data Source=.\\sqlexpress;Initial Catalog=NorthWind2020;Integrated Security=True";
public static (DataTable table, Exception exception) SelectRow(string contactId)
{
DataTable table = new DataTable();
try
{
using (var cn = new SqlConnection { ConnectionString = connection })
{
using (var cmd = new SqlCommand { Connection = cn })
{
cmd.CommandText = "SELECT FirstName, LastName FROM dbo.Contacts WHERE ContactId = @contactId;";
cmd.Parameters.Add("@contactId", SqlDbType.NVarChar).Value = contactId;
cn.Open();
table.Load(cmd.ExecuteReader());
return (table, null);
}
}
}
catch (Exception exception)
{
return (null, exception);
}
}
}
Sample code to call method above.
var (dataTable, exception) = DataOperations.SelectRow(contactIdentifier);
if (exception == null)
{
Debug.WriteLine("Use table");
}
else
{
Debug.WriteLine(exception.Message);
}
Also, if the contact identifier is pointing to a single record you could simply pass a single DataRow back rather than an entire DataTable or use a single instance of a class e.g.
public class Contact
{
// seems this would be an int
public string ContactId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public override string ToString() => $"{FirstName} {LastName}";
}
Code to get data
public static Contact SelectContact(string contactId)
{
Contact contact = new Contact() {ContactId = contactId};
using (var cn = new SqlConnection { ConnectionString = connection })
{
using (var cmd = new SqlCommand { Connection = cn })
{
cmd.CommandText = "SELECT FirstName, LastName FROM dbo.Contacts WHERE ContactId = @contactId;";
cmd.Parameters.Add("@contactId", SqlDbType.NVarChar).Value = contactId;
cn.Open();
var reader = cmd.ExecuteReader();
if (reader.HasRows)
{
reader.Read();
contact.FirstName = reader.GetString(0);
contact.LastName = reader.GetString(1);
}
}
}
return contact;
}