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

Column Manipulation

11 Answers 256 Views
Grid
This is a migrated thread and some comments may be shown as answers.
SDI
Top achievements
Rank 1
SDI asked on 07 Jan 2012, 10:28 PM
Hello Telerik,

I have seen all kinds of ways to code for changing up column types, setting data bound combos, etc. But what is the proper procedure for changing up a column in code-behind. In other words, which procedures are suppose to use for changing up things. 

Here is the scenario:

I have a grid with AutoGenerated fields from a code behind data tier that returns a data table for a grid. Now this data may need a mask, or a drop down combo, or a numeric text control for UI enhancements in the grid. Here would be a typical grid for this scenario in the mark-up:

<telerik:RadGrid runat="server" ID="RadGrid1" AllowMultiRowSelection="true" AllowMultiRowEdit="true" EnableViewState="true" ViewStateMode="Enabled">
 
<MasterTableView DataKeyNames="ProgramPhoneListId, ProgramId, IsPrimary, AliasName, PhoneNumber, Extension, PhoneTypeValuesId" ClientDataKeyNames="ProgramPhoneListId, ProgramId, IsPrimary, AliasName, PhoneNumber, Extension, PhoneTypeValuesId" NoMasterRecordsText="Please click the 'Add' button to add a phone number..." EditMode="InPlace" AutoGenerateColumns="true" TableLayout="Fixed">
 
<Columns>
<telerik:GridClientSelectColumn UniqueName="ClientSelectColumn" CommandName="Select" />
</Columns>
 
</MasterTableView>
 
<ClientSettings EnableRowHoverStyle="true">
<Selecting AllowRowSelect="true" />
<Scrolling AllowScroll="true" UseStaticHeaders="true" />
</ClientSettings>
 
</telerik:RadGrid>

Now what events would be needed in the code-behind for changing things up to use the UI enhancements as I mentioned above. For instance: (in order of firing precedence)

DataBinding:
I use this for "EditIndexes" on the grid, no problems here with what is supposed to be here.

ColumnCreated:
Its works for changing the header, style, text, width, etc., but what if 'PhoneTypeValuesId' is just integers and needs another data table for its data. Do I need to change it to a GridBoundColumn in this event? If 'PhoneNumber' needs a mask to I change it to a RadMaskedColumn in this event and add the DisplayMask - "(###) ###-####" ? 

ItemCreated:
Ok, this is when the rows are created and gets fired for each row if I am not mistaken. So in this event you can cast GridItems to RadMaskedTextBox, RadNumericTextBox and others, but do you have to if you set the columns up in the ColumnCreated event? When I try to change the type to a RadMaskedTextBox it errors out unable to cast type of the TextBox to RadMaskedTextBox. Now is this because something else has to happen to the cell? What about the drop down in this event? Do you change the cell to a RadComboBox? 

ItemDataBound:
This event can fill in my GridDropDownColumn, but what needs to be setup before this? When the GetColumnEditor of the 'PhoneTypeValuesId' is trying to change the type to a GridDropDownColumnEditor it again fails on the cast object of type. I feel like something is supposed to be done before this tries to add the datasource, datatextfield, etc. to the GridDropDownColumnEditor, if it can't change the type this will not work. 

PreRender:
Basically I use this to change up the controls in the grid properties, width, borderstyle, etc. Also used to attach attributes for events to the TextBox for editing. No real issues here. 

Now I've been through the documentation and it wasn't in too much detail with different scenarios, it was a lot of mark-up usage which doesn't apply much to my situation.

Can someone please elaborate on this and maybe a small example of what should get put into each event? How to achieve the desired results in the grid. I really appreciate it!

SDI

11 Answers, 1 is accepted

Sort by
0
SDI
Top achievements
Rank 1
answered on 07 Jan 2012, 11:23 PM
I did find this, which helped explain the proper placing of code.

http://www.telerik.com/help/aspnet-ajax/grid-distinguish-differences-between-itemcreated-itemdatabound.html 

...but as the errors above I mentioned are happening here when trying to cast the control type TextBox to the RadNumericTextBox or a RadMaskedTextBox in the ItemCreated event. Is there something else needed here before its converted?

