Click here to Skip to main content
15,891,976 members
Articles / Web Development / ASP.NET
Article

Working DataGrid TemplateColumns and Binding these Columns

Rate me:
Please Sign up or sign in to vote.
1.50/5 (2 votes)
14 Nov 2002 204.2K   1.4K   33   22
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:

C#
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:

C#
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


Written By
Web Developer
Brazil Brazil
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralDropdown list Pin
jaasmine17-Feb-06 5:54
jaasmine17-Feb-06 5:54 
QuestionI Want Editable DropDown List Pin
Piyush K Patel16-Mar-08 20:49
professionalPiyush K Patel16-Mar-08 20:49 
Generalnew header Pin
Fernando Finelli23-Jul-04 6:13
Fernando Finelli23-Jul-04 6:13 
GeneralConvert DateTime datatype to Date bind to datagrid Pin
Anonymous14-Apr-04 18:51
Anonymous14-Apr-04 18:51 
GeneralRe: Convert DateTime datatype to Date bind to datagrid Pin
tranminhtrung11-May-06 17:53
tranminhtrung11-May-06 17:53 
QuestionHow to validate a textbox in datagrid with two Regular Expression Validation? Pin
Q_Quek13-Apr-04 20:47
Q_Quek13-Apr-04 20:47 
AnswerRe: How to validate a textbox in datagrid with two Regular Expression Validation? Pin
Esteves14-Apr-04 14:50
Esteves14-Apr-04 14:50 
GeneralRe: How to validate a textbox in datagrid with two Regular Expression Validation? Pin
Q_Quek14-Apr-04 16:02
Q_Quek14-Apr-04 16:02 
GeneralRe: How to validate a textbox in datagrid with two Regular Expression Validation? Pin
Sam964348-Nov-04 10:43
Sam964348-Nov-04 10:43 
QuestionRe: How to validate a textbox in datagrid with two Regular Expression Validation? Pin
Panduraj23-Nov-07 21:18
Panduraj23-Nov-07 21:18 
AnswerRe: How to validate a textbox in datagrid with two Regular Expression Validation? Pin
Q_Quek25-Nov-07 14:51
Q_Quek25-Nov-07 14:51 
GeneralUnbound Column in Windows Forms Pin
SapanShah7-Jul-03 18:01
SapanShah7-Jul-03 18:01 
GeneralRe: Unbound Column in Windows Forms Pin
Esteves8-Jul-03 15:50
Esteves8-Jul-03 15:50 
GeneralRe: Unbound Column in Windows Forms Pin
SapanShah8-Jul-03 17:33
SapanShah8-Jul-03 17:33 
GeneralRe: Unbound Column in Windows Forms Pin
Esteves9-Jul-03 6:29
Esteves9-Jul-03 6:29 
GeneralRe: Unbound Column in Windows Forms Pin
Esteves9-Jul-03 6:36
Esteves9-Jul-03 6:36 
GeneralMy Search For An Unbound Grid Pin
chetkloss16-Nov-02 16:49
chetkloss16-Nov-02 16:49 
GeneralRe: My Search For An Unbound Grid Pin
Esteves16-Nov-02 17:34
Esteves16-Nov-02 17:34 
GeneralRe: My Search For An Unbound Grid Pin
chetkloss16-Nov-02 17:51
chetkloss16-Nov-02 17:51 
GeneralRe: My Search For An Unbound Grid Pin
Esteves17-Nov-02 7:38
Esteves17-Nov-02 7:38 
GeneralRe: My Search For An Unbound Grid Pin
geoff_simpson21-Nov-02 14:37
geoff_simpson21-Nov-02 14:37 
QuestionHow I Can Create Editable DropDownList in ASP.NET Web Application Pin
Piyush K Patel16-Mar-08 20:48
professionalPiyush K Patel16-Mar-08 20:48 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.