Monday, 7 May 2012

How to add a ASPxImage control in ASPxGridView run time?

ASPxGridView

<dx:ASPxGridView ID="gvUser" AutoGenerateColumns="False" runat="server"  OnDataBound="gvUser_DataBound" 
            OnHtmlRowCreated="gvUser_HtmlRowCreated">
            <Columns>
                <dx:GridViewCommandColumn ShowSelectCheckbox="True" VisibleIndex="0">
                </dx:GridViewCommandColumn>
                <dx:GridViewDataTextColumn FieldName="fldFirstName" VisibleIndex="1">
                </dx:GridViewDataTextColumn>
                <dx:GridViewDataTextColumn FieldName="fldLastName" VisibleIndex="2">
                </dx:GridViewDataTextColumn>
                 <dx:GridViewDataTextColumn FieldName="fldMobileNo" VisibleIndex="3">
                </dx:GridViewDataTextColumn>
                <dx:GridViewDataTextColumn FieldName="fldEmailAddress" VisibleIndex="4">
                </dx:GridViewDataTextColumn>
                 <dx:GridViewDataTextColumn FieldName="fldUserType" VisibleIndex="5">
                </dx:GridViewDataTextColumn>
            </Columns>
        </dx:ASPxGridView>

Adding a ASPxImage Control to ASPxGridView

Here I create a class called MyImageTemplate  in c# which implements ITemplate interface and create an instance of ASPxImage control and add it to GridViewDataItemTemplateContainer.

 class MyImageTemplate : ITemplate
    {
        public string ID { get; set; }

        public void InstantiateIn(Control container)
        {
            img = new ASPxImage();
            gridContainer = (GridViewDataItemTemplateContainer)container;
            //img.ImageUrl = "~/Images/OK.gif";
            img.Visible = false;
            img.ID = ID;
            img.Width = 50;
            img.Height = 40;
            container.Controls.Add(img);
        }
    } 

OnDataBound Event Method

Here I implement the OnDataBound event in which adds  ASPxImage Control as custom calumn.

protected void gvUser_DataBound(object sender, EventArgs e)
        {
            GridViewDataColumn col1 = new GridViewDataColumn();
            col1.Caption = "User Icon";
            col1.FieldName = "UserIcom";
            col1.Width = 60;
            col1.VisibleIndex = 6;
            //visibleIndex++;
            col1.DataItemTemplate = new MyImageTemplate() { ID = "ASPxImage1" };
            gvUser.Columns.Add(col1);
        }

No comments:

Post a Comment