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

[Solved] Create grid entirely in code behind. Newbie, please help...

2 Answers 163 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Armindo
Top achievements
Rank 1
Armindo asked on 13 Feb 2013, 04:07 PM
Hi Telerik Team,

I'm starting using Telerik, but since this is a first project that i have in hands, i'm having many problems getting started.

I just browser the examples online and i found 2 that would be perfect:

http://demos.telerik.com/aspnet-ajax/grid/examples/dataediting/alleditablecolumns/defaultcs.aspx
http://demos.telerik.com/aspnet-ajax/grid/examples/generalfeatures/columntypes/defaultcs.aspx

The problem is that i need to generate the grid completely in codebehind, so i don't know in advance what the columns would be, how many i will have and what type they will be. I will need to have Text boxes, HTML editors, an image upload field (and show that image on the grid, etc.)

So far i have this, but with many problems:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register TagPrefix="telerik" Namespace="Telerik.Web.UI" Assembly="Telerik.Web.UI" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<head>
    <title>ASP.NET Grid Demo - Automatic Operations</title>
     
    <style>
 
        .MyImageButton
        {
            cursor: hand;
        }
 
        .EditFormHeader td
        {
            font-size: 14px;
            padding: 4px !important;
            color: #0066cc;
        }
 
 
    </style>
</head>
 
<body>
    <form id="form1" runat="server">
    <telerik:RadScriptManager runat="server" ID="RadScriptManager1" />
     
    <telerik:RadFormDecorator ID="QsfFromDecorator" runat="server" DecoratedControls="All" EnableRoundedCorners="false" />
    
        <telerik:RadCodeBlock ID="RadCodeBlock1" runat="server">
        <script type="text/javascript">
          
            function RowDblClick(sender, eventArgs)
            {
                sender.get_masterTableView().editItem(eventArgs.get_itemIndexHierarchical());
            }
 
            function gridCreated(sender, args)
            {
                if (sender.get_editIndexes && sender.get_editIndexes().length > 0)
                {
                    document.getElementById("OutPut").innerHTML = sender.get_editIndexes().join();
                }
                else
                {
                    document.getElementById("OutPut").innerHTML = "";
                }
            }
 
        </script>
        </telerik:RadCodeBlock>
        <telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">
        <AjaxSettings>
            <telerik:AjaxSetting AjaxControlID="RadGrid1">
                <UpdatedControls>
                    <telerik:AjaxUpdatedControl ControlID="RadGrid1" LoadingPanelID="RadAjaxLoadingPanel1"></telerik:AjaxUpdatedControl>
                    <telerik:AjaxUpdatedControl ControlID="RadWindowManager1"></telerik:AjaxUpdatedControl>
                </UpdatedControls>
            </telerik:AjaxSetting>
        </AjaxSettings>
    </telerik:RadAjaxManager>
 
    <telerik:RadAjaxLoadingPanel lID="RadAjaxLoadingPanel1" runat="server"></telerik:RadAjaxLoadingPanel>
 
    <telerik:RadGrid ID="RadGrid1" GridLines="None" runat="server" AllowAutomaticDeletes="True" AllowAutomaticInserts="True" PageSize="10"
        AllowAutomaticUpdates="True" AllowPaging="True" AutoGenerateColumns="False" OnItemUpdated="RadGrid1_ItemUpdated" OnItemDeleted="RadGrid1_ItemDeleted"
        OnItemInserted="RadGrid1_ItemInserted" OnDataBound="RadGrid1_DataBound">
 
        <PagerStyle Mode="NextPrevAndNumeric"></PagerStyle>
 
        <MasterTableView Width="100%" CommandItemDisplay="TopAndBottom" HorizontalAlign="NotSet" AutoGenerateColumns="False">
         
            <Columns>
 
                <telerik:GridEditCommandColumn ButtonType="ImageButton" UniqueName="EditCommandColumn">
                    <ItemStyle CssClass="MyImageButton"></ItemStyle>
                </telerik:GridEditCommandColumn>
 
            </Columns>
 
 
 
 
            <EditFormSettings ColumnNumber="2" CaptionDataField="Objecto_ID" CaptionFormatString="Edit properties of Product {0}"
                InsertCaption="New Product">
                <FormTableItemStyle Wrap="False"></FormTableItemStyle>
                <FormCaptionStyle CssClass="EditFormHeader"></FormCaptionStyle>
                <FormMainTableStyle GridLines="None" CellSpacing="0" CellPadding="3"
                    Width="100%"></FormMainTableStyle>
                <FormTableStyle CellSpacing="0" CellPadding="2" Height="110px">
                </FormTableStyle>
                <FormTableAlternatingItemStyle Wrap="False"></FormTableAlternatingItemStyle>
                <EditColumn ButtonType="ImageButton" InsertText="Insert Order" UpdateText="Update record"
                    UniqueName="EditCommandColumn1" CancelText="Cancel edit">
                </EditColumn>
                <FormTableButtonRowStyle HorizontalAlign="Right" CssClass="EditFormButtonRow"></FormTableButtonRowStyle>
            </EditFormSettings>
        </MasterTableView>
        <ClientSettings>
            <ClientEvents OnRowDblClick="RowDblClick" OnGridCreated="gridCreated"></ClientEvents>
        </ClientSettings>
    </telerik:RadGrid>
 
 
 
    <telerik:GridTextBoxColumnEditor ID="GridTextBoxColumnEditor1" runat="server" TextBoxStyle-Width="200px"></telerik:GridTextBoxColumnEditor>
    <telerik:GridTextBoxColumnEditor ID="GridTextBoxColumnEditor2" runat="server" TextBoxStyle-Width="150px"></telerik:GridTextBoxColumnEditor>
    <telerik:GridDropDownListColumnEditor ID="GridDropDownColumnEditor1" runat="server" DropDownStyle-Width="110px"></telerik:GridDropDownListColumnEditor>
    <telerik:GridNumericColumnEditor ID="GridNumericColumnEditor1" runat="server" NumericTextBox-Width="40px"></telerik:GridNumericColumnEditor>
    <telerik:RadWindowManager ID="RadWindowManager1" runat="server"></telerik:RadWindowManager>
 
 
    <br />
 
    </form>
