views:

279

answers:

2

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);
                }
+1  A: 

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>

...

Dewfy
In this case I'm using ObjectDataSource. Eval("Name") does the trick with regular fields. My problem is that listItem.DNRole.RoleName ... I can't just go and write Eval("DNRole.RoleName")....
Leon
@Leon Then you use what I have wrote about direct cast:((MarketingCampaign)Container.DataItem).DNRole.RoleName
Dewfy
@Dewfy I see... thanks. That worked great!
Leon
A: 
List<MarketingCampaign> mk= obj.SelectForGrid("Role");
GridView1.DataSource = mk;
GridView1.DataBind();
adatapost