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

"Add New Item" option in Grid

5 Answers 399 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Venkatesh
Top achievements
Rank 1
Venkatesh asked on 03 Dec 2012, 07:24 AM
Hi,

I installed the "RadControls for ASP.NET AJAX Q3 2012". I am using sharepoint 2010. I added the Rad grid in the visual webpart and bound the columns.  I used the below code:
<telerik:RadGrid ID="RadGrid1" runat="server" Visible="true" ShowHeader="true" ShowFooter="true" >
    <MasterTableView DataKeyNames="Title" AutoGenerateColumns="false">
                    <Columns>
                        <telerik:GridBoundColumn DataField="Title" HeaderText="Product Number" UniqueName="ProductNumber">
                        </telerik:GridBoundColumn>
                        <telerik:GridBoundColumn DataField="Description" HeaderText="Description" UniqueName="Description">
                        </telerik:GridBoundColumn>
  </Columns>
    </MasterTableView>
    </telerik:RadGrid>
I am able to bind the existing data in the databind code using c#. Few questions:
1) How to insert new data?
2) Also above the header and below the footer, is it possible to add a option as "Add new item" clicking on this, the textbox within the grid become editable?
3) Limit the number of items which can be added in the grid to 5.

How to achieve this?
Thanks

5 Answers, 1 is accepted

Sort by
0
Princy
Top achievements
Rank 2
answered on 03 Dec 2012, 08:09 AM
Hi Venkatesh,

Try setting CommandItemDisplay property of MasterTableView to TopAndBottom to show the Add New Record button in the top and bottom of RadGrid.

ASPX:
<MasterTableView CommandItemDisplay="TopAndBottom">

To achieve your third requirement try the following code snippet.

C#:
protected void RadGrid1_ItemCommand(object sender, GridCommandEventArgs e)
{
    if (e.CommandName == RadGrid.InitInsertCommandName)
    {
        if (i < 5)
        {
            i++;
        }
        else
        {
            e.Canceled = true;
            RadGrid1.MasterTableView.CommandItemDisplay = GridCommandItemDisplay.None;
        }
    }
}

Hope this helps.

Regards,
Princy.
0
Venkatesh
Top achievements
Rank 1
answered on 03 Dec 2012, 08:33 AM
HI,
Thanks for the quick reply.

In the ItemCommand, I am not getting the property "InitInsertCommandName".

Also, when "Add new Item" is clicked, how to show the textbox to add the items in grid and how to save the changes.

Thanks
0
Princy
Top achievements
Rank 2
answered on 04 Dec 2012, 04:20 AM
Hi,

The InitInsertCommandName is raised when you click add new record button. In order to add textbox in edit mode, you can use a template column as shown below.
aspx:
<telerik:GridTemplateColumn>
    <EditItemTemplate>
          <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    </EditItemTemplate>
</telerik:GridTemplateColumn>

Hope this helps.

Regards,
Princy.
0
Venkatesh
Top achievements
Rank 1
answered on 04 Dec 2012, 05:22 AM
HI,
Thanks for the reply.
I have adde the grid as below:

<telerik:RadGrid ID="RadGrid1" runat="server" 
        ShowFooter="True" onitemcommand="RadGrid1_ItemCommand" 
        ondeletecommand="RadGrid1_DeleteCommand" 
        oninsertcommand="RadGrid1_InsertCommand" 
        onupdatecommand="RadGrid1_UpdateCommand" >
    <MasterTableView DataKeyNames="Title" AutoGenerateColumns="false" EditMode="InPlace" CommandItemDisplay="TopAndBottom" CommandItemSettings-AddNewRecordText="Add New Item" >
                      
<Columns>
                     <telerik:GridEditCommandColumn ButtonType="ImageButton">
                        </telerik:GridEditCommandColumn>
                        <telerik:GridButtonColumn ConfirmText="Delete this product?" ConfirmDialogType="RadWindow"
                            ConfirmTitle="Delete" ButtonType="ImageButton" CommandName="Delete" ConfirmDialogHeight="100px"
                            ConfirmDialogWidth="220px">
                        </telerik:GridButtonColumn>
  
                     <telerik:GridTemplateColumn DataField="Title" HeaderText="Product Number" UniqueName="ProductNumber"
                            Visible="true">
                            <InsertItemTemplate>
                                <telerik:RadTextBox ID="RadtxtPrdNumber" runat="server" Text='<%# Bind("Title") %>' >
                                </telerik:RadTextBox>
                            </InsertItemTemplate>
                            <EditItemTemplate>
                                <telerik:RadTextBox ID="RadtxtPrdNumber" runat="server" Text='<%# Eval("Title") %>' >
                                </telerik:RadTextBox>
                            </EditItemTemplate>    
                            <ItemTemplate>
                            <telerik:RadTextBox ID="RadtxtPrdNumber" ReadOnly="true" runat="server" Text='<%# Eval("Title") %>' />
                            </ItemTemplate>                       
                        </telerik:GridTemplateColumn>
  
</Columns>
    </MasterTableView>
     <ClientSettings EnableRowHoverStyle="true">
        </ClientSettings>

In the cs code i have as below:

protected void RadGrid1_ItemCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
       {
           int i = 0;
           if (e.CommandName == RadGrid1.InitInsertCommandName)
           {
               if (i < 10)
               {
                   i++;
               }
               else
               {
                   e.Canceled = true;
                   RadGrid1.MasterTableView.CommandItemDisplay = GridCommandItemDisplay.None;
               }
           }
       }

I am getting the error as "Member 'Telerik.Web.UI.RadGrid.InitInsertCommandName' cannot be accessed with an instance reference; qualify it with a type name instead".

Is there anything i am missing? How to fix this?
Thanks
Jesse
Top achievements
Rank 1
Veteran
commented on 13 Jun 2024, 06:34 PM | edited

Same code, why is the below snippet the accepted answer when it is identical???
0
Accepted
Andrey
Telerik team
answered on 06 Dec 2012, 06:32 AM
Hi,

The problem you are facing is caused by the fact that you are trying to access the InitInsertCommandName property through the instance of RadGrid. InitInsertCommandName and all other command names are string constants and as such they are static, so they could not be accessed through the class instance. Instead they should be accessed through the class. You should change your code as follows:

protected void RadGrid1_ItemCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
{
   int i = 0;
   if (e.CommandName == RadGrid.InitInsertCommandName)
   {
       if (i < 10)
       {
           i++;
       }
       else
       {
           e.Canceled = true;
           RadGrid1.MasterTableView.CommandItemDisplay = GridCommandItemDisplay.None;
       }
   }
}

in order to achieve your goal.

All the best,
Andrey
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.
Jesse
Top achievements
Rank 1
Veteran
commented on 13 Jun 2024, 06:33 PM

This the exact same code as below and isn't compiling for me either
Vasko
Telerik team
commented on 18 Jun 2024, 05:21 AM

Hello Jesse,

I tried the above suggestion and it was working fine for me.

Could you take a look at the code below and see if you can reproduce the issue, if you can, please specify the steps to doing so: 

<asp:Label ID="Label1" runat="server" Text="Action:"></asp:Label>
<telerik:RadGrid ID="RadGrid1" runat="server" AllowPaging="True" Width="800px"
    AutoGenerateEditColumn="true"
    AutoGenerateDeleteColumn="true"
    OnItemCommand="RadGrid1_ItemCommand"
    OnNeedDataSource="RadGrid1_NeedDataSource"
    OnInsertCommand="RadGrid1_InsertCommand"
    OnUpdateCommand="RadGrid1_UpdateCommand"
    OnDeleteCommand="RadGrid1_DeleteCommand"    >
    <MasterTableView AutoGenerateColumns="False" DataKeyNames="OrderID" CommandItemDisplay="TopAndBottom" InsertItemDisplay="Top" InsertItemPageIndexAction="ShowItemOnLastPage">
        <Columns>
            <telerik:GridBoundColumn DataField="OrderID" DataType="System.Int32"
                FilterControlAltText="Filter OrderID column" HeaderText="OrderID"
                ReadOnly="True" SortExpression="OrderID" UniqueName="OrderID">
            </telerik:GridBoundColumn>
            <telerik:GridDateTimeColumn DataField="OrderDate" DataType="System.DateTime"
                FilterControlAltText="Filter OrderDate column" HeaderText="OrderDate"
                SortExpression="OrderDate" UniqueName="OrderDate">
            </telerik:GridDateTimeColumn>
            <telerik:GridNumericColumn DataField="Freight" DataType="System.Decimal"
                FilterControlAltText="Filter Freight column" HeaderText="Freight"
                SortExpression="Freight" UniqueName="Freight">
            </telerik:GridNumericColumn>
            <telerik:GridBoundColumn DataField="ShipName"
                FilterControlAltText="Filter ShipName column" HeaderText="ShipName"
                SortExpression="ShipName" UniqueName="ShipName">
            </telerik:GridBoundColumn>
            <telerik:GridBoundColumn DataField="ShipCountry"
                FilterControlAltText="Filter ShipCountry column" HeaderText="ShipCountry"
                SortExpression="ShipCountry" UniqueName="ShipCountry">
            </telerik:GridBoundColumn>
        </Columns>
    </MasterTableView>
</telerik:RadGrid>

#region Properties for CRUD Operations
public DataTable SessionDataSource
{
    get
    {
        string sessionKey = "SessionDataSource";

        if (Session[sessionKey] == null || !IsPostBack)
        {
            Session[sessionKey] = OrdersTable();
        }
        return (DataTable)Session[sessionKey];
    }
}
#endregion

#region RadGrid Events for CRUD Operations

protected void RadGrid1_ItemCommand(object sender, GridCommandEventArgs e)
{
    int i = 0;
    if (e.CommandName == RadGrid.InitInsertCommandName)
    {
        if (i < 10)
        {
            i++;
        }
        else
        {
            e.Canceled = true;
            RadGrid1.MasterTableView.CommandItemDisplay = GridCommandItemDisplay.None;
        }
    }
}


// CREATE (Add New Record)
protected void RadGrid1_InsertCommand(object sender, GridCommandEventArgs e)
{
    GridEditableItem editedItem = e.Item as GridEditableItem;

    DataRow newRow = SessionDataSource.NewRow();

    //As this example demonstrates only in-memory editing, a new primary key value should be generated
    //This should not be applied when updating directly the database
    DataRow[] allValues = SessionDataSource.Select("OrderID = MAX(OrderID)");

    if (allValues.Length > 0)
    {
        newRow["OrderID"] = int.Parse(allValues[0]["OrderID"].ToString()) + 1;
    }
    else
    {
        newRow["OrderID"] = 1; //the table is empty;
    }

    //Set new values
    Hashtable newValues = new Hashtable();
    //The GridTableView will fill the values from all editable columns in the hash
    e.Item.OwnerTableView.ExtractValuesFromItem(newValues, editedItem);

    try
    {
        foreach (DictionaryEntry entry in newValues)
        {
            newRow[(string)entry.Key] = entry.Value;
        }
    }
    catch (Exception ex)
    {
        Label1.Text += string.Format("<br />Unable to insert into Orders. Reason: {0}", ex.Message);
        e.Canceled = true;
        return;
    }

    SessionDataSource.Rows.Add(newRow);
    //Code for updating the database ca go here...
    Label1.Text += string.Format("<br />Order {0} inserted", newRow["OrderID"]);
}

// READ (data binding)
protected void RadGrid1_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
{
    (sender as RadGrid).DataSource = SessionDataSource;
}

// UPDATE
protected void RadGrid1_UpdateCommand(object sender, GridCommandEventArgs e)
{
    GridEditableItem editedItem = e.Item as GridEditableItem;

    //Locate the changed row in the DataSource
    DataRow[] changedRows = SessionDataSource.Select(string.Format("OrderID = {0}", editedItem.GetDataKeyValue("OrderID")));

    if (changedRows.Length != 1)
    {
        this.Label1.Text += "Unable to locate the Order for updating.";
        e.Canceled = true;
        return;
    }
    //Update new values
    Hashtable newValues = new Hashtable();
    e.Item.OwnerTableView.ExtractValuesFromItem(newValues, editedItem);
    changedRows[0].BeginEdit();
    try
    {
        foreach (DictionaryEntry entry in newValues)
        {
            changedRows[0][(string)entry.Key] = entry.Value;
        }
        changedRows[0].EndEdit();
    }
    catch (Exception ex)
    {
        changedRows[0].CancelEdit();
        Label1.Text += string.Format("Unable to update Orders. Reason: {0}", ex.Message);
        e.Canceled = true;
        return;
    }
}

// DELETE
protected void RadGrid1_DeleteCommand(object sender, GridCommandEventArgs e)
{
    GridDataItem dataItem = e.Item as GridDataItem;
    string ID = dataItem.GetDataKeyValue("OrderID").ToString();

    if (SessionDataSource.Rows.Find(ID) != null)
    {
        SessionDataSource.Rows.Find(ID).Delete();
    }
}
#endregion

#region DataSource
private DataTable OrdersTable()
{
    DataTable dt = new DataTable();

    dt.Columns.Add(new DataColumn("OrderID", typeof(int)));
    dt.Columns.Add(new DataColumn("OrderDate", typeof(DateTime)));
    dt.Columns.Add(new DataColumn("Freight", typeof(decimal)));
    dt.Columns.Add(new DataColumn("ShipName", typeof(string)));
    dt.Columns.Add(new DataColumn("ShipCountry", typeof(string)));

    dt.PrimaryKey = new DataColumn[] { dt.Columns["OrderID"] };

    for (int i = 0; i < 70; i++)
    {
        int index = i + 1;

        DataRow row = dt.NewRow();

        row["OrderID"] = index;
        row["OrderDate"] = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0).AddHours(index);
        row["Freight"] = index * 0.1 + index * 0.01;
        row["ShipName"] = "Name " + index;
        row["ShipCountry"] = "Country " + index;

        dt.Rows.Add(row);
    }

    return dt;
}
#endregion

Regards,
Vasko
Progress Telerik

Tags
Grid
Asked by
Venkatesh
Top achievements
Rank 1
Answers by
Princy
Top achievements
Rank 2
Venkatesh
Top achievements
Rank 1
Andrey
Telerik team
Share this question
or