This is a migrated thread and some comments may be shown as answers.

[Solved] Need help with dynamically added columns

1 Answer 211 Views
Grid
This is a migrated thread and some comments may be shown as answers.
David
Top achievements
Rank 1
David asked on 03 Mar 2008, 04:28 PM
Ok, so I'll start off with what I'm having issues with and then paste code below.

I have a RadGrid that allows for grouping and sorting.  I have the RadGrid tied to a DataSet that is stored in ViewState.

I need to manually add columns in the code behind so that I can allow some to be hidden and also becasue we allow the users to add extra columns from the database.

After a lot of playing I thought I had it working, but now my problem is that when sorting the column headers go away.

The issue is, and I have no idea why it's designed this way, but on every single post back, the Column collection in the RadGrid keeps the column count and the number of columns there, but it clears all the properties on that column so that there is no header text, there is no DatatField property, there is DataType.

I just need to know why this does this and how I can get around it, it's been like 2 full days of frustration and trying to get those columns to be persistant across post backs.

RadGrid in aspx:
                        <telerik:RadGrid ID="RadGrid1" runat="server" Skin="Office2007" Width="100%" BorderWidth="0px" 
                            GridLines="None" ShowGroupPanel="True" AllowSorting="True" OnNeedDataSource="RadGrid1_NeedDataSource" 
                            OnItemCreated="RadGrid1_ItemCreated" OnItemDataBound="RadGrid1_ItemDataBound" 
                            AllowMultiRowSelection="true" AutoGenerateColumns="true">  
                            <ClientSettings AllowColumnsReorder="True" AllowDragToGroup="True" ReorderColumnsOnClient="True">  
                                <Selecting AllowRowSelect="True" /> 
                            </ClientSettings> 
                        </telerik:RadGrid> 
 