"Cannot convert to 'Class RadMaskedTextBox'."

Thanks!
SDI


0
Shinu
Top achievements
Rank 2
answered on 09 Jan 2012, 05:34 AM
Hello,

Since you are setting the property AutoGenerateColumns as true, you can customize the columns in ColumnCreated event.
C#:
protected void RadGrid1_ColumnCreated(object sender, GridColumnCreatedEventArgs e)
{
 if (e.Column.UniqueName == "Name")
 {//code here
 }
}

-Shinu.
0
SDI
Top achievements
Rank 1
answered on 11 Jan 2012, 11:29 PM
Hello Shinu

So, if ColumnCreated event is where all this happens, how can you change your column to a GridDropDown or a RadMask? I didn't think this was possible at that point. I know I can do other things here, obviously off the e.Column, but changing the type of a GridBoundColumn to a GridMaskColumn fails. You don't do anything in the ColumnCreated like what I explained below. The itemdatabound is where this is suppose to happen. Changing type is always failing. How do you set a GridMaskColumn, GridNumericColumn, GridDropDownColumn in the server-side code if I have server-side data with auto-generated columns? This is the issue.

Thanks
SDI
0
SDI
Top achievements
Rank 1
answered on 16 Jan 2012, 02:02 PM
Telerik,

Can you let me know how you get a dropdown, mask, or any other rad control as a cell in the grid if its autogenerated data? I looked through the samples and documentation and it doesn't explain this very well or at all with autogenerated=true. Can someone from Telerik please explain, or at least send me a link to how this is accomplished? There is a ton of help with client-side coding but I cant find server-side help with for this scenario.

Thanks a bunch!
SDI
0
Tsvetina
Telerik team
answered on 18 Jan 2012, 09:49 AM
Hi,

The auto-generated columns feature of RadGrid does not support changing the type of the columns. Based on the datatype, the control will generate:
  • GridBoundColumn for string fields

  • GridCheckBoxColumn for boolean fields

  • GridDateTimeColumn for datetime fields

  • GridNumericColumn for numeric fields

If you want to have more control over the column types and still create them dynamically, you could switch to programmatic creation of RadGrid, following the guidelines from this topic:
http://www.telerik.com/help/aspnet-ajax/grid-changing-structure-dynamically.html

All the best,
Tsvetina
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
0
SDI
Top achievements
Rank 1
answered on 19 Jan 2012, 04:31 AM
Tsventia,

I dont think I made myself very clear. I have a data source that fills in a grid on load, in code behind. One of the fields is an integer that points its value to another field in another table. All I want to do is have that column be a DropDown with the values and integers from the table that field points to so the user can just choose a different value.

<telerik:RadGrid runat="server" ID="RadGridProgramPhone" Width="495px" Height="160"
AllowMultiRowSelection="true" AllowMultiRowEdit="true" EnableViewState="true" ViewStateMode="Enabled">
<MasterTableView DataKeyNames="ProgramPhoneListId"
ClientDataKeyNames="ProgramPhoneListId, ProgramId, IsPrimary, AliasName, PhoneNumber, Extension, PhoneTypeValuesId"
NoMasterRecordsText="Please click the 'Add' button to add a program phone number..."
EditMode="InPlace" AutoGenerateColumns="true" TableLayout="Fixed">
<Columns>
<telerik:GridClientSelectColumn UniqueName="ClientSelectColumn" CommandName="Select" />
</Columns>
</MasterTableView>
<ClientSettings EnableRowHoverStyle="true">
<Selecting AllowRowSelect="true" />
<Scrolling AllowScroll="true" UseStaticHeaders="true" />
</ClientSettings>
</telerik:RadGrid>


The field "PhoneTypeValuesId" is an integer which is a key in another table with the actual text value.
ie - 1 - cell
2 - house
3 - pager
.
I would need a dropdown in the grid for that column for the user to pick something else. Is this possible from the server-side? Just as well the phonenumber field would be a mask for phone numbers. How can you accomplish this with the grid?

Thanks
SDI
0
Tsvetina
Telerik team
answered on 19 Jan 2012, 12:09 PM
Hello,

