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

[Solved] Dynamically added row, no controls???

1 Answer 113 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Ebony Gainey
Top achievements
Rank 1
Ebony Gainey asked on 31 Dec 2009, 12:05 AM
I have a grid that allows the user to add a new row to the list of objects that is saved in view state.  The new row is added correctly, I can see them and they are populated.  When the user clicks the save button, I have a method to get loop through all the rows in the grid and save the values off to an object, everything works fine EXCEPT when I try to find the controls on my dynamically added row, it can't find any of them...Am I missing something.

So to summarize:
User clicks button - add a new object to the list of objects in viewstate, set the datasource = new list of objects
User enters data and clicks the "save question" button - Loop through all of the form data and the grid and collect values to save to object.  This is where I get the error because it can't seem to find the controls on my dynamic row.  I have attached the necessary code.

 

<telerik:RadGrid ID="RadGrid1" runat="server" PageSize="10" Skin="Default" GridLines="None" 
                                        AllowSorting="True" AllowMultiRowSelection="False" AllowPaging="True" AllowMultiRowEdit="true" 
                                        ShowGroupPanel="True" GroupingEnabled="False" EnableLinqExpressions="false"   
                                        BorderWidth="1px" BorderColor="Gainsboro" 
                                        OnPreRender="RadGrid1_PreRender" OnNeedDataSource="RadGrid1_NeedDataSource"   
                                        OnItemCommand="RadGrid1_ItemCommand" OnItemDataBound="RadGrid1_ItemDataBound"   
                                        OnInsertCommand="RagGrid1_InsertCommand" 
                                    > 
                                        <PagerStyle Mode="NextPrevNumericAndAdvanced" CssClass="tbl"></PagerStyle> 
                                        <ClientSettings ReorderColumnsOnClient="false" AllowDragToGroup="true" AllowColumnsReorder="false">  
                                            <Selecting AllowRowSelect="True"></Selecting> 
                                            <ClientEvents OnRowDblClick="RowDblClick" /> 
                                            <Scrolling AllowScroll="True" UseStaticHeaders="True" SaveScrollPosition="False" 
                                                ScrollHeight="250" /> 
                                        </ClientSettings> 
                                          
                                        <MasterTableView DataKeyNames="FileChecklistReferenceId" EditMode="InPlace" TableLayout="Fixed" AllowFilteringByColumn="true" AutoGenerateColumns="false" CommandItemDisplay="Top">  
                                            <EditItemStyle Font-Bold="true"/>  
                                            <Columns> 
                                                <telerik:GridTemplateColumn UniqueName="Checklist" HeaderText="Checklist">  
                                                    <ItemTemplate> 
                                                        <%#Eval("FileType")%> 
                                                    </ItemTemplate> 
                                                    <EditItemTemplate> 
                                                        <asp:DropDownList ID="ddlFileType" runat="server" CssClass="ddl" /> 
                                                        <asp:RequiredFieldValidator ID="rfvFileType" runat="server" ControlToValidate="ddlFileType" Text="*" ErrorMessage="Please Select a Checklist" SetFocusOnError="True" InitialValue="-1" ValidationGroup="SaveGroup" /> 
                                                    </EditItemTemplate> 
                                                </telerik:GridTemplateColumn> 
                                                <telerik:GridBoundColumn DataField="Reference" HeaderText="Reference" ItemStyle-Font-Bold="true" /> 
                                                <telerik:GridNumericColumn UniqueName="Threshold" ConvertEmptyStringToNull="true" DataType="System.Double" HeaderText="Threshold" NumericType="Currency" DataField="Threshold" /> 
                                                <%--<telerik:GridEditCommandColumn HeaderStyle-Width="80px"  />--%> 
                                            </Columns> 
                                        </MasterTableView> 
                                    </telerik:RadGrid> 

Code to add new row:
        protected void RadGrid1_ItemCommand(object sender, GridCommandEventArgs e)  
        {  
            if (e.CommandName == RadGrid.InitInsertCommandName)  
            {  
                //Get the filechecklist from Viewstate  
                List<FileChecklist> fileList = (List<FileChecklist>)ViewState["Checklists"];  
                //Add a new file checklist object to it  
                fileList.Add(new FileChecklist());  
                //Save it back to ViewState  
                ViewState["Checklists"] = fileList;  
 
                e.Canceled = true;  
                System.Collections.Specialized.ListDictionary newValues = new System.Collections.Specialized.ListDictionary();  
                //the values set here must match the values types declared in the class (Model) otherwise, an exception will be thrown  
                //if any of the values do not "match" you will get a "Specified cast is not valid." exception  
                newValues["FileTypeId"] = -1;  
                newValues["FileChecklistReferenceId"] = -1;  
                newValues["Threshold"] = 0.0;  
 
                //Insert the item and rebind  
                e.Item.OwnerTableView.InsertItem(newValues);  
            }  
        } 

Data Source:
        protected void RadGrid1_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)  
        {  
            RadGrid rg = (RadGrid)sender;  
 
            List<FileChecklist> fileList = (List<FileChecklist>)ViewState["Checklists"];  
            rg.DataSource = fileList;  
        } 

Code to get grid row values
        private void SaveFileChecklists(ref Question data)  
        {  
            List<FileChecklist> newList = new List<FileChecklist>();  
 
            foreach (GridDataItem row in RadGrid1.MasterTableView.Items)  
            {  
                int id = Convert.ToInt32(row.OwnerTableView.DataKeyValues[row.ItemIndex]["FileChecklistReferenceId"]);  
 
                FileChecklist fc = new FileChecklist();  
                DropDownList ddl = (row.FindControl("ddlFileType"as DropDownList); //null  
                TextBox tb = (row["Reference"].Controls[0] as TextBox); //throws index out of range error  
                RadNumericTextBox rtb = (row["Threshold"].Controls[0] as RadNumericTextBox);//throws index out of range error  
            }  
            data.FileChecklists = newList;  
        } 

WHAT AM I MISSING???

1 Answer, 1 is accepted

Sort by
0
Mira
Telerik team
answered on 04 Jan 2010, 03:33 PM
Hi Ebony,

Please take a look at the Changing the grid structure dynamically on postback help topic to see how to add columns dynamically in RadGrid.
You must ensure that the entire grid, including its columns collection, is modified on Page_Init so that the control ViewState remains consistent. Also, you should set the EnableColumnViewState property to False, so that the grid knows that the columns may vary at some stage of the page lifecycle.

I hope this helps.

Regards,
Mira
the Telerik team

Instantly find answers to your questions on the new Telerik Support Portal.
Watch a video on how to optimize your support resource searches and check out more tips on the blogs.
Tags
Grid
Asked by
Ebony Gainey
Top achievements
Rank 1
Answers by
Mira
Telerik team
Share this question
or