Hi,
Please refer below code.
Here I have created Generic Class PopulateList,that has generic method Populate accepts commandText(i.e. query or procedureName) and CommandType based on that it populates generic Lists(i.e. List of Customers or List of Employees)
HTML
<div>
<asp:GridView ID="gvCustomers" runat="server" />
<br />
<asp:GridView ID="gvEmployees" runat="server" />
</div>
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
PopulateCustomers();
PopulateEmployees();
}
}
private void PopulateCustomers()
{
List<Customer> customers = PopulateList<Customer>.Populate("Select TOP 10 * FROM Customers", CommandType.Text);
gvCustomers.DataSource = customers;
gvCustomers.DataBind();
}
private void PopulateEmployees()
{
List<Employee> customers = PopulateList<Employee>.Populate("Select TOP 10 * FROM Employees", CommandType.Text);
gvEmployees.DataSource = customers;
gvEmployees.DataBind();
}
public class Customer
{
public string CustomerId { get; set; }
public string ContactName { get; set; }
public string City { get; set; }
public string Country { get; set; }
}
public class Employee
{
public int EmployeeID { get; set; }
public string FirstName { get; set; }
public DateTime BirthDate { get; set; }
public DateTime HireDate { get; set; }
}
Generic Class PopulateList
public class PopulateList<T>
where T : class
{
private static string ConnectionString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
public static List<T> Populate(string cmdText, CommandType commandType, params SqlParameter[] sqlParameters)
{
using (SqlConnection con = new SqlConnection(ConnectionString))
{
using (SqlCommand cmd = new SqlCommand(cmdText, con))
{
cmd.CommandType = commandType;
cmd.Connection.Open();
cmd.Parameters.AddRange(sqlParameters);
using (IDataReader idr = cmd.ExecuteReader())
{
return (PopulateEntities<T>(idr, cmd));
}
}
}
}
public static List<T> PopulateEntities<T>(IDataReader dr, SqlCommand cmd)
{
List<T> entities = new List<T>();
while (dr.Read())
{
T ent = Activator.CreateInstance<T>();
PopulateEntity<T>(ent, dr);
entities.Add(ent);
}
cmd.Connection.Close();
return entities;
}
public static void PopulateEntity<T>(T entity, IDataRecord record)
{
if (record != null && record.FieldCount > 0)
{
Type type = entity.GetType();
for (int i = 0; i < record.FieldCount; i++)
{
if (DBNull.Value != record[i])
{
PropertyInfo property =
type.GetProperty(record.GetName(i),
BindingFlags.IgnoreCase |
BindingFlags.Public | BindingFlags.Instance);
if (property != null)
{
property.SetValue(entity,
record[property.Name], null);
}
}
}
}
}
}
Screenshot