</body>
</html>

And the code behind:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;
using Telerik.Web.UI;
 
public partial class _Default : System.Web.UI.Page
{
 
    SqlDataSource SqlDataSource1 = new SqlDataSource();
    SqlDataSource SqlDataSource2 = new SqlDataSource();
 
 
    protected void Page_Init(object sender, EventArgs e) {
 
 
         
    }
 
    
    protected void Page_Load(object sender, EventArgs e)
    {
 
 
        SqlDataSource1.ConnectionString = "Data Source=DATA_SOURCE;Initial Catalog=DATABASE;user=USER;password=PASS;Integrated Security=false; Connection Timeout=30";
        SqlDataSource1.SelectCommand = "SELECT Objecto_ID, fk_Designacao, Descricao FROM Objecto";
         
        RadGrid1.MasterTableView.DataKeyNames = new string[] { "Objecto_ID" };
        RadGrid1.DataSource = SqlDataSource1;
        RadGrid1.Skin = "Metro";
 
 
        SqlDataSource2.ConnectionString = "Data Source=DATA_SOURCE;Initial Catalog=DATABASE;user=USER;password=PASS;Integrated Security=false; Connection Timeout=30";
        SqlDataSource2.SelectCommand = "SELECT Designacao FROM Designacao";
 
        RadGrid1.Columns.Clear();
 
 
        GridEditCommandColumn c_Edit = new GridEditCommandColumn();
        c_Edit.UniqueName = "EditCommandColumn";
        RadGrid1.MasterTableView.Columns.Add(c_Edit);
 
 
        GridBoundColumn c_gridBound = new GridBoundColumn();
        c_gridBound.DataField = "Objecto_ID";
        c_gridBound.HeaderText = "Objecto ID";
        c_gridBound.SortExpression = "Objecto_ID";
        c_gridBound.UniqueName = "Objecto_ID";
        c_gridBound.ColumnEditorID = "GridTextBoxColumnEditor1";
        RadGrid1.MasterTableView.Columns.Add(c_gridBound);
 
 
        GridDropDownColumn c_gridBoundDrop = new GridDropDownColumn();
        c_gridBoundDrop.DropDownControlType = GridDropDownColumnControlType.RadComboBox;
        c_gridBoundDrop.DataField = "fk_Designacao";
        c_gridBoundDrop.HeaderText = "Designacao Objecto";
        c_gridBoundDrop.SortExpression = "fk_Designacao";
        c_gridBoundDrop.ListTextField = "fk_Designacao";
        c_gridBoundDrop.ListValueField = "fk_Designacao";
        c_gridBoundDrop.UniqueName = "fk_Designacao";
        c_gridBoundDrop.ColumnEditorID = "GridDropDownColumnEditor1";
        RadGrid1.MasterTableView.Columns.Add(c_gridBoundDrop);
 
 
        GridHTMLEditorColumn c_HTML = new GridHTMLEditorColumn();
        c_HTML.DataField = "Descricao";
        c_HTML.SortExpression = "Descricao";
        c_HTML.UniqueName = "Descricao";
        c_HTML.ColumnEditorID = "Descricao";
        c_HTML.HeaderText = "Descricao";
        c_HTML.FooterText = "HTMLEditorColumn footer";
        c_HTML.HeaderStyle.Width = 200;
        RadGrid1.MasterTableView.Columns.Add(c_HTML);
 
 
        GridButtonColumn c_delete = new GridButtonColumn();
        //c_delete = new ImageButton();
        c_delete.ConfirmText = "Delete this product?";
        c_delete.ConfirmTitle = "Delete";
        //c_delete.ButtonType = c_delete_button;
        //c_delete.ConfirmDialogType = RadWindow;
        c_delete.CommandName = "Delete";
        c_delete.Text = "Delete";
        c_delete.UniqueName = "DeleteColumn";
        RadGrid1.MasterTableView.Columns.Add(c_delete);
 
         
    }
 
    protected void RadGrid1_ItemUpdated(object source, Telerik.Web.UI.GridUpdatedEventArgs e)
    {
        GridEditableItem item = (GridEditableItem)e.Item;
        String id = item.GetDataKeyValue("Objecto_ID").ToString();
 
        if (e.Exception != null)
        {
            e.KeepInEditMode = true;
            e.ExceptionHandled = true;
            SetMessage("Product with ID " + id + " cannot be updated. Reason: " + e.Exception.Message);
        }
        else
        {
            SetMessage("Product with ID " + id + " is updated!");
        }
    }
 
    protected void RadGrid1_ItemInserted(object source, GridInsertedEventArgs e)
    {
        if (e.Exception != null)
        {
            e.ExceptionHandled = true;
            SetMessage("Product cannot be inserted. Reason: " + e.Exception.Message);
        }
        else
        {
            SetMessage("New product is inserted!");
        }
    }
 
    protected void RadGrid1_ItemDeleted(object source, GridDeletedEventArgs e)
    {
        GridDataItem dataItem = (GridDataItem)e.Item;
        String id = dataItem.GetDataKeyValue("Objecto_ID").ToString();
 
        if (e.Exception != null)
        {
            e.ExceptionHandled = true;
            SetMessage("Product with ID " + id + " cannot be deleted. Reason: " + e.Exception.Message);
        }
        else
        {
            SetMessage("Product with ID " + id + " is deleted!");
        }
    }
 
    protected void RadioCheckedChanged(object sender, System.EventArgs e)
    {
        //switch ((sender as RadioButton).ID)
        //{
        //    case "RadioButton1":
        //        {
        //            RadGrid1.MasterTableView.EditMode = GridEditMode.EditForms;
        //            RadioButton2.Checked = false;
        //            break;
        //        }
        //    case "RadioButton2":
        //        {
        //            RadGrid1.MasterTableView.EditMode = GridEditMode.InPlace;
        //            RadioButton1.Checked = false;
        //            break;
        //        }
        //}
        RadGrid1.Rebind();
    }
    protected void CheckboxCheckedChanged(object sender, System.EventArgs e)
    {
                     
        //RadGrid1.AllowMultiRowEdit = CheckBox1.Checked;
                     
        RadGrid1.Rebind();
    }
 
    private void DisplayMessage(string text)
    {
        RadGrid1.Controls.Add(new LiteralControl(string.Format("<span style='color:red'>{0}</span>", text)));
    }
 
    private void SetMessage(string message)
    {
        gridMessage = message;
    }
 
    private string gridMessage = null;
    protected void RadGrid1_DataBound(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(gridMessage))
        {
            DisplayMessage(gridMessage);
        }
    }
 
    private void RadGrid1_ItemDataBound(object sender, Telerik.Web.UI.GridItemEventArgs e)
    {
         
    
}

The Objecto table as a foreign key ft_Designacao, that is on Designacao table. So, when in edit mode i should have a dropdownlist with all the values from Designacao, but with the correct one selected for a specific record.

My problems:

- the RadAjaxLoadingPanel doesn't show when i click something
- the GridDropDownColumn doesn't show the value on the grid and on edit mode (it's empty)
- when i'm on edit mode on a record, i cannot click another record to edit it
- when i'm on edit mode on a record, the save and cancel buttons don't work (the events are not fired...)
- the HTML editor doesn't have the value that is shown on the grid and i can't write on it
- i still need to add an image to the grid and the option to upload a file on edit mode

I'm really desperating :( Telerik has many great examples but i can't find any with all the features i need. I need to completely generate a grid, with an unknow column cound, unknow column type, all this in code behind. I need to have text boxes, drop dow lists, check boxes, text validator boxes (for numbers for instance), HTML editor areas, image upload, etc. Also, the image needs to be shown on the grid.

This is my first project, and i have a really short deadline. And i'm really desperating because i've spend days broswing samples and i still have nothing, as this is a bit daunting to me, to start from scratch.

So, if someone would be kind enought to give a look at my code, point me on the right direction, or, the ideal, to send me a simple sample template where all this is created and works on code behind, i would be extremely grateful.

Thank you so much in advance!

2 Answers, 1 is accepted

Sort by
0
Armindo
Top achievements
Rank 1
answered on 14 Feb 2013, 12:11 PM
Anyone, please? I'm completely lost, confused, and i really don't know where to start... :(
0
Kostadin
Telerik team
answered on 18 Feb 2013, 11:17 AM
Hello Armindo,

I would suggest you start looking at the following help article where is described how you could create a grid programmatically. Also at the following help topic you could find how to change the grid structure dynamically. Additionally this demo demonstrated how you could implement a ComboBox in RadGrid. Note that if you want to show the loading panel of the RadAjaxLoadingPanel you have to set a skin. For instance.
<telerik:RadAjaxLoadingPanel ID="RadAjaxLoadingPanel1" runat="server" Skin="Vista"></telerik:RadAjaxLoadingPanel>

I hope this information is enough to start creating your project.

Greetings,
Kostadin
the Telerik team
If you want to get updates on new releases, tips and tricks and sneak peeks at our product labs directly from the developers working on the RadControls for ASP.NET AJAX, subscribe to their blog feed now.
Tags
Grid
Asked by
Armindo
Top achievements
Rank 1
Answers by
Armindo
Top achievements
Rank 1
Kostadin
Telerik team
Share this question
or