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

Radgrid Add new record

21 Answers 2662 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Janaki
Top achievements
Rank 1
Janaki asked on 11 Apr 2012, 04:26 AM
Hi,

I have a radgrid using editmode inplace.  It has the Add new record button and a GridEditcommandcolumn for insert/cancel/edit/update/delete. My end users do not want to click on save for each row. They would like the record to be saved to the database when they click on the Add new record button again and also add another blank row. Can this be done?

Thanks, Jana

21 Answers, 1 is accepted

Sort by
0
Elliott
Top achievements
Rank 2
answered on 11 Apr 2012, 03:28 PM
not really the exact problem, but hitting enter was the same as pressing Insert or Update
<EditFormSettings EditFormType="Template">
    <EditColumn UniqueName="ecColumn" />
    <FormTemplate>
        <table border="0" cellpadding="2" cellspacing="2">
        <tr>
        <td>
            <asp:HiddenField ID="hdnPartNumberID" Value='<%# Bind("PartNumberID") %>' runat="server" />
        </td>
        <td>
            <asp:HiddenField ID="hdnItemID" Value='<%# Bind("ItemID") %>' runat="server" />
        </td>
        </tr>
        <tr>
        <td class="body_text_black_BOLD">Part Number</td>
        <td>
            <asp:TextBox ID="txtPartNumber" Text='<%# Bind("PartNumber") %>' CssClass="body_text_black" runat="server"></asp:TextBox>
            <asp:RequiredFieldValidator ID="rfdPartNumber" ControlToValidate="txtPartNumber" ErrorMessage="Part Number Required" runat="server" />               
        </td>
        </tr>
        <tr>
        <td class="body_text_black_BOLD">Quantity</td>
        <td>
            <telerik:RadNumericTextBox ID="rntbQty" Text='<%# Bind("Qty") %>' MaxLength="5" MaxValue="9999" MinValue="1" CssClass="body_text_black" runat="server" >
                <NumberFormat DecimalDigits="0" />
            </telerik:RadNumericTextBox>
            <asp:RequiredFieldValidator ID="rfQty" ControlToValidate="rntbQty" ErrorMessage="Quantity required" runat="server">
            </asp:RequiredFieldValidator>
        </td>
        </tr>
        <tr>
        <td>
            <asp:LinkButton ID="btnUpdate" Text='<%# IIF(TryCast(Container,GridItem).OwnerTableView.IsItemInserted,"Insert","Update") %>'  CommandName='<%# IIF(TryCast(Container,GridItem).OwnerTableView.IsItemInserted,"PerformInsert","Update") %>' runat="server" />
        </td>
        <td>
            <asp:LinkButton ID="btnCancel" Text="Cancel" CommandName="Cancel" CausesValidation="false" runat="server" />
        </td>
        </tr>
        </table>
    </FormTemplate>
Protected Sub rgAddItems_ItemCreated(ByVal sender As Object, ByVal e As Telerik.Web.UI.GridItemEventArgs) Handles rgAddItems.ItemCreated
    Dim geItem As GridEditableItem = Nothing
    Dim tcPartNumber, tcQty As TableCell
    Dim txtPartNumber As TextBox
    Dim rntbQty As RadNumericTextBox
    Dim btnUpdate As LinkButton
    Dim sb As StringBuilder = Nothing
 
    If e.Item.IsInEditMode Then
    Else
        Exit Sub
    End If
    If TypeOf e.Item Is GridEditableItem Then
    Else
        Exit Sub
    End If
    geItem = DirectCast(e.Item, GridEditableItem)
    tcPartNumber = geItem.Cells(0)
    txtPartNumber = DirectCast(tcPartNumber.FindControl("txtPartNumber"), TextBox)
    btnUpdate = DirectCast(geItem.FindControl("btnUpdate"), LinkButton)
    tcQty = geItem.Cells(1)
    rntbQty = tcQty.FindControl("rntbQty")
    If rntbQty Is Nothing Then
    Else
        sb = New StringBuilder("if(event.which || event.keyCode)")
        sb.Append("{if ((event.which == 13) || (event.keyCode == 13)) ")
        sb.Append("{document.getElementById('")
        sb.Append(btnUpdate.ClientID)
        sb.Append("').click();return false;}} ")
        sb.Append("else {alert(keyCode);return true};")
        rntbQty.Attributes.Add("onkeydown", sb.ToString)
    End If
    If TypeOf e.Item Is IGridInsertItem Then
        If txtPartNumber Is Nothing Then
        Else
            txtPartNumber.Focus()
        End If
    Else
        txtPartNumber.ReadOnly = True
        rntbQty.Focus()
    End If
End Sub
0
Shinu
Top achievements
Rank 2
answered on 11 Apr 2012, 03:53 PM
Hello Janaki,

I am not quite sure about your requirement. If you are using AddNewRecord button it wont show insert/cancel button on each row. It will appear only in the insert form. Anyway if you dont want to show insert/cancel button you can use CommandItemTemplate to customize the buttons.  Also you can use GridEditCommandColumn for edit purpose and for delete option you can use GridButtonColumn with CommandName as 'Delete'. Following is a sample code snippet which implements all this.

