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

Add/Edit/Delete in Grid

6 Answers 434 Views
Grid
This is a migrated thread and some comments may be shown as answers.
George
Top achievements
Rank 1
George asked on 31 Oct 2011, 06:31 PM
Hello everyone,

What is the easiest way to add/edit/delete records from a rad grid?
I tried to look for online tutorials but there are none, the one I found is in VB but I need it in C#.
I tried checking the videos but they wouldn't load even though I have a good connection.

If you can guide me step by step, I'll be appreciated.

Thanks.

6 Answers, 1 is accepted

Sort by
0
Elliott
Top achievements
Rank 2
answered on 31 Oct 2011, 10:05 PM
hey George-I didn't delete any of the stuff Telerik automatically puts in the .aspx file
it uses Northwind's Shippers table
<connectionStrings>
    <add name="Northwind" connectionString="Data Source=none of your business;Initial Catalog=Northwind;User ID=sa;Password=xxxxx"/>
</connectionStrings>
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head runat="server">
    <title>Simple Grid</title>
    <telerik:RadStyleSheetManager id="rssManager" runat="server" />
</head>
<body>
    <form id="frmSimple" runat="server">
    <telerik:RadScriptManager ID="rsManager" runat="server">
        <Scripts>
            <%--Needed for JavaScript IntelliSense in VS2010--%>
            <%--For VS2008 replace RadScriptManager with ScriptManager--%>
            <asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.Core.js" />
            <asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.jQuery.js" />
            <asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.jQueryInclude.js" />
        </Scripts>
    </telerik:RadScriptManager>
    <script type="text/javascript">
        //Put your JavaScript code here.
    </script>
    <telerik:RadAjaxManager ID="raManager" runat="server">
    </telerik:RadAjaxManager>
    <div>
        <telerik:RadGrid ID="rgShippers" AutoGenerateColumns="False" OnNeedDataSource="rgShipper_NeedDataSource" OnItemCommand="rgShipper_ItemCommand" runat="server" >
        <MasterTableView DataKeyNames="ShipperID" CommandItemDisplay="Top" EditMode="InPlace" >
        <Columns>
            <telerik:GridBoundColumn UniqueName="ShipperID" DataField="ShipperID" HeaderText="ID" ReadOnly="true" >
            </telerik:GridBoundColumn>
            <telerik:GridBoundColumn UniqueName="CompanyName" DataField="CompanyName" HeaderText="Company Name">
            </telerik:GridBoundColumn>
            <telerik:GridBoundColumn UniqueName="Phone" DataField="Phone" HeaderText="Phone">
            </telerik:GridBoundColumn>
            <telerik:GridEditCommandColumn EditText="Edit" />                      
            <telerik:GridButtonColumn UniqueName="DeleteColumn" CommandName="Delete" Text="Delete" />                  
        </Columns>
    </MasterTableView>
    </telerik:RadGrid>
    </div>
    </form>
</body>
</html>
you said c#
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Telerik.Web.UI;
 
