Click here to Skip to main content
15,886,919 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
Hi
I have used the dataSource Manually(Connecting in Properties) as well as in coding ..
I am working on RadGrid CRUD operation,While connecting the database in code it shows object refernce is not set.

What I have tried:

C#
<pre>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Text;
using System.Web.UI.WebControls;
using System.Data.Sql;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using Telerik.Web.UI;


namespace Telerik08._03
{
    public partial class Sample123 : System.Web.UI.Page
    {
        SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["sqlconnection"].ConnectionString);
        
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                bind();
            }
        }




        private static void ShowCheckedItems(Telerik.Web.UI.RadComboBox comboBox, Literal literal)
        {
            //var obj = new StringBuilder();
            //var collection = comboBox.CheckedItems;

            //if (collection.Count != 0)
            //{
            //    obj.Append("<h3>Checked Items:</h3><ul class=\"results\">");

            //    foreach (var item in collection)
            //        obj.Append("<Items>" + item.Text + "</Items>");

            //    obj.Append("</ul>");

            //    //    literal.Text = obj.ToString();
            //}
            //else
            //{
            //    literal.Text = "<p>No items selected</p>";
            //}
        }
        
        protected void RadComboBox1_SelectedIndexChanged(object sender, Telerik.Web.UI.RadComboBoxSelectedIndexChangedEventArgs e)
        {

        }
        
        protected void Button1_Click(object sender, EventArgs e)
        {
            //ShowCheckedItems(RadComboBox2, itemsClientSide);
        }
        protected void RadComboBox2_DataBound(object sender, EventArgs e)
        {

           
        }
        protected void RadComboBox2_ItemsRequested(object sender, RadComboBoxItemsRequestedEventArgs e)
        {

            //string sql = "SELECT * from gvdetails17 " ;

            //SqlDataSource1.SelectCommand = sql;
            //RadComboBox2.DataBind();
        }
        protected void RadComboBox2_ItemDataBound(object sender, RadComboBoxItemEventArgs e)
        {
            //e.Item.Value = ((DataRowView)e.Item.DataItem)["EmpId"].ToString()
            //    + ";" + ((((DataRowView)e.Item.DataItem)["EmpName"].ToString()))
            //    + ";" + (((DataRowView)e.Item.DataItem)["Dep"].ToString());
            //e.Item.Text = ((DataRowView)e.Item.DataItem)["Dep"].ToString();
            //e.Item.Text = ((DataRowView)e.Item.DataItem)["Dep"].ToString();
           
            
        }
        

         protected void RadGrid1_ItemUpdated(object source, Telerik.Web.UI.GridUpdatedEventArgs e)
        {

             


        }
         protected void bind()
         {
             cn.Open();
             SqlCommand cmd = new SqlCommand("Select * from gvdetails17", cn);
             SqlDataAdapter da = new SqlDataAdapter(cmd);
             DataSet ds = new DataSet();
             da.Fill(ds);
             cn.Close();
             if (ds.Tables[0].Rows.Count > 0)
             {
                 RadGrid1.DataSource = ds;
                 RadGrid1.DataBind();
             }
         }

         protected void RadGrid1_DeleteCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
         {
             
             GridDataItem item = (GridDataItem)e.Item;
             
             string EmployeeID = item.OwnerTableView.DataKeyValues[item.ItemIndex]["EmpID"].ToString();
             try
             {
                
                  cn.Open();
                  SqlCommand cmd = new SqlCommand("delete from gvdetails17 where EmpId=" + EmployeeID, cn);
            int result = cmd.ExecuteNonQuery();
            cn.Close();
                 

             }
             catch (Exception ex)
             {
                 RadGrid1.Controls.Add(new LiteralControl("Unable to delete Employee. Reason: " + ex.Message));
                 e.Canceled = true;
             }


         }  
        public RadComboBoxItem item { get; set; }

        public RadComboBoxItem EmpName { get; set; }

        protected void RadComboBox2_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
        {

        }


My aspx page
ASP.NET
<pre><%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Sample123.aspx.cs" Inherits="Telerik08._03.Sample123" %>
<%@ Register TagPrefix="telerik" Namespace="Telerik.Web.UI" Assembly="Telerik.Web.UI" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
        <style>
            .col1,
.col2,
.col3 {
    margin: 0;
    padding: 0 5px 0 0;
    width: 30%;
    line-height: 14px;
    float: left;
}
        .multipleRowsColumns .rcbItem,
.multipleRowsColumns .rcbHovered {
    float: left;
    margin: 0 1px;
    min-height: 13px;
    overflow: hidden;
    padding: 2px 19px 2px 6px;
    width: 193px;
}
 .exampleRadComboBox.RadComboBoxDropDown .rcbHeader {
    padding: 5px 27px 4px 7px;
}
 
.results {
    display: block;
    margin-top: 20px;
}



        .RadDock a {
    color: #58954D;
}
        .alternateItemStyle
{
    background-color: #FFFFFF;
    color: #000000;
    font-size: 8pt;
}

 
.higherZIndex {
    z-index: 2;
}

.demo-container.wrapper {
    background-image: url(images/background.png);
    background-repeat: no-repeat;
    width: 260px;
    padding: 190px 30px 10px;
    margin: 0 auto;
    border: 0 none;
 
}
 
.demo-container > .RadInput,
.demo-container .RadPicker,
.button-wrapper .RadButton {
    width: 100%;
    margin-bottom: 10px;
}
 
html .rbCheckBox {
    vertical-align: middle;
}
 
.button-wrapper {
    padding: 25px 13px 0;
}
 
.background-material .rbCheckBox,
.background-material .RadLabel {
    margin-left: 13px;
    margin-right: -13px;
}
    </style>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/jquery-ui.js" type="text/javascript"></script>
    <link href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/themes/start/jquery-ui.css"
        rel="stylesheet" type="text/css" />
    <script type="text/javascript">
<%--     $(function () {

            var grid = document.getElementById('<%= RadGrid1.ClientID%>');
            $('tr', grid).on('dblclick', function (obj, b) {

                $("#id").html($(".clsempid", $(this).closest("tr")).html());
               
                $("#dialog").dialog({
                    title: "View Details",
                    buttons: {
                        Ok: function () {
                            $(this).dialog('close');
                        }
                    },
                    modal: true
                });

            })
        });--%>
</script>
</head>
<body>
    <form id="form1" runat="server">
        <telerik:RadScriptManager runat="server" ID="RadScriptManager1" />
    <telerik:RadSkinManager ID="RadSkinManager1" runat="server" ShowChooser="true" />
    <telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">
        <AjaxSettings>
            <telerik:AjaxSetting AjaxControlID="Button1">
                <UpdatedControls>
                    <telerik:AjaxUpdatedControl ControlID="Label1" />
                </UpdatedControls>
            </telerik:AjaxSetting>
        </AjaxSettings>
    </telerik:RadAjaxManager>

        <table style="margin-left:471px;margin-bottom:-27px">
            <tr>
                <td>
                    <telerik:RadComboBox RenderMode="Classic" ID="RadComboBox1" Text="Select" runat="server"
                        CheckBoxes="true" EnableCheckAllItemsCheckBox="true" MarkFirstMatch="true"  HighlightTemplatedItems="true"
                        AutoPostBack="true" ValueField="--Select--" OnSelectedIndexChanged="RadComboBox1_SelectedIndexChanged"
          > <%--HighlightTemplatedItems="true" OnClientItemsRequested="UpdateItemCountField"
            OnDataBound="RadComboBox1_DataBound" OnItemDataBound="RadComboBox1_ItemDataBound"
            OnItemsRequested="RadComboBox1_ItemsRequested" DropDownCssClass="exampleRadComboBox"> --%>
                        <Items>

                            <telerik:RadComboBoxItem Text="Dotnet" />
                            <telerik:RadComboBoxItem Text="Java" />
                            <telerik:RadComboBoxItem Text="Sales" />
                            <telerik:RadComboBoxItem Text="Hr" />
                            <telerik:RadComboBoxItem Text="Admin" />
                        </Items>
                    </telerik:RadComboBox>
                </td>
            </tr>
        </table>
        <telerik:RadComboBox RenderMode="Lightweight" runat="server" ID="RadComboBox2" style="margin-left:671px;margin-bottom:24px;width:250px"
             DataSourceID="SqlDataSource1" AutoPostBack="true" Text="Select" MarkFirstMatch="true" EnableLoadOnDemand="true" HighlightTemplatedItems="true"
             ValueField="--Select--"
            OnDataBound="RadComboBox2_DataBound" OnItemDataBound="RadComboBox2_ItemDataBound"
              OnSelectedIndexChanged="RadComboBox2_SelectedIndexChanged">
           <HeaderTemplate>
                <ul>
                    <li class="col1">Employee ID</li>
                    <li class="col2">Employee Name</li>
                    <li class="col3">Salary</li>
                    <li class="col3">Department</li>
                    <li class="col3">Age</li>
                </ul>
            </HeaderTemplate>
            <ItemTemplate>
                <table>
                    <tr>
                        <td style="width: 225px">
                            <%#DataBinder.Eval(Container.DataItem,"EmpId") %>

                        </td>
                        <td style="width: 225px">
                            <%#DataBinder.Eval(Container.DataItem,"EmpName") %>

                        </td>
                        <td style="width: 225px">
                            <%#DataBinder.Eval(Container.DataItem,"Sal") %>

                        </td>
                        <td style="width: 225px">
                            <%#DataBinder.Eval(Container.DataItem,"Dep") %>

                        </td>
                        <td style="width: 225px">
                            <%#DataBinder.Eval(Container.DataItem,"Age") %>

                        </td>
                    </tr>


                </table>
            </ItemTemplate>
            <FooterTemplate>
                A total of
                <asp:Literal runat="server" ID="RadComboItemsCount" />
                items
            </FooterTemplate>
        </telerik:RadComboBox>
        <telerik:RadButton RenderMode="Lightweight" runat="server" ID="Button1" Text="Select" OnClick="Button1_Click" ></telerik:RadButton>
        <asp:Label runat="server" ID="Label1" />

        <div style="margin-top:-46px;background-color:lightgreen;     border-collapse: collapse;
               background-color: lightgreen;">


            <telerik:RadGrid ID="RadGrid1"  ShowStatusBar="true"   margin-top="-46px" Height="500px" runat="server"
                ShowGroupPanel="True" GridLines="None"  
                AllowPaging="True" AllowAutomaticDeletes="True" AllowAutomaticInserts="True"
                AllowFilteringByColumn="True"  OnDeleteCommand="RadGrid1_DeleteCommand"
              
                AllowSorting="True" AutoGenerateDeleteColumn="true" 
                AutoGenerateEditColumn="True" CellSpacing="0" DataSourceID="SqlDataSource1" 
                Skin="Forest" AllowCustomPaging="True" AllowMultiRowEdit="True" AllowMultiRowSelection="True" PageSize="20" >
               


                <HeaderContextMenu>
                    <CollapseAnimation Type="OutQuint" Duration="200" />

                </HeaderContextMenu>
                <MasterTableView GroupLoadMode="Client" AutoGenerateColumns="False"  DataSourceID="SqlDataSource1">
                    <Columns>
                        
                        <telerik:GridBoundColumn DataField="EmpId" DataType="System.Int32" FilterControlAltText="Filter EmpId column" HeaderText="EmployeeId" SortExpression="EmpId" UniqueName="EmpId">
                        </telerik:GridBoundColumn>
                        <telerik:GridBoundColumn DataField="EmpName" FilterControlAltText="Filter EmpName column" HeaderText="EmployeeName" SortExpression="EmployeeName" UniqueName="EmpName">
                        </telerik:GridBoundColumn>
                        <telerik:GridBoundColumn DataField="Dep" FilterControlAltText="Filter Dep column" HeaderText="Department" SortExpression="Dep" UniqueName="Department">
                        </telerik:GridBoundColumn>
                        <telerik:GridBoundColumn DataField="Age" FilterControlAltText="Filter Age column" HeaderText="Age" SortExpression="Age" UniqueName="Age">
                        </telerik:GridBoundColumn>
                        <telerik:GridBoundColumn DataField="Sal" DataType="System.Int32" FilterControlAltText="Filter Sal column" HeaderText="Salary" SortExpression="Salary" UniqueName="Sal">
                        </telerik:GridBoundColumn>
                        
                    </Columns>
                   
                    <EditFormSettings>
                        <EditColumn FilterControlAltText="Filter EditCommandColumn column"></EditColumn>
                        

                    </EditFormSettings>
                    
                </MasterTableView>
                <%--<ClientSettings AllowDragToGroup="true" AllowColumnsReorder="True" ReorderColumnsOnClient="True">


                 <Scrolling AllowScroll="True" UseStaticHeaders="True" />


             </ClientSettings>--%>
                 
            
                <FilterMenu>

                    

                </FilterMenu>

            </telerik:RadGrid>
            <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:SST321ConnectionString %>" SelectCommand="SELECT EmpId,EmpName,Dep,Age,Sal FROM [gvdetails17]"></asp:SqlDataSource>
        <asp:Literal ID ="itemsClientSide" runat="server" />
        </div>
    </form>
</body>
</html>
Posted
Updated 10-Mar-17 1:13am
Comments
Graeme_Grant 10-Mar-17 5:23am    
Developers sacrifice and contribute their time for free to help fellow developers resolve difficulties. It is important that you are crystal clear about what you are experiencing with plenty of information so that your time and theirs are not wasted. The clearer the question, the better chance that you will get a favorable response in a timely manner.

Please take the time to look at these links provided before posting questions:
* Basic Debugging with Visual Studio 2010 - YouTube[^]
* Some guidelines for posting questions in the forums[^]
* Tales from the Evil Empire - Asking questions is a skill[^]

Once you are ready update the question with clear and concise details, sample code, any error messages (includding inner exception details), etc, please click on Improve question to add more info to the question.
Karthik_Mahalingam 10-Mar-17 5:31am    
which line ?
Member 12605293 10-Mar-17 6:47am    
Connection string line "SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["sqlconnection"].ConnectionString);"
Karthik_Mahalingam 10-Mar-17 6:52am    
post the connectionstring section from config file.
Member 12605293 10-Mar-17 6:57am    
Done posting sir

You have this in web.config:
<add name="SST321ConnectionString" 
and then you try to reference it like this:
ConfigurationManager.ConnectionStrings["sqlconnection"].ConnectionString
You don't have a connection string named "sqlconnection." You have one named "SST321ConnectionString"
 
Share this answer
 
change the connection string name

SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["SST321ConnectionString"].ConnectionString);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900