ASPX:
<telerik:RadGrid ID="RadGrid1" runat="server"
        AutoGenerateColumns="false" onitemcommand="RadGrid1_ItemCommand"
         onprerender="RadGrid1_PreRender">
     <MasterTableView EditMode="InPlace" CommandItemDisplay="Top" >
         <CommandItemTemplate>
                 <asp:LinkButton ID="add" runat="server" Text="Add new Record" CommandName="InitInsert">         
                </asp:LinkButton>
                <asp:LinkButton ID="save" runat="server" Text="Add new Record" CommandName="PerformInsert"
                    Visible="false"></asp:LinkButton>
          </CommandItemTemplate>
         <Columns>
              <telerik:GridEditCommandColumn UniqueName="EditColumn" ButtonType="LinkButton">          
             </telerik:GridEditCommandColumn>
            <telerik:GridButtonColumn UniqueName="Delete" ButtonType="LinkButton" CommandName="Delete"
                 Text="Delete"></telerik:GridButtonColumn>
            <telerik:GridBoundColumn UniqueName="OrderID" DataField="OrderID" HeaderText="OrderID">
           </telerik:GridBoundColumn>
           <telerik:GridBoundColumn UniqueName="ShipName" DataField="ShipName" HeaderText="ShipName">
            </telerik:GridBoundColumn>
       </Columns>
    </MasterTableView>
</telerik:RadGrid>

C#:
public static string commandName = "";
protected void RadGrid1_ItemCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
{
    if (e.CommandName == "PerformInsert")
    {
        //your code for insertion
        commandName = "PerformInsert";
           
    }
    if (e.CommandName == "InitInsert")
    {
        commandName = "PerformInsert";
 
    }
}
protected void RadGrid1_ItemDataBound(object sender, Telerik.Web.UI.GridItemEventArgs e)
{
    if (e.Item is GridDataInsertItem && e.Item.OwnerTableView.IsItemInserted)
    {
        LinkButton updateButton = (LinkButton)e.Item.FindControl("CancelButton");
        updateButton.Visible = false;
        LinkButton btnInsert = (LinkButton)e.Item.FindControl("PerformInsertButton");
        btnInsert.Visible = false;
        GridCommandItem cmditem = (GridCommandItem)RadGrid1.MasterTableView.GetItems(GridItemType.CommandItem)[0];
        LinkButton saveButton = (LinkButton)cmditem.FindControl("save");
        saveButton.Visible = true;
        LinkButton addButton = (LinkButton)cmditem.FindControl("add");
        addButton.Visible = false;
    }
}
protected void RadGrid1_PreRender(object sender, EventArgs e)
{
    //to show the grid in insert mode after insert operation
    if (commandName == "PerformInsert")
    {
        commandName = "";
        RadGrid1.MasterTableView.IsItemInserted = true;
        RadGrid1.Rebind();
 
    }
    else
    {
        RadGrid1.MasterTableView.IsItemInserted = false;
        RadGrid1.Rebind();
    }
}

Also please check this demo if you dont want to show edit/delete button in each grid row.

Please elaborate your requirement more if it doesnt help.
Thanks,
Shinu.

0
Janaki
Top achievements
Rank 1
answered on 11 Apr 2012, 06:52 PM
Hi Shinu,

Thanks for the details on the buttons. I have implemented as per your code. I am having a problem in this section of the code.
if (e.CommandName == "PerformInsert")
    {
        //your code for insertion
TripItineraryDTO itin = new TripItineraryDTO();
                GridDataItem item = e.Item as GridDataItem;
                // get the date picker
               RadDatePicker datePicker = item["Date"].Controls[1] as RadDatePicker;
               //itin.ItinDate = this.TripStartDate.ToString();
               itin.ItinDate = datePicker.SelectedDate.Value.ToShortDateString();
               itin.PrNumber = this.AuthorizationNumber.Value;
                itin.ToCity = (item["ToCity"].Controls[1] as TextBox).Text;
                itin.FromCity = (item["FromCity"].Controls[1] as TextBox).Text;
                // get drop Down lists
                itin.ToStateCode = (item["ToStateCode"].Controls[1] as DropDownList).SelectedValue;
                itin.ToCountryCode = (item["ToCountryCode"].Controls[1] as DropDownList).SelectedValue;

                itin.FromStateCode = (item["FromStateCode"].Controls[1] as DropDownList).SelectedValue;
                itin.FromCountryCode = (item["FromCountryCode"].Controls[1] as DropDownList).SelectedValue;
                itin.PersonalTravel = (item["PersonalTravel"].Controls[1] as CheckBox).Checked.ToString();
                Ucar.Data.Travel.TravelSessionManager.TravelManager.CreateTripItineraryItem(itin);
        commandName = "PerformInsert";
           
    }