public partial class Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
 
    protected void rgShipper_NeedDataSource(object sender,EventArgs e)
    {
        DataSet ds = null;
        DataAccess ws = new DataAccess();
        ds = ws.GetShipper();
        rgShippers.DataSource = ds;
    }
 
    protected void rgShipper_ItemCommand(object sender, GridCommandEventArgs e)
    {
        GridDataItem gdItem=null;
        GridEditFormItem gefItem=null;
        switch (e.CommandName)
        {
            case "PerformInsert":
                gdItem = (GridDataItem)e.Item;
                InsertShipper(gdItem);
                break;
            case "Edit":
                gdItem = (GridDataItem)e.Item;
                break;
            case "Update":
                gdItem = (GridDataItem)e.Item;
                UpdateShipper(gdItem);
                break;
            case "Delete":
                gdItem = (GridDataItem)e.Item;
                DeleteShipper(gdItem);
                break;
        }
    }
    private void InsertShipper(GridDataItem gdItem)
    {
        TextBox txtCompanyName, txtPhone;
        int ShipperID;
 
        txtCompanyName = (TextBox)(gdItem["CompanyName"].Controls[0]);
        txtPhone = (TextBox)(gdItem["Phone"].Controls[0]);
        DataAccess ws = new DataAccess();
        ShipperID = ws.InsertShipper(txtCompanyName.Text, txtPhone.Text);
    }
 
    private void UpdateShipper(GridDataItem gdItem)
    {
        TextBox txtCompanyName, txtPhone;
        int ShipperID;
 
        ShipperID = Convert.ToInt32(gdItem.OwnerTableView.DataKeyValues[gdItem.ItemIndex]["ShipperID"]);
        txtCompanyName = (TextBox)(gdItem["CompanyName"].Controls[0]);
        txtPhone = (TextBox)(gdItem["Phone"].Controls[0]);
        DataAccess ws = new DataAccess();
        ws.UpdateShipper(ShipperID, txtCompanyName.Text, txtPhone.Text);
    }
 
    private void DeleteShipper(GridDataItem gdItem)
    {
        int ShipperID;
        ShipperID = Convert.ToInt32(gdItem.OwnerTableView.DataKeyValues[gdItem.ItemIndex]["ShipperID"]);
        DataAccess ws = new DataAccess();
        ws.DeleteShipper(ShipperID);
    }
}
in the App_Code folder
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
 
/// <summary>
/// Summary description for DataAccess
/// </summary>
public class DataAccess
{
    string strConn = "";
    SqlConnection conn = null;
    const string CONNSTR = "Northwind";
 
    public DataAccess()
    {
        ConnectionStringSettings dbConns;
        dbConns = ConfigurationManager.ConnectionStrings[CONNSTR];
        strConn = dbConns.ConnectionString;
        conn = new SqlConnection(strConn);
    }
 
    public DataSet GetShipper()
    {
        DataSet ds = null;
        SqlDataAdapter da = new SqlDataAdapter("get_shippers", conn);
        da.SelectCommand.CommandType=CommandType.StoredProcedure;
        conn.Open();
        ds = new DataSet();
        da.Fill(ds, "Shippers");
        conn.Close();
        conn.Dispose();
        da.Dispose();
        return ds;
    }
 
    public int InsertShipper(string CompanyName,string Phone)
    {
        int ShipperID = 0;
        SqlCommand cmd = null;
        SqlParameter param = null;
 
        cmd = new SqlCommand("insert_shipper", conn);
        cmd.CommandType = CommandType.StoredProcedure;
        param = new SqlParameter("@CompanyName", SqlDbType.VarChar, 40);
        param.Value=CompanyName;
        cmd.Parameters.Add(param);
        param = new SqlParameter("@Phone", SqlDbType.VarChar, 24);
        param.Value = Phone;
        cmd.Parameters.Add(param);
        conn.Open();
        ShipperID = (int)cmd.ExecuteScalar();
        conn.Close();
        conn.Dispose();
        cmd.Dispose();
        return ShipperID;
    }
 
    public void UpdateShipper(int ShipperID, string CompanyName, string Phone)
    {
        SqlCommand cmd = null;
        SqlParameter param = null;
 
        cmd = new SqlCommand("update_shipper", conn);
        cmd.CommandType = CommandType.StoredProcedure;
        param = new SqlParameter("@ShipperID", SqlDbType.Int);
        param.Value = ShipperID;
        cmd.Parameters.Add(param);
        param = new SqlParameter("@CompanyName", SqlDbType.VarChar, 40);
        param.Value = CompanyName;
        cmd.Parameters.Add(param);
        param = new SqlParameter("@Phone", SqlDbType.VarChar, 24);
        param.Value = Phone;
        cmd.Parameters.Add(param);
        conn.Open();
        cmd.ExecuteNonQuery();
        conn.Close();
        conn.Dispose();
        cmd.Dispose();
    }
 
    public void DeleteShipper(int ShipperID)
    {
        SqlCommand cmd = null;
        SqlParameter param = null;
 
        cmd = new SqlCommand("delete_shipper", conn);
        cmd.CommandType = CommandType.StoredProcedure;
        param = new SqlParameter("@ShipperID", SqlDbType.Int);
        param.Value = ShipperID;
        cmd.Parameters.Add(param);
        cmd.ExecuteNonQuery();
    }
 
}
Priyanka
Top achievements
Rank 1
commented on 03 Sep 2022, 11:57 AM

getting following  exception while using this code -

System.NullReferenceException: 'Object reference not set to an instance of an object.'

gdItem was null.

why it showing this exception?

Priyanka
Top achievements
Rank 1
commented on 03 Sep 2022, 12:00 PM

and also have query that how can i assign default value to text box while adding new record.
0
Shinu
Top achievements
Rank 2
answered on 01 Nov 2011, 04:23 AM
Hello George,

Check the following demo which implements the same functionality.
Grid / Automatic Operations.

Thanks,
Shinu.
0
George
Top achievements
Rank 1
answered on 01 Nov 2011, 10:22 AM
Thanks guys, it worked!
I finally got it to work.
Now I need to make the edit in a popup window and the delete message with a confirmation.

I have already downloaded a small demo app for this matter but I can't connect to the sql server for some reason even though everything is turned on.

I downloaded this demo app: http://www.telerik.com/community/code-library/aspnet-ajax/grid/manual-insert-update-delete-using-formtemplate-and-sql-backend.aspx
The problem is I don't know where to download the Northwind database from, I looked on google with no luck.

And since I don't have the DB, I created my own, with different db name and tables names. But it wouldn't connect.
It kept giving me the sql server is unreachable.

The original SqlConnection that came with the demo is set to this
SqlConnection("Data Source=local;Initial Catalog=Northwind;User ID=**");

So I replaced it with this
SqlConnection("Data Source=UTOPICVISION-PC\SQLEXPRESS;Initial Catalog=realestate;Integrated Security=True;");

But it's not working.
Any help on this one? 

Thanks you.
0
Elliott
Top achievements
Rank 2
answered on 01 Nov 2011, 02:40 PM
to get the edit to popup, change the EditMode=InPlace to EditMode=PopUp on the MasterTableView in the .aspx file
the delete confirmation is a little more complicated (but not much more)

as to why your ConnectionString isn't working-that's not a Telerik related problem!
as you notice-I use the sa account with the password, a big no no, for my development
what does the code look like that you use to create your connection object?
maybe you can put a SQLDataSource object and configure it (delete it after)
0
George
Top achievements
Rank 1
answered on 01 Nov 2011, 03:17 PM
Thank you! That worked, quick and painless.
The delete message is not important now, what is important is to add an "insert" button/link onto the grid to be able to add new rows.
Is there a quick way for this?

Also, I want to replace a textbox with a textarea when the edit popup appears. In standard visual studio, I have to convert the field to template field and then manually set its property to text area. But here it's different. I would appreciate it if you could guide me to it.

Thanks a lot.
0
Elliott
Top achievements
Rank 2
answered on 02 Nov 2011, 03:08 PM
again! two problems, one simpler than another
do you need a Textbox for the grid, then a popup Textarea on Insert/Edit or a different control for Insert than Edit?
if you need a textbox for the grid, a textarea in Insert/Edit then use a templated column
<telerik:GridTemplateColumn UniqueName="VendorName" HeaderText="Vendor Name" HeaderStyle-Width="200px" >
<ItemTemplate>
    <asp:Label ID="lblVendorName" Text='<%# Bind("VendorName") %>' runat="server" />
</ItemTemplate>
<EditItemTemplate>
    <telerik:RadTextBox ID="rtbVendorName" Text='<%# Eval("VendorName") %>' runat="server" />
    <asp:RequiredFieldValidator ID="rfvVendorName" ControlToValidate="rtbVendorName" ErrorMessage="*" runat="server" />
</EditItemTemplate>
</telerik:GridTemplateColumn>
to make a textarea in the RadTextBox you can experiment with properties
as for changing the Add New Record to a button in the grid=why?  you don't add a record to a line, you add one to the grid
you can put the Add New Record to the top or the bottom of the grid - or both
you can change the wording
 
Tags
Grid
Asked by
George
Top achievements
Rank 1
Answers by
Elliott
Top achievements
Rank 2
Shinu
Top achievements
Rank 2
George
Top achievements
Rank 1
Share this question
or