A lot of different RadGrid code in the codebehind:
        private DataSet dataSource  
        {  
            get { return (DataSet)ViewState["dataSource"]; }  
            set { ViewState["dataSource"] = value; }  
        }  
        public void RadGrid1_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)  
        {  
            RadGrid1.DataSource = dataSource;  
        }  
        protected void AddColumnsToRadGrid(string columnName, string columnText, Type dataType, bool display)  
        {  
            int test = 0;  
 
            GridBoundColumn newnewBoundColumn = new GridBoundColumn();  
            newBoundColumn.DataType = dataType;  
            newBoundColumn.DataField = columnName;  
            newBoundColumn.HeaderText = columnText;  
            newBoundColumn.Display = display;  
 
            if (_RadGrid1Columns == null)  
            {  
                _RadGrid1Columns = RadGrid1.Columns;  
                test = 1;  
            }  
 
            _RadGrid1Columns.Add(newBoundColumn);  
 
            if (test != 1)  
            {  
                RadGrid1.Columns.Clear();  
 
                foreach (GridColumn gc in _RadGrid1Columns)  
                    RadGrid1.Columns.Add(gc);  
            }  
        }  
        protected void AddColumnsToDataTable(DataTable table, List<JobAttributeValue> _javc)  
        {  
            System.Text.StringBuilder sb = new System.Text.StringBuilder();  
            sb.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");  
            sb.AppendLine("<ArrayOfJobTicket xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">");  
 
            int jrn = 0;  
            bool parseSuccess = false;  
            List<JobAttributeValue> matches = null;  
 
            foreach (DataRow row in table.Rows)  
            {  
                sb.AppendLine("<JobTicket>");  
 
                foreach (DataColumn column in table.Columns)  
                {  
                    sb.AppendLine(string.Format("<{0}>{1}</{2}>", column.ColumnName, row[column.ColumnName].ToString(), column.ColumnName));  
                    if (column.ColumnName == "JobRecordNumber")  
                    {  
                        parseSuccess = int.TryParse(row[column.ColumnName].ToString(), out jrn);  
 
                    }  
                }  
                if (parseSuccess)  
                {  
                    matches = _javc.FindAll(delegate(JobAttributeValue jav) { return jav.JobRecordNumber == jrn; });  
                    if (matches != null)  
                    {  
                        if(matches.Count == 1)  
                        {  
                            foreach (JobAttributeValue Attribute in matches)  
                                sb.AppendLine(string.Format("<{0}>{1}</{2}>", Attribute.AttributeName, Attribute.AttributeValue,Attribute.AttributeName));  
                        }  
                        else  
                            if(matches.Count > 1)  
                            {  
                                matches.Sort(delegate(JobAttributeValue obj1, JobAttributeValue obj2) {return obj1.AttributeValue.CompareTo(obj2.AttributeValue);} );  
                                foreach (JobAttributeValue Attribute in matches)  
                                {  
                                    if (matches.IndexOf(Attribute) == 0)  
                                        sb.AppendLine(string.Format("<{0}>{1}, ", Attribute.AttributeName, Attribute.AttributeValue));  
                                    else  
                                        if (matches.IndexOf(Attribute) == matches.Count - 1)  
                                            sb.Append(string.Format("{0}</{1}>", Attribute.AttributeValue, Attribute.AttributeName));  
                                        else  
                                            sb.Append(string.Format("{0}, ", Attribute.AttributeValue));  
                                }  
                            }  
                    }  
                }  
                else  
                {  
                    sb.AppendLine(string.Format("<{0}></{1}>", _javc[1].AttributeName, _javc[1].AttributeName));  
                }  
 
                sb.AppendLine("</JobTicket>");  
 
            }  
            sb.AppendLine("</ArrayOfJobTicket>");  
            //System.IO.File.WriteAllText("C:\\datasetoutfromSB.xml", sb.ToString());  
              
            TextReader tr = new StringReader(sb.ToString());  
            dataSource.Tables.Clear();  
            dataSource.ReadXml(tr, XmlReadMode.Auto);  
 
            AddColumnsToRadGrid(_javc[0].AttributeName, _javc[0].AttributeName, _javc[0].AttributeValue.GetType(), true);  
        }  
        protected void treeFolders_NodeClick1(object sender, RadTreeNodeEventArgs e)  
        {  
            //folderName = e.Node.Text;  
 
            //RadGrid1.CurrentPageIndex = 0;  
            //RadGrid1.Rebind();  
 
            //labelFrom.Text = String.Empty;  
            //labelDate.Text = String.Empty;  
            //labelSubject.Text = String.Empty;  
            //labelMessage.Text = String.Empty;  
 
            _currentSelectedNode = e.Node;  
 
            if (e.Node.Value != "")  
            {  
                string xmlValue = string.Empty;  
                if (e.Node != null)  
                    xmlValue = e.Node.Value.ToString();  
 
                if (xmlValue.Length > 0)  
                {  
                    JobTicketCollection JobTicketCollection = new JobTicketCollection();  
                    JobTicketCollection = JobTicketService.getJobsByFilter(xmlValue);  
                    if (JobTicketCollection != null)  
                    {  
                        if (JobTicketCollection.Count > 0)  
                        {  
                            Stream _stream = SerializationServices<JobTicketCollection>.SerializeToStream(JobTicketCollection);  
 
                            DataSet _dataSet = new DataSet();  
                            _dataSet.ReadXml(_stream, XmlReadMode.Auto);  
 
                            dataSource = _dataSet;  
 
                            // Add default columns to RadGrid  
                            AddColumnsToRadGrid("JobRecordNumber", "Job Record Number", typeof(Int32), true);  
                        }  
                    }  
                }  
                else  
                {  
                    DataSet _dataSet = new DataSet();  
                    dataSource = _dataSet;  
                }  
 
                RadGrid1.Rebind();  
            }  
        }  
        protected void btnStock_Click(object sender, EventArgs e)  
        {  
            List<int> jobRecNums = new List<int>();  
            foreach (DataRow dataRow in dataSource.Tables[0].Rows)  
                jobRecNums.Add(Convert.ToInt32(dataRow["JobRecordNumber"]));  
 
            List<JobAttributeValue> jobAttributeValueCollection = new List<JobAttributeValue>();  
            jobAttributeValueCollection = JobTicketService.getNewAttribute(jobRecNums, "ImprintLine_color");  
 
            AddColumnsToDataTable(dataSource.Tables[0], jobAttributeValueCollection);  
 
            RadGrid1.Rebind();  
        }  
 


Ok, so in explaination of what's going on in the code behind.
1. The dataSource DataSet is filled when you click on a treeNode.
2. The "JobRecordNumber" is added to the RadGrid Columns
3. When a user clicks the btnStock it goes out and adds a new column to dataSource and fills it with the different stocks.
4. Then it adds that column to the RadGrid.

This is my code, I'm just really wondering where I'm going wrong to make the columns in the RadGrid clear their properties on post back and also, if that's just how it is, how can I fix my code to work for me.

Thanks
Davey

1 Answer, 1 is accepted

Sort by
0
David
Top achievements
Rank 1
answered on 03 Mar 2008, 04:46 PM
Sorry, I though of something else to search the forumns for and found the dynamically building RadGrid.

Weird that you have to add the null column first, then set the properties on it can change all that.
Tags
Grid
Asked by
David
Top achievements
Rank 1
Answers by
David
Top achievements
Rank 1
Share this question
or