I have added my code for doing the insert. This is the code that I had in the Radgrid1_InsertCommand which worked with the save button that I added in the RadGrid1_ItemCommand. When I click on Add new record first it lets me input the data. Then when I click on the add again, it is giving me error at the Raddatepicker line Null Reference exception was unhandled by user code Object reference not set to an instance of an object.
0
Janaki
Top achievements
Rank 1
answered on 11 Apr 2012, 09:43 PM
Did you find anything wrong in my code? Not sure why it is giving the null exception.
0
Elliott
Top achievements
Rank 2
answered on 11 Apr 2012, 09:52 PM
I'd have to get the page and trace it to find the problem
but...
if I was getting a null exception I'd split up the command and see where it's losing it
isolate item["Date"] (with an explicit index, if necessary)
cast it to TableCell - it's item.Cells[n]
then go into the TableCell just isolated and cast Controls[1] to RadDatePicker
makes sense?
0
Janaki
Top achievements
Rank 1
answered on 11 Apr 2012, 10:03 PM
I am not able to locate the problem with the trace. The item itself is null.
0
Elliott
Top achievements
Rank 2
answered on 11 Apr 2012, 10:06 PM
if you are going into insert mode won't the DataItem be null?
you need to get the item not of the one you are going to insert but the one you just created
0
Janaki
Top achievements
Rank 1
answered on 11 Apr 2012, 10:59 PM
How do I get the item of the one I just created?
0
Janaki
Top achievements
Rank 1
answered on 11 Apr 2012, 11:33 PM
I am trying to trace the code and will need some help.  When I click on the Add New record button, a new row comes up and I enter the data. Then, I click on the Add New record button again. Here is where it goes into the RadGrid_ItemCommand and gives the null reference on the date. The date is set in the row. What is needed is when I click on  the Add new record button second time, it should take the user input and be able to save this row to the database with my insert code.
0
Janaki
Top achievements
Rank 1
answered on 11 Apr 2012, 11:57 PM
Any suggestions on what I can do here??
0
Janaki
Top achievements
Rank 1
answered on 12 Apr 2012, 12:07 AM
Should I be using the ItemDataBound event instead of the itemcommandevent??
0
Janaki
Top achievements
Rank 1
answered on 12 Apr 2012, 02:40 AM
Hi Shinu,

Can you help with this problem?

Thanks, Janaki
0
Accepted
Shinu
Top achievements
Rank 2
answered on 12 Apr 2012, 06:23 AM
Hi Janaki,

Here is the code I tried to insert and is working fine. Please have a look into the following code.

ASPX:
<telerik:RadGrid ID="RadGrid1" runat="server" DataSourceID="SqlDataSource1"
AutoGenerateColumns="false" onitemcommand="RadGrid1_ItemCommand"
onitemdatabound="RadGrid1_ItemDataBound" onprerender="RadGrid1_PreRender">
  <MasterTableView EditMode="InPlace" CommandItemDisplay="Top" EnableHeaderContextMenu="true">
    <CommandItemTemplate>
      <asp:LinkButton ID="add" runat="server" Text="Add new Record" CommandName="InitInsert"></asp:LinkButton>
      <asp:LinkButton ID="save" runat="server" Text="Add new Record" CommandName="PerformInsert" Visible="false"></asp:LinkButton>
    </CommandItemTemplate>
    <Columns>
      <telerik:GridEditCommandColumn UniqueName="EditColumn" ButtonType="LinkButton"></telerik:GridEditCommandColumn>
      <telerik:GridButtonColumn UniqueName="Delete" ButtonType="LinkButton" CommandName="Delete" Text="Delete"></telerik:GridButtonColumn>
      <telerik:GridBoundColumn UniqueName="OrderID" DataField="OrderID" HeaderText="OrderID"></telerik:GridBoundColumn>
      <telerik:GridBoundColumn UniqueName="ShipName" DataField="ShipName" HeaderText="ShipName"></telerik:GridBoundColumn>
      <telerik:GridDateTimeColumn DataField="OrderDate" HeaderText="Order Date" UniqueName="OrderDate"></telerik:GridDateTimeColumn>
    </Columns>
  </MasterTableView>
</telerik:RadGrid>

C#:
protected void RadGrid1_ItemCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
{
    if (e.CommandName == "PerformInsert")
    {
        LinkButton performinsert = (LinkButton)e.CommandSource;
        GridDataInsertItem editItem = (GridDataInsertItem)RadGrid1.MasterTableView.GetInsertItem();
        string OrderId = (editItem["OrderID"].Controls[0] as TextBox).Text;
        string ShipName = (editItem["ShipName"].Controls[0] as TextBox).Text;
        DateTime OrderDate = Convert.ToDateTime((editItem["OrderDate"].Controls[0] as RadDatePicker).SelectedDate);
        string insertQuery = "insert into Orders (OrderID,ShipName,OrderDate) values ('" + OrderId + "','" + ShipName + "','" + OrderDate + "')";
        conn.Open();
        SqlCommand.CommandText = insertQuery;
        SqlCommand.Connection = conn;
        SqlCommand.ExecuteNonQuery();
        conn.Close();
        commandName = "PerformInsert";   
    }
    if (e.CommandName == "InitInsert")
    {
        commandName = "PerformInsert";
    }
}

Hope this helps.
Thanks,
Shinu.
0
Janaki
Top achievements
Rank 1
answered on 12 Apr 2012, 05:30 PM
Thanks a lot. It worked great!!
0
Janaki
Top achievements
Rank 1
answered on 12 Apr 2012, 05:47 PM
Hi Shinu,

One more question on this. I had required validators on certain fields and these are not working when I click on the Add new record to save the record. It seems to be working fine with the update. Any idea why this would be?

Thanks, Janaki
0
Janaki
Top achievements
Rank 1
answered on 12 Apr 2012, 06:10 PM
I found the answer to set the validation group for the add/save buttons.
0
michelle
Top achievements
Rank 1
answered on 21 Aug 2013, 02:54 PM
I cannot get the Add New Record button to bring up the edit form so that I can do an insert??

Here is the asp.net file
<%@ Page Title="" Language="C#" MasterPageFile="~/calcs/rescalc5x/SiteBase.Master" AutoEventWireup="true" CodeBehind="ProductUtilityAsnFrameworkMaintenance.aspx.cs" Inherits="HECWebsite5x.admin.calcs.rescalc.Spcs.ProductUtilityAsnFrameworkMaintenance" %>
<%@ Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %>
<asp:Content ID="Content3" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
 
<div id="apo_Admin_Navigation">
        <asp:Literal ID="txtAdminNavigation"  runat="server" />
        <div align="right">
        <asp:updateprogress id="UpdateProgress1" runat="server" associatedupdatepanelid="updPnlRecList" dynamiclayout="true" DisplayAfter="50">
            <progresstemplate>
                  <asp:Image ID="ImageFileFolders" runat="server" ImageUrl="~/images/load.gif" AlternateText="Loading..." ImageAlign="AbsMiddle" />
            </progresstemplate>
        </asp:updateprogress>        
        </div>     
</div>
 
<h3><asp:placeholder id="plCurrentSiteInfo" runat="server" visible="false"> <%=TargetSite.AccountID%>.<%=TargetSite.HostHeader%>. </asp:placeholder> <%=TargetSite.UtilityID%> </h3>
 
<asp:UpdatePanel ID="updPnlRecList" RenderMode="Inline" runat="server" updatemode="Conditional" EnableViewState="true">
<ContentTemplate>
<div id="apo_Admin_Content">
 
    <h2><asp:Label ID="lblListPageTitle" runat="server" Text="ProductUtilityAsns"></asp:Label></h2>
 
    <asp:Label ID="lblError" runat="server" style="color:red"></asp:Label>
 
    <asp:placeholder id="plResult" runat="server" visible="false">
        <p><asp:literal id="txtResult" runat="server" /></p>
    </asp:placeholder>
 
    <asp:EntityDataSource ID="EntityDataSource1" runat="server" ConnectionString="name=GeneratorConnectionString" DefaultContainerName="ApogeeCentralEntities" EnableFlattening="False" EntitySetName="Products" Select="it.[Id] as [ProductId], it.[Name] as [ProductName]">
    </asp:EntityDataSource>
     
    <asp:EntityDataSource ID="EntityDataSource2" runat="server" ConnectionString="name=GeneratorConnectionString" DefaultContainerName="ApogeeCentralEntities" EnableFlattening="False" EntitySetName="HEC_Utility" Select="it.[Id] as [UtilityId], it.[UtilityId] as [UtilityName]">
    </asp:EntityDataSource>
 
    <asp:placeholder id="plRebatesList" runat="server">
     
    <div align="left">
    <asp:Image ID="Image1" runat="server" ImageUrl="~/images/pinback.png" ImageAlign="AbsMiddle" /><asp:linkbutton id="btnBack" runat="server" text="HEC Admin" OnCommand="DoCommand" CommandName="BackToHecAdmin" CommandArgument="" />
    </div>
    <br />
    <asp:Panel runat="server" ID="pnlUtilitySpcGrid">
     
                 <telerik:RadGrid ID="GridView1"  runat="server"
                                  AutoGenerateColumns="False"  Visible="true" 
                      GridLines="None"
                                  AllowPaging="True" AllowSorting="True"  MasterTableView-ClientDataKeyNames="ProductId,UtilityId"
                                  OnNeedDataSource="GridView1_NeedDataSource"
                                  OnCancelCommand="GridView1_RowCancelingEdit"
                                  OnDeleteCommand="GridView1_RowDeleting" 
                                  OnEditCommand="GridView1_RowEditing"
                                  OnUpdateCommand="GridView1_RowUpdating"
                                  OnInsertCommand="GridView1_RowInserting"
                       
        OnItemInserted="GridView1_ItemInserted" OnItemUpdated="GridView1_ItemUpdated" OnItemCommand="GridView1_ItemCommand"
        OnPreRender="GridView1_PreRender"
                                  AllowScroll = "True"
                                  AllowFilteringByColumn="True"
                                  AllowMultiRowSelection="True"
                                  ItemStyle-VerticalAlign="Top"
                                  PageSize="25"
                                  AutoGenerateEditColumn="true"
                                  AutoGenerateDeleteColumn="true"
                                  AutoGenerateInsertColumn="true"
                                  AllowAutomaticInserts="false"
                                  AllowAutomaticDeletes="false"
                                  AllowAutomaticUpdates="false"
                                  >
                <MasterTableView CommandItemDisplay="Top"  EditMode="EditForms">
              
                         <Columns>
 
 
                           
                             <telerik:GridBoundColumn DataField="ProductId" ReadOnly="true" HeaderText="Product Id" Display="false" SortExpression="ProductId" />
                             <telerik:GridBoundColumn DataField="ProductName" ReadOnly="false" HeaderText="Product Name" Display="true" SortExpression="ProductName" />
                             <telerik:GridBoundColumn DataField="UtilityId" ReadOnly="true" HeaderText="Utility Id" Display="false" SortExpression="UtilityId" />
                             <telerik:GridBoundColumn DataField="UtilityName" ReadOnly="false" HeaderText="Utility Name" Display="true" SortExpression="UtilityName" />
                            <telerik:GridBoundColumn DataField="isDesktopActive"  HeaderText="is Desktop Active" Display="true" SortExpression="isDesktopActive" />
                            <telerik:GridBoundColumn DataField="isMobileActive"  HeaderText="is Mobile Active" Display="true" SortExpression="isMobileActive" />
                            <telerik:GridBoundColumn DataField="isTabletActive"  HeaderText="is Tablet Active" Display="true" SortExpression="isTabletActive" />
                             
                             
 
          
                         </Columns>
                     
            
            <EditFormSettings EditFormType="Template" >
                <FormTemplate>
                 
            <table>
                            <tr>
                                <td width="125px">
                                    Product:
                                </td>
                                <td>
                                    <asp:DropDownList ID="drpProduct" runat="server" AppendDataBoundItems="True" SelectedValue='<%# Bind("ProductId") %>' DataSourceID="EntityDataSource1" DataTextField="ProductName" DataValueField="ProductId" AutoPostBack="True">
                                        <asp:ListItem Value="0">Select a Product..</asp:ListItem>
                                    </asp:DropDownList>
                                    </td>
                                </tr>
                            <tr>
                                 
                                <td width="125px">
                                    Utility:
                                </td>
                                <td>
                                    <asp:DropDownList ID="drpUtility" runat="server" AppendDataBoundItems="True" SelectedValue='<%# Bind("UtilityId") %>' DataSourceID="EntityDataSource2" DataTextField="UtilityName" DataValueField="UtilityId" AutoPostBack="True">
                                        <asp:ListItem Value="0">Select a Utility..</asp:ListItem>
                                    </asp:DropDownList>
                                    </td>
                                </tr>
                            <tr>
                                 
                                <td width="125px">
                                    IsDesktopActive:
                                </td>
                                <td>
                                    <asp:CheckBox ID="chkIsDesktopActive" runat="server" Checked='<%# Bind("isDesktopActive") %>' />
                                    </td>
                                </tr>
                                <tr>
                                 
                                <td width="125px">
                                    IsMobileActive:
                                </td>
                                <td>
                                    <asp:CheckBox ID="chkIsMobileActive" runat="server" Checked='<%# Bind("isMobileActive") %>' />
                                    </td>
                                </tr>
                            <tr>
                                 
                                <td width="125px">
                                    IsTabletActive:
                                </td>
                                <td>
                                    <asp:CheckBox ID="chkIsTabletActive" runat="server" Checked='<%# Bind("isTabletActive") %>' />
                                    </td>
                                </tr>
                            <tr>
                            <td align="right" colspan="2">
                                <asp:Button ID="btnUpdate" Text='<%# (Container is GridEditFormInsertItem) ? "Insert" : "Update" %>'
                                    runat="server" CommandName='<%# (Container is GridEditFormInsertItem) ? "PerformInsert" : "Update" %>'>
                                </asp:Button
                                <asp:Button ID="btnCancel" Text="Cancel" runat="server" CausesValidation="False"
                                    CommandName="Cancel"></asp:Button>
                            </td>
                        </tr>
                    </table>
         
            </FormTemplate>
            <PopUpSettings Modal="True" Width="650px"></PopUpSettings>
        </EditFormSettings>
          <NoRecordsTemplate>
            You currently have no listings in the system.</NoRecordsTemplate>
    </MasterTableView>
            
                      
                 <ClientSettings AllowGroupExpandCollapse="True" AllowDragToGroup="False" AllowColumnsReorder="true" ColumnsReorderMethod="Reorder" ReorderColumnsOnClient="true">
                                    <Animation AllowColumnReorderAnimation="true" ColumnReorderAnimationDuration="300" AllowColumnRevertAnimation="true" />
                                    <Selecting AllowRowSelect="true" />
                                    <Scrolling UseStaticHeaders="true" AllowScroll="true" ScrollHeight="550px" />
                                    <Resizing AllowColumnResize="true" ClipCellContentOnResize="true" EnableRealTimeResize="true" />
                         </ClientSettings>
                                 
                </telerik:RadGrid>
             
        
  
                <br /><br />
     
   </div>
    </asp:Panel>
    </asp:placeholder>
 
</div>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>





Here is the csharp behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HECWebsite5x.admin.calcs.rescalc.Common;
using HECWebsite5x.Entities;
using HECWebsite5x.admin.calcs.rescalc.Spcs.usercontrols;
using System.Data;
using ApogeeInteractive.ApplicationFramework.ORM;
using Telerik.Web.UI;
using System.Data.SqlClient;
using System.Configuration;
 
namespace HECWebsite5x.admin.calcs.rescalc.Spcs
{
public partial class ProductUtilityAsnFrameworkMaintenance : HECWebsite5x.admin.HECBaseAdminPage
{
    public string MyConString =ConfigurationManager.ConnectionStrings["GeneratorConnectionString"].ConnectionString;
    public SqlConnection connection;
    public SqlConnection SqlConn;
 
 
 
    protected override void Page_Init(object sender, EventArgs e)
    {
        base.Page_Init(sender, e);
        setAdminView(IsApogeeAdmin);
    }
 
 
    private void setAdminView(bool IsApogeeAdmin)
    {
       txtAdminNavigation.Text= GenerateAdminMenu();
    }
 
 
    protected void Page_Load(object sender, EventArgs e)
    {
        base.Page_Load(sender, e);
            txtAdminNavigation.Text = GenerateAdminMenu();
 
 
        if (!IsPostBack)
        {
 
            ViewState["sortExpression"] = "ProductId,UtilityId";
            ViewState["sortDirection"] = "asc";
            DataBind();
        }
         
    }
 
 
 
    protected void GridView1_NeedDataSource(object source, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
    {
        try
        {
 
        ApogeeCentralEntities context = ApogeeCentral.CreateContext();
 
            GridView1.DataSource =  from tblProductUtilityAsn in context.ProductUtilityAsns.AsEnumerable().ToArray() //.OrderBy(ViewState["sortExpression"].ToString()).Sort(ViewState["sortDirection"].ToString())
                                    join tblProduct in context.Products on tblProductUtilityAsn.ProductId equals tblProduct.Id
                                    join tblUtility in context.HEC_Utility on tblProductUtilityAsn.UtilityId equals tblUtility.id
                                    
                                              select new {
 
                        //Id=tblProductUtilityAsn.Id,
                        isDesktopActive=tblProductUtilityAsn.isDesktopActive,
                        isMobileActive=tblProductUtilityAsn.isMobileActive,
                        isTabletActive=tblProductUtilityAsn.isTabletActive,
                        ProductId=tblProduct.Id,
                        ProductName = tblProduct.Name,
                        UtilityId=tblUtility.id,
                        UtilityName = tblUtility.utilityid
 
                        };
 
 
        GridView1.Skin = TelerikSkin.GridDefaultSkin;
            //GridView1.DataBind();
        }
        catch(Exception exProductUtilityAsn)
        {
        }
        finally
        {
            //not sure what to do here?
        }
    }
    protected void GridView1_ItemCommand(object source, GridCommandEventArgs e)
    {
        if (e.CommandName == RadGrid.InitInsertCommandName) //"Add new" button clicked
        {
            e.Item.Edit=true;
            
        }
        else if (e.CommandName == RadGrid.RebindGridCommandName && e.Item.OwnerTableView.IsItemInserted)
        {
            e.Canceled = true;
        }
        else
        {
             
         //   GridEditCommandColumn editColumn = (GridEditCommandColumn)GridView1.MasterTableView.GetColumn("EditCommandColumn");
         //   if (!editColumn.Visible)
         //       editColumn.Visible = true;
        }
    }
    protected void GridView1_ItemUpdated(object source, Telerik.Web.UI.GridUpdatedEventArgs e)
    {
        if (e.Exception != null)
        {
            e.KeepInEditMode = true;
            e.ExceptionHandled = true;
            //DisplayMessage(true, "Employee " + e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["EmployeeID"] + " cannot be updated. Reason: " + e.Exception.Message);
        }
        else
        {
            GridView1.Rebind();
            //DisplayMessage(false, "Employee " + e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["EmployeeID"] + " updated");
        }
    }
    protected void GridView1_ItemDeleted(object source, Telerik.Web.UI.GridUpdatedEventArgs e)
    {
        if (e.Exception != null)
        {
            e.KeepInEditMode = true;
            e.ExceptionHandled = true;
            //DisplayMessage(true, "Employee " + e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["EmployeeID"] + " cannot be updated. Reason: " + e.Exception.Message);
        }
        else
        {
            //DisplayMessage(false, "Employee " + e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["EmployeeID"] + " updated");
        }
    }
    protected void GridView1_ItemInserted(object source, Telerik.Web.UI.GridInsertedEventArgs e)
    {
        if (e.Exception != null)
        {
            e.ExceptionHandled = true;
            e.KeepInInsertMode = true;
            //DisplayMessage(true, "Employee cannot be inserted. Reason: " + e.Exception.Message);
        }
        else
        {
            //DisplayMessage(false, "Employee inserted");
        }
    }
 
    protected void GridView1_PreRender(object sender, EventArgs e)
    {
    
    }
 
    protected void BtnAdd_Click(object sender, EventArgs e)
    {
        InsertNewRecord();   
    }
 
 
 
    protected void GridView1_RowInserting(object source, Telerik.Web.UI.GridCommandEventArgs e)
    {
        GridEditableItem item = e.Item as GridEditableItem;
 
 
        ApogeeCentralEntities context = ApogeeCentral.CreateContext();
 
 
        int rowIndex = 0;
        ProductUtilityAsn updProductUtilityAsn = new ProductUtilityAsn();
 
 
        //what if this is not an int type??
 
        updProductUtilityAsn.ProductId = -1; //identity
        updProductUtilityAsn.UtilityId = -1; //identity
 
     //   rowIndex = item.RowIndex;
 
        updProductUtilityAsn.isDesktopActive = Convert.ToBoolean((item["isDesktopActive"].Controls[0] as TextBox).Text);
        updProductUtilityAsn.isMobileActive = Convert.ToBoolean((item["isMobileActive"].Controls[0] as TextBox).Text);
        updProductUtilityAsn.isTabletActive = Convert.ToBoolean((item["isTabletActive"].Controls[0] as TextBox).Text);
 
 
 
 
    try{
        context.AddObject("ProductUtilityAsns", updProductUtilityAsn);
 
        context.SaveChanges();
 
        context.AcceptAllChanges();
    }
    catch(Exception ex)
    {
        lblError.Text = "Unable to insert";
    }
 
        GridView1.Rebind();
 
    }
    public DataTable LinqToDataTable<T>(IEnumerable<T> varlist)
    {
             DataTable dtReturn = new DataTable();
 
             // column names
             PropertyInfo[] oProps = null;
 
             if (varlist == null) return dtReturn;
 
             foreach (T rec in varlist)
             {
                  // Use reflection to get property names, to create table, Only first time, others will follow
                  if (oProps == null)
                  {
                       oProps = ((Type)rec.GetType()).GetProperties();
                       foreach (PropertyInfo pi in oProps)
                       {
                            Type colType = pi.PropertyType;
 
                            if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition()     
                            ==typeof(Nullable<>)))
                             {
                                 colType = colType.GetGenericArguments()[0];
                             }
 
                            dtReturn.Columns.Add(new DataColumn(pi.Name, colType));
                       }
                  }
 
                  DataRow dr = dtReturn.NewRow();
 
                  foreach (PropertyInfo pi in oProps)
                  {
                       dr[pi.Name] = pi.GetValue(rec, null) == null ?DBNull.Value :pi.GetValue
                       (rec,null);
                  }
 
                  dtReturn.Rows.Add(dr);
             }
             return dtReturn;
        }
    protected void DoCommand(object sender, CommandEventArgs e)
        {
            switch (e.CommandName.ToString())
            {
                case "BackToHecAdmin":
                    Response.Redirect(PageList.AdminDefault);
                    break;
                case "NewProductUtilityAsn":
                    InsertNewRecord();
                    break;
                default:
                    Response.Redirect("ProductUtilityAsnFrameworkMaintenance.aspx");
                    break;
            }
        }
 
    protected void InsertNewRecord()
    {
    ApogeeCentralEntities context = ApogeeCentral.CreateContext();
 
        try
        {      
     
            var updProductUtilityAsn = from tblProductUtilityAsn in context.ProductUtilityAsns
                                  
 
        //                                 where util.utilityid == TargetSite.UtilityID
                         
 
                                         select tblProductUtilityAsn;
 
 
            DataTable dt = new DataTable();
            dt=LinqToDataTable<ProductUtilityAsn>(updProductUtilityAsn);
 
            // Here we'll add a blank row to the returned DataTable
            DataRow dr = dt.NewRow();
 
 
 
            dt.Rows.InsertAt(dr, 0);
            //Creating the first row of GridView to be Editable
         
            GridView1.CurrentPageIndex = 0;
            //GridView1.EditIndex = 0;
        GridView1.MasterTableView.Items[0].Edit = true;
            GridView1.MasterTableView.Rebind();
            GridView1.DataSource = dt;
            GridView1.DataBind();
 
 
 
 
 
 
            //Changing the Text for Inserting a New Record
            ((LinkButton)GridView1.Items[0].Cells[0].Controls[0]).Text = "Insert";
 
        }
        finally
        {
            connection.Close();
            connection = null;
        }
    }
    protected string iif(bool x, string y, string z)
    {
        if (x == true)
        {
            return y;
 
        }
        else
        {
            return z;
        }
    }
     
    protected void GridView1_RowUpdating(object source, Telerik.Web.UI.GridCommandEventArgs e)
    {
            GridEditableItem item = e.Item as GridEditableItem;
             
 
 
            ApogeeCentralEntities context = ApogeeCentral.CreateContext();
 
 
        int rowIndex = 0;
        ProductUtilityAsn updProductUtilityAsn = new ProductUtilityAsn();
 
 
            //if not insert
             
            //what if this is not an int type??
 
 
 
            int ProductId= Convert.ToInt32(item.OwnerTableView.DataKeyValues[item.ItemIndex]["ProductId"].ToString());
            int UtilityId = Convert.ToInt32(item.OwnerTableView.DataKeyValues[item.ItemIndex]["UtilityId"].ToString());
 
            //get existing ProductUtilityAsn so we can update it
 
            updProductUtilityAsn = (from tblProductUtilityAsn in context.ProductUtilityAsns
                                     
                                    where
 
 
 
 
                                        tblProductUtilityAsn.ProductId == ProductId &&
                                        tblProductUtilityAsn.UtilityId == UtilityId
 
 
 
 
        //                                 where util.utilityid == TargetSite.UtilityID
                    
 
                                         select tblProductUtilityAsn).First<ProductUtilityAsn>();
 
//do we need to select only fk e.Keys[[FKNum]-1]??
 
               rowIndex = item.RowIndex;
 
 
               item.UpdateValues(updProductUtilityAsn);
 
             
 
        try
            {
                //FKs
 
        }
 
            catch(Exception exFK)
            {
                  
 
 
 
 
 
 
            }
 
       
 
            //Columns that are not PK or FK
            CheckBox chkIsDesktopActive = (CheckBox)item.FindControl("chkIsDesktopActive");
            CheckBox chkIsMobileActive = (CheckBox)item.FindControl("chkIsMobileActive");
            CheckBox chkIsTabletActive = (CheckBox)item.FindControl("chkIsTabletActive");
            updProductUtilityAsn.isDesktopActive= Convert.ToBoolean(chkIsDesktopActive.Checked);
            updProductUtilityAsn.isMobileActive= Convert.ToBoolean(chkIsMobileActive.Checked);
            updProductUtilityAsn.isTabletActive= Convert.ToBoolean(chkIsTabletActive.Checked);
 
 
 
 
 
        try{
            context.SaveChanges();
            context.AcceptAllChanges();
            GridView1.EditIndexes.Clear();
            }
            catch(Exception ex)
            {
                lblError.Text = "Unable to update";
            }
 
 
            //GridView1.MasterTableView.DetailTables[0].ClearEditItems();
            GridView1.Rebind();
            //DataBind();
    }
 
    protected void GridView1_RowEditing(object source, Telerik.Web.UI.GridCommandEventArgs e)
    {
 
    GridView1.MasterTableView.Items[e.Item.ItemIndex].Edit = true;
 
 
         
         
         
         
         
         
        ((System.Web.UI.WebControls.TableCell)(GridView1.Items[e.Item.ItemIndex].Controls[0])).Text="0";
        ((System.Web.UI.WebControls.TableCell)(GridView1.Items[e.Item.ItemIndex].Controls[0])).Text="0";
        ((System.Web.UI.WebControls.TableCell)(GridView1.Items[e.Item.ItemIndex].Controls[0])).Text="0";
        ((System.Web.UI.WebControls.TableCell)(GridView1.Items[e.Item.ItemIndex].Controls[0])).Text="0";
        ((System.Web.UI.WebControls.TableCell)(GridView1.Items[e.Item.ItemIndex].Controls[0])).Text="0";
        ((System.Web.UI.WebControls.TableCell)(GridView1.Items[e.Item.ItemIndex].Controls[0])).Text="0";
 
 
 
 
 
 
 
 
 
 
        DataBind();
 
        //create a dropdown for each foreign key
 
 
    }
 
 
 
 
    private int GetIndexOfValue(string value,DataTable dt0)
    {
        int iRow = 0;
        for (iRow = 0; iRow < dt0.Rows.Count; iRow++ )
        {
            DataRow dr = dt0.Rows[iRow];
            if (dr[1].ToString() == value)
            {
                return iRow;
            }
         
        }
        return (-1);
    }
     
    protected void GridView1_RowCancelingEdit(object source, Telerik.Web.UI.GridCommandEventArgs e)
    {
        try
        {
            if (GridView1.MasterTableView.DetailTables.Count>0)
            {
            GridView1.MasterTableView.DetailTables[0].ClearEditItems();
            }
        }
        catch(Exception ex)
        {
           //if it fails just bind
        }
        DataBind();
    }
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            try
            {
 
            }
            catch(Exception exList)
            {
            }
        }
    }
    protected void GridView1_RowDeleting( object source, Telerik.Web.UI.GridCommandEventArgs e)
    {
 
         
    ApogeeCentralEntities context = ApogeeCentral.CreateContext();
 
 
        try
        {
 
        GridEditableItem item = e.Item as GridEditableItem;
 
             
        int rowIndex = 0;
        ProductUtilityAsn updProductUtilityAsn = new ProductUtilityAsn();
 
 
            //if not insert
             
            //what if this is not an int type??
            int ProductId= Convert.ToInt32(item.OwnerTableView.DataKeyValues[item.ItemIndex]["ProductId"].ToString());
            int UtilityId = Convert.ToInt32(item.OwnerTableView.DataKeyValues[item.ItemIndex]["UtilityId"].ToString());
 
            //get existing ProductUtilityAsn so we can update it
 
            updProductUtilityAsn = (from tblProductUtilityAsn in context.ProductUtilityAsns
                                    where tblProductUtilityAsn.ProductId == ProductId
                                    where tblProductUtilityAsn.UtilityId == UtilityId
 
        //                                 where util.utilityid == TargetSite.UtilityID
                         select tblProductUtilityAsn).First<ProductUtilityAsn>();
 
            try
            {
                context.DeleteObject(updProductUtilityAsn);
 
                context.SaveChanges();
                context.AcceptAllChanges();
 
             
            }
            catch (Exception exDel)
            {
                //lblError.Text = "An unexpected error occurred while deleting:" + exDel.ToString();
            }
            //DataBind();
        }
        finally
        {
             
        }
    }
 
    protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    {
        if (ViewState["sortExpression"].ToString() == e.SortExpression && ViewState["sortDirection"].ToString() == "asc")
            ViewState["sortDirection"] = "desc";
        else
            ViewState["sortDirection"] = (e.SortDirection == SortDirection.Ascending ? "asc" : "desc");
 
        ViewState["sortExpression"] = e.SortExpression;
 
 
        DataBind();
    }
 
    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.CurrentPageIndex = e.NewPageIndex;
        DataBind();
    }
}
 
         
}

0
michelle
Top achievements
Rank 1
answered on 21 Aug 2013, 04:19 PM
Some additional info -

I also found that if I change
<MasterTableView EditMode="EditForms"
to
<MasterTableView EditMode="InPlace"

I DO get the default add form to come up but I want to use the EditForm because I need to add drop down lists etc.

Note that the Edit button DOES bring up the Edit Form but not the Add New Record button - very frustrating!!

This is happening on two different web pages for me right now and I feel like I have tried everything!
0
michelle
Top achievements
Rank 1
answered on 21 Aug 2013, 05:10 PM
And now I find a more interesting fact!  It appears to work fine in IE but not in Firefox!!!!
0
michelle
Top achievements
Rank 1
answered on 21 Aug 2013, 05:21 PM
Actually that is wrong - it doesnt work - it just did something different!!!! ARRRGGHHH
0
Kostadin
Telerik team
answered on 26 Aug 2013, 10:55 AM
Hello Michelle,

I noticed that in your project you are using advanced databinding and simple databinding together which is not supported scenario. I would recommend you to review the following help article which elaborates more on the advantage of the advanced databinding. Additionally could you please verify that you do not cancel the init insert command in ItemCommnad event handler of your grid?

Regards,
Kostadin
Telerik
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 the blog feed now.
Tags
Grid
Asked by
Janaki
Top achievements
Rank 1
Answers by
Elliott
Top achievements
Rank 2
Shinu
Top achievements
Rank 2
Janaki
Top achievements
Rank 1
michelle
Top achievements
Rank 1
Kostadin
Telerik team
Share this question
or