List<T> and GridView binding
-
20-09-2019 - |
Question
Here are a few properties of my class. There is also a public object of another class DNRole
private Int32 _IDMarketingCampaign;
private String _Name;
public Int32 IDMarketingCampaign
{
get { return _IDMarketingCampaign; }
set { _IDMarketingCampaign = value; }
}
public String Name
{
get { return _Name; }
set { _Name = value; }
}
public DPRole DNRole = new DPRole();
In the same class I have a method returnig List. Besides my regular fields, I'm also populating one field of my DNRole object:
listItem.DNRole.RoleName = dr["RoleNameFK"].ToString();
My question is.. Is this legal and is it how it should be done, and if yes, how do I show data in a girdview?
public List<MarketingCampaign> SelectForGrid(string strRoleName)
{
List<MarketingCampaign> lista = new List<MarketingCampaign>();
SqlCommand command = new SqlCommand("fra_MarketingCampaignSelectForGrid ", conn);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("RoleName", SqlDbType.VarChar).Value = strRoleName;
SqlDataReader dr = null;
try
{
conn.Open();
dr = command.ExecuteReader();
while (dr.Read())
{
MarketingCampaign listItem = new MarketingCampaign();
listItem.IDMarketingCampaign = Convert.ToInt32(dr["IDMarketingCampaign"]);
listItem.Name = dr["Name"].ToString();
listItem.DNRole.RoleName = dr["RoleNameFK"].ToString();
...
lista.Add(listItem);
}
Solution
You can use ObjectDataSource - to wrap call SelectForGrid, also you can direct bind List to your GridView:
MyGrid.DataSoure = some. SelectForGrid();
MyGrid.DataBind();
When data is binded in *.aspx/ascx code you need bind columns to properties: Eval and Bind allows you do it by name, but faster way to use explicit cast to MarketingCampaign.
<asp:TemplateField >
<ItemTemplate>
<%#((MarketingCampaign)Container.DataItem).Name%>
</ItemTemplate>
...
OTHER TIPS
List<MarketingCampaign> mk= obj.SelectForGrid("Role");
GridView1.DataSource = mk;
GridView1.DataBind();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow