Says, I have employee table, with {id, name, unit, etc..} what is the preferred ways to get this data if I frequently use this data, my first option is to query it from database when needed, something like this,
public static List<Employee> GetEmployees(string unitID)
{
List<Employee> employees = new List<Employee>();
using (SqlConnection sqlConn = new SqlConnection(string.Format(constring, UserID, Password, Server, Database)))
{
using (SqlCommand sqlComm = new SqlCommand(string.Format("SELECT ID, Name FROM Employee WHERE UnitID = {0} ORDER BY Name", unitID), sqlConn))
{
try
{
sqlConn.Open();
using (SqlDataReader sqlReader = sqlComm.ExecuteReader())
{
if (sqlReader.HasRows)
{
while (sqlReader.Read())
{
Employee employee = new Employee()
{
ID= sqlReader["ID"].ToString(),
Name = StaticField.id_ID.TextInfo.ToTitleCase(sqlReader["Name"].ToString())
};
employees.Add(employee);
}
}
}
}
catch (Exception ex)
{
MessageBoxEx.Show(ex.Message, "GetEmployees Error", MessageBoxButton.OK, MessageBoxImage.Stop);
}
return employees;
}
}
}
Or second option, create DataSet, then add employee table as TableAdapter on the dataset.
var employeeListTableAdapter = new DataSetEmployeeTableAdapters.EmployeeListTableAdapter();
employeeListTableAdapter.ClearBeforeFill = true;
employeeListTableAdapter.Fill(dataset.EmployeeList);
then when I need to filter the row, I just use something like this.
DataView data = dataset.EmployeeList.DefaultView;
data.RowFilter = string.Format("Unit = {0}", unitID);