As I said in my previous reply, this is not possible with auto-generated columns. As their name suggests, they are automatically generated. You could do this if you are manually creating the columns (which you can do in code-behind) and specifying their types.

Greetings,
Tsvetina
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
0
SDI
Top achievements
Rank 1
answered on 29 Jan 2012, 08:09 PM
Hello Telerik,

I was able to achieve the GridDropDownColumn functionality on the editcommand, but not when it loads. The grid is bound to a datatable with a integer field that is a index pointer to the value in another datatable. When I click edit the dropdown displays the values I want from the datatable. When I select it and click updatecommand the table now displays the correct value, as well as the rest ot the rows. At the load of the page they all displayed the "&nbsp;". I have the code for the ItemDataBound, do I need something else for the column to look up the value when it loads? I am also having a problem with the RadMask, when it edit mode it doesnt let me type anything in it.

<telerik:RadGrid runat="server" ID="RadGridProgramPhone" GridLines="None" EnableViewState="true">
                                            <MasterTableView DataKeyNames="ProgramPhoneListId, ProgramId" Width="100%" Height="100%" AutoGenerateColumns="false" CommandItemDisplay="Top" EditMode="InPlace" TableLayout="Fixed" NoMasterRecordsText="Please click the 'Add' button to add a program phone number...">
                                                <Columns>

<telerik:GridDropDownColumn DataField="PhoneTypeValuesId" ListTextField="CategoryValue" ListValueField="CategoryValueId" DataType="System.Int64" ColumnEditorID="PhoneTypeValuesIdEditor" HeaderText="Type" DropDownControlType="RadComboBox" UniqueName="PhoneTypeValuesId" ItemStyle-Width="20%" HeaderStyle-Width="20%" ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center" EditFormColumnIndex="4" />
 
 
<telerik:GridDropDownListColumnEditor ID="PhoneTypeValuesIdEditor" runat="server" DropDownStyle-Width="100%" />

<telerik:GridMaskedColumn DataField="PhoneNumber" DataType="System.String" ColumnEditorID="PhoneNumberEditor" HeaderText="Number" UniqueName="PhoneNumber" ItemStyle-Width="20%" HeaderStyle-Width="20%" EditFormColumnIndex="2" />
 
 
 
<telerik:GridMaskedColumnEditor ID="PhoneNumberEditor" runat="server" MaskedTextBox-Width="95%" MaskedTextBox-PromptChar="_" MaskedTextBox-DisplayMask="(###) ### - ####" MaskedTextBox-SelectionOnFocus="SelectAll" />



Protected Sub RadGridProgramPhone_ItemDataBound(sender As Object, e As Telerik.Web.UI.GridItemEventArgs) Handles RadGridProgramPhone.ItemDataBound
 
        Try
 
            If (TypeOf e.Item Is GridEditableItem AndAlso CType(e.Item, GridEditableItem).IsInEditMode) Then
 
                Dim myEditedItem As GridEditableItem = TryCast(e.Item, GridEditableItem)
                Dim myEditManager As GridEditManager = myEditedItem.EditManager
 
                Dim myColumnEditor As GridDropDownColumnEditor
                myColumnEditor = TryCast(myEditManager.GetColumnEditor("PhoneTypeValuesId"), GridDropDownColumnEditor)
 
                If myColumnEditor IsNot Nothing Then
                    If Me.m_PhoneNumberTypesDT Is Nothing Then Me.m_PhoneNumberTypesDT = Me.GetPhoneNumberTypesDT()
                    myColumnEditor.DataSource = Me.m_PhoneNumberTypesDT
                    myColumnEditor.DataTextField = "CategoryValue"
                    myColumnEditor.DataValueField = "CategoryValueId"
                    myColumnEditor.DataBind()
                End If
 
                ' set the item tooltips
                'For x As Integer = 0 To Editor.Items.Count - 1
                'Me.RadComboBoxProgramStatus.Items(x).ToolTip = String.Concat(Editor.Rows(x)("CategoryValue").ToString(), Environment.NewLine(), Editor.Rows(x)("Description").ToString())
                'Next
 
            End If
 
        Catch ex As Exception
            Me.ShowError(ex.Message, String.Concat("RadGridProgramPhone.ItemDataBound - ", ex.Source), ex.StackTrace)
        End Try
 
    End Sub
Thanks
SDI
0
Shinu
Top achievements
Rank 2
answered on 30 Jan 2012, 05:53 AM
Hello SDI,

Please have a look into the following forum to achieve your requirement. I hope it will help.

Rad Grid Not Showing DropDownEditable Field value

-Shinu.
0
SDI
Top achievements
Rank 1
answered on 30 Jan 2012, 04:45 PM
Thanks for the information Shinu. But I don't see how that would work in my scenario. The dropdowncolumn does not have a value in it - PhoneTypeValuesId has a "&nbsp;" data at this point. I thought ItemCreated had to have something set for the dropdowncolumn. It is not databound unless it is in edit mode. Remember this is in display mode.

How about a template column to set the value that gets filled in from the datatable somehow. This seems like a common task, where you hold an ID of the value and have a "lookup" table to display the string bound to the dropdowncolumn data. Telerik, is this not supported easily enough, w/o having to create another column for display and the editing. I would think that I could bind the dropdowncolumn to a datatable then it would have its values so when the data gets passed on itemcreated it would know which item in the dropdowncolumn to display from its ID integer.

So how it should work is - when the columns are created, you bind a datatable to the dropdowncolumn, setting the DataTextField ("CategoryValue") and DataValueField ("CategoryId") from the given datatable. Then when the grid gets its data and in the ItemCreated event it has the integer column ("PhoneTypeValuesId") that corresponds to the DataValueField and it shows the DataTextField (ie: "PhoneTypeValuesId" points to "CategoryId" and displays "CategoryValue". This should be seamless, especially when using a properly designed relational database, or did we just swing and miss on understanding how this can be designed with Telerik controls? Is there an example of this or maybe a snippet to look at here, again this is common way to setup any type of dropdown to get the proper text, we don't store the text we store a pointer to the text in another table.

Thanks,
SDI


0
Tsvetina
Telerik team
answered on 02 Feb 2012, 11:06 AM
Hello,

RadGrid is a UI component and displays the data you pass to it, it cannot and is not designed to automatically query other tables based on DB relations. You can achieve your requirement with a few lines of custom code however.
Here is a sample declaration of a template column that I will use in the code snippet below:
<telerik:GridTemplateColumn UniqueName="LookupCol">
    <ItemTemplate>
        <asp:Label ID="Label1" runat="server">
        </asp:Label>
    </ItemTemplate>
    <EditItemTemplate>
        <telerik:RadComboBox ID="RadComboBox1" runat="server">
        </telerik:RadComboBox>
    </EditItemTemplate>
</telerik:GridTemplateColumn>

And here is how you can populate a combo, using the row ID and taking the records from a related table:
protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
{
    if (e.Item is GridEditableItem && e.Item.IsInEditMode)
    {
        string key = (e.Item as GridEditableItem).GetDataKeyValue("CustomerID").ToString();
        RadComboBox combo = e.Item.FindControl("RadComboBox1") as RadComboBox;
        combo.DataSource = GetComboData("SELECT CustomerID, CompanyName FROM [Customers]");
        combo.DataValueField = "CustomerID";
        combo.DataTextField = "CompanyName";
        combo.DataBind();
        combo.SelectedValue = key;
    }
}
 
public DataTable GetComboData(string query)
{
    String ConnString = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;
    SqlConnection conn = new SqlConnection(ConnString);
    SqlDataAdapter adapter = new SqlDataAdapter();
    adapter.SelectCommand = new SqlCommand(query, conn);
 
    DataTable myDataTable = new DataTable();
 
    conn.Open();
    try
    {
        adapter.Fill(myDataTable);
    }
    finally
    {
        conn.Close();
    }
 
    return myDataTable;
}

Of course, instead of querying the database each time, you could save a table in ViewState or Session and take the records from it.

You can do the same with the Label in regular mode. You only need to change the ItemDataBound check to simply if(e.Item is GridDataItem).

Kind regards,
Tsvetina
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
SDI
Top achievements
Rank 1
Answers by
SDI
Top achievements
Rank 1
Shinu
Top achievements
Rank 2
Tsvetina
Telerik team
Share this question
or