Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Working DataGrid TemplateColumns and Binding these Columns

0.00/5 (No votes)
14 Nov 2002 1  
Working DataGrid TemplateColumns and binding these columns with differents objects (TextBox, DropDownList, CheckBox, Image and others).

Sample Image - workingdatagrid1.jpg

Introduction

The example to follow helps you to work with columns template in a DataGrid using different types of controls, as shown in picture.

Step 1

Drag DataGrid control from your toolbox, create a template column in property builder. In property menu, select option for editing column template.

Step 2

Customize your object (example, your TextBox) and drag the ItemTemplate. You must personalize its picture.

Step 3

Let's analyze the ConverGridObjects class:

using System;
using System.Data;
using System.Web.UI.WebControls;    
using System.Collections; 

namespace DataGridCheckColumn
{
    public class ConvertGridObjects
    {
        public ConvertGridObjects()
        {
        }

        TextBox txt = null;
        DropDownList ddl = null;
        CheckBox chk = null;
        int record ; 

        public DataSet ReverseDataBiding()
        {
            return reversedata;
        }

        public void DataBindObjects(DataGrid dg, 
           DataSet ds,int pageindex,int pagesize)
        {
            int i = 0;
            int ids = 0;

            //Verify the not null properties

            //Exeption Controls

            if (this.editable == null ||
                this.objectname == null ||
                this.fieldname == null ||
                this.editable.Count != this.fieldname.Count ||
                this.editable.Count != this.objectname.Count ||
                this.fieldname.Count != this.editable.Count ||
                this.fieldname.Count != this.objectname.Count || 
                this.objectname.Count != this.fieldname.Count ||
                this.objectname.Count != this.editable.Count )
            {
                string msg = "You must define for all the objects \n";
                msg += "DropDown,TextBox e CheckBox as follow properties:\n";
                msg += "c.FieldName = 'My Field'\n"; 
                msg += "c.ObjectName = 'TextBox3'\n";
                msg += "c.Editable = true\n ";
                msg += " where 'c' instance ";

                throw new Exception(msg); 
            }

            //Move the itens of the grid

            for (ids=0;ids<dg.Items.Count;ids++)
            {
                //to select the item

                DataGridItem dgi = dg.Items[ids]; 
                
                //to verify paging

                record = (pagesize * pageindex) + ids;

                //to verify fieldname collections

                for (i=0;i<this.fieldname.Count;i++)
                {                

                    //find the control

                    object obj = 
                      dgi.FindControl(this.objectname[i].ToString());

                    //to verify type

                    //this editable all itens

                    if (obj is TextBox)
                    {
                        txt = 
                         (TextBox) 
                         dgi.FindControl(this.objectname[i].ToString());
                        if (this.editable != null)
                        {                            
                            if ((bool)this.editable[i] == true)
                            {
                                txt.ReadOnly = false;
                            }
                            else
                            {
                                txt.ReadOnly = true;
                            }
                        }
                        else
                        {
                            txt.Enabled = true;
                        }
                    }
                    else if (obj is Image)
                    {
                        img = (Image) 
                         dgi.FindControl(this.objectname[i].ToString());
                    }
                    else if (obj is DropDownList)
                    {
                        ddl = (DropDownList) 
                         dgi.FindControl(this.objectname[i].ToString());
                        if (this.editable != null)
                        {
                            if ((bool)this.editable[i] == true)
                            {
                                ddl.Enabled = true;
                            }
                            else
                            {
                                ddl.Enabled = false;
                            }
                        }
                        else
                        {
                            ddl.Enabled = true;
                        }

                    }
                    else if (obj is CheckBox)
                    {
                        chk = (CheckBox) 
                          dgi.FindControl(this.objectname[i].ToString());
                        if (this.editable != null)
                        {
                            if ((bool)this.editable[i] == true)
                            {
                                chk.Enabled = true;
                            }
                            else
                            {
                                chk.Enabled = false;
                            }
                        }
                        else
                        {
                            chk.Enabled = true;
                        }

                    }
                }
                
                i=0;

                //bind the data to fieldname 

                //correspondent to collection fieldname 

                for (i=0;i<this.fieldname.Count;i++)
                {
                    //Check the objects in ther columns 

                    //it is applied to all itens

                    if (txt !=null && 
                      this.objectname[i].ToString().ToUpper() 
                      == txt.ID.ToUpper())
                    {                        
                        txt.Text = ds.Tables[0].Rows[record]
                            [this.fieldname[i].ToString()].ToString();  
                    }
                    else if (img !=null && 
                      this.objectname[i].ToString().ToUpper()
                        == img.ID.ToUpper())
                    {
                        try
                        {
                            //convert to binary data 

                            //your database field type image

                            byte[] bits = (byte[]) ds.Tables[0].Rows[record]
                                [this.fieldname[i].ToString()];  
                            MemoryStream memorybits = new MemoryStream(bits);
                            System.Drawing.Image bitmap = 
                              System.Drawing.Image.FromStream(memorybits);
                            string imageharddisk = 
                              @"c:\temp\img\" + (img.GetHashCode() + i); 
                            bitmap.Save(imageharddisk);  
                            img.ImageUrl = imageharddisk;
                        }
                        catch
                        {
                        }
                    }

                    else if (ddl !=null && this.objectname[i].ToString().ToUpper()
                        == ddl.ID.ToUpper())
                    {                        
                        if(this.DataFieldText == null |
                            this.DataFieldValue == null)
                        {
                            throw new 
                              NullReferenceException("DataFieldText" + 
                              " ou DataFieldValue, n�o pode ser nulo");
                        }

                        ddl.DataTextField = this.DataFieldText;
                        ddl.DataValueField = this.DataFieldValue;

                        if (this.dropdowndata == null)
                        {
                            throw new 
                              NullReferenceException("DropDownData, 
                              n�o pode ser nulo");
                        }

                        ddl.DataSource = (DataSet) this.dropdowndata[i]; 
                        ddl.DataBind();
 
                        this.PositionObjectList(
                         ddl,
                         ds.Tables[0].Rows[record]
                         [this.fieldname[i].ToString()].ToString());

                    }
                    else if (chk !=null && this.objectname[i].ToString().ToUpper()
                        == chk.ID.ToUpper())
                    {
                        if (ds.Tables[0].Rows[record]
                         [this.fieldname[i].ToString()].ToString().Trim() == "0")
                        {
                            chk.Checked = false;
                        }
                        else
                        {
                            chk.Checked = true;
                        }

                    }

                }
            }
        }

        public void PositionObjectList(System.Web.UI.WebControls.DropDownList cbo,
            string val)
                        
        {            
            int i;

            for (i = 0;i < (cbo.Items.Count);i++)
            {
                cbo.SelectedIndex = i;
                if (cbo.SelectedItem.Value == val)
                {
                    cbo.SelectedItem.Selected = true;
                    break;
                }

            }
        }
    
        private ArrayList fieldname;
        private ArrayList objectname;
        private ArrayList editable;
        static DataSet dropdowndata;
        static string datafieldtext;
        static string datafieldvalue;
        static DataSet reversedata;

        public string DataFieldText
        {
            set
            {
                datafieldtext = value;
            }
            get
            {
                return datafieldtext;
            }
        }

        public string DataFieldValue
        {
            set
            {
                datafieldvalue = value;
            }
            get
            {
                return datafieldvalue ;
            }
        }

        public  DataSet DropDownData
        {
            set
            {
                dropdowndata = value;
            }
            get
            {
                return dropdowndata ;
            }
        }

        public string FieldName
        {
            set
            {
                if (fieldname == null)
                {
                    fieldname = new ArrayList();
                }
                fieldname.Add (value);
            }
        }

        public  string ObjectName
        {
            set
            {
                if (objectname == null)
                {
                    objectname = new ArrayList(); 
                }
                objectname.Add(value);
            }
        }

        public bool Editable
        {
            set
            {
                if (editable == null)
                {
                    editable = new ArrayList(); 
                }
                editable.Add(value);
            }
        }

    }
}

Last Step

In the button where grid must be loaded, add this procedure:

private void Button1_Click(object sender, System.EventArgs e)
    {            
        //initialize the class

        ConvertGridObjects convert =
            new ConvertGridObjects(); 

        //extract data to database

        ds= SqlHelper.ExecuteDataset(connectionString,"sp_tst",null);
        //set to DataSource 

        grid.DataSource = ds.Tables[0].DefaultView;
        //bind to grid 

        grid.DataBind(); 

        //It extracts the data for its DropDownList that is inside of grid 

        DataSet uf = SqlHelper.ExecuteDataset(connectionString,"spuf",null);

        //Warning! Set the properties following always 

        //the order where the objects appear in grid

        convert.FieldName = "mytext"; 
        convert.ObjectName = "TextBox3";
        convert.Editable = true;
        convert.FieldName = "Flag";
        convert.ObjectName  = "CheckBox1";
        convert.Editable = true;
        convert.FieldName = "iduf";
        convert.ObjectName  = "cboUf";
        convert.Editable = false;
        convert.DataFieldText = "coduf";
        convert.DataFieldValue = "iduf";
        convert.DropDownData = uf;

        //Bind the objects Textbox,CheckBox,DropDown

        convert.GetDataToObject(grid,ds,0,grid.PageSize);

    }

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here