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

rad grid's insert button event

2 Answers 141 Views
Grid
This is a migrated thread and some comments may be shown as answers.
mohamed
Top achievements
Rank 1
mohamed asked on 18 Apr 2011, 11:48 AM
while accessing the addnew control insert button in my rad grid. my grid disappears. I don't know how to fix this prob. If any body knows pls let me know. This is my snippet:



<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Models.aspx.cs" Inherits="TBS_HelpDesk.Views.Assets.Models"
    MasterPageFile="~/Views/Shared/MasterPage.Master" %>

<%@ Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %>
<asp:Content ID="aboutContent" ContentPlaceHolderID="MainContent" runat="server">
    <div style="width: 500px; height: 600px;">
        <telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">
            <AjaxSettings>
                <telerik:AjaxSetting AjaxControlID="RadComboBox1">
                    <UpdatedControls>
                        <telerik:AjaxUpdatedControl ControlID="RadComboBox1" UpdatePanelHeight="" />
                        <telerik:AjaxUpdatedControl ControlID="RadGrid1" UpdatePanelHeight="" />
                    </UpdatedControls>
                </telerik:AjaxSetting>
                <telerik:AjaxSetting AjaxControlID="RadGrid1">
                    <UpdatedControls>
                        <telerik:AjaxUpdatedControl ControlID="RadComboBox1" UpdatePanelHeight="" />
                        <telerik:AjaxUpdatedControl ControlID="RadGrid1" UpdatePanelHeight="" />
                    </UpdatedControls>
                </telerik:AjaxSetting>
            </AjaxSettings>
        </telerik:RadAjaxManager>
        <telerik:RadComboBox ID="RadComboBox1" runat="server" Width="200" AutoPostBack="true"
            AppendDataBoundItems="true" OnSelectedIndexChanged="RadComboBox1_SelectedIndexChanged">
        </telerik:RadComboBox>
        <telerik:RadGrid ID="RadGrid1" runat="server" AllowAutomaticInserts="True" AllowAutomaticUpdates="True"
            GridLines="None" AllowPaging="True" AllowSorting="True" Skin="Office2007" OnItemCommand="RadGrid1_ItemCommand"
            AutoGenerateColumns="False" >
            <MasterTableView CommandItemDisplay="Top" EditMode="PopUp" EnableHeaderContextMenu="true">
                <PagerStyle BackColor="#D8EBFC" />
                <HeaderStyle CssClass="dataheadcolor" />
                <RowIndicatorColumn>
                    <HeaderStyle Width="20px"></HeaderStyle>
                </RowIndicatorColumn>
                <ExpandCollapseColumn>
                    <HeaderStyle Width="20px"></HeaderStyle>
                </ExpandCollapseColumn>
                <CommandItemSettings ExportToPdfText="Export to Pdf"></CommandItemSettings>
                <Columns>
                    <telerik:GridEditCommandColumn ButtonType="ImageButton" />
                    <telerik:GridNumericColumn DataField="Model_ID" HeaderText="Model Id" SortExpression="Model_ID"
                        UniqueName="Model_ID">
                    </telerik:GridNumericColumn>
                    <telerik:GridBoundColumn DataField="Model_Name" HeaderText="Model Name" SortExpression="Model_Name"
                        UniqueName="Model_Name">
                    </telerik:GridBoundColumn>
                    <telerik:GridBoundColumn DataField="Model_Description" DataType="System.Boolean"
                        HeaderText="Model Description" SortExpression="Model_Description" UniqueName="Model_Description">
                    </telerik:GridBoundColumn>
                    <telerik:GridButtonColumn CommandName="Delete" ButtonType="ImageButton" UniqueName="DeleteColumn"
                        CommandArgument="Child" ConfirmDialogType="RadWindow" ConfirmText="Are You Sure Want To Delete This Record?"
                        ConfirmTitle="Delete Confirm" />
                </Columns>
                <EditFormSettings ColumnNumber="3" CaptionFormatString="Model Create">
                    <EditColumn UniqueName="EditCommandColumn1">
                    </EditColumn>
                    <FormTemplate>
                        <table cellspacing="2" cellpadding="1" width="100%" border="1">
                            <tr>
                                <td>
                                    <asp:Label runat="server" Text="Manuf" ID="label1"></asp:Label>
                                </td>
                                <td>
                                    <asp:TextBox Width="200px" ID="Model_ID" AutoCompleteType="Disabled" runat="server"
                                        Text='<%# Bind("Model_ID") %>'></asp:TextBox>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    Model Name
                                </td>
                                <td>
                                    <asp:TextBox Width="200px" ID="Model_Name" AutoCompleteType="Disabled" runat="server"
                                        Text='<%# Bind("Model_Name") %>'></asp:TextBox>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    Model Description
                                </td>
                                <td>
                                    <asp:TextBox Width="200px" ID="Model_Description" AutoCompleteType="Disabled" runat="server"
                                        Text='<%# Bind("Model_Description") %>'></asp:TextBox>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <asp:Button ID="Button1" runat="server" Text='<%# (Container is GridEditFormInsertItem) ? "Insert" : "Update" %>'
                                        CommandName='<%# (Container is GridEditFormInsertItem) ? "PerformInsert" : "Update" %>'>
                                    </asp:Button>
                                    <asp:Button ID="Button2" runat="server" Text="Cancel" CausesValidation="false" CommandName="Cancel">
                                    </asp:Button>
                                </td>
                            </tr>
                        </table>
                    </FormTemplate>
                </EditFormSettings>
            </MasterTableView>
        </telerik:RadGrid>
    </div>
</asp:Content>











using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;

namespace TBS_HelpDesk.Views.Assets
{
    public partial class Models : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadManufacturers();
            }
        }
        protected void LoadManufacturers()
        {
            DataTable dtTable = new DataTable();
            string conn = ConfigurationManager.ConnectionStrings["TBSHelpDeskLiveDB_ConnectionString"].ToString();
            SqlDataAdapter sqladp = new SqlDataAdapter();
            SqlConnection sqlconn = new SqlConnection(conn);
            sqlconn.Open();

            try
            {
                string selectQuery = "SELECT * FROM [ASSETMANUFACTURERS] order by Manuf_ID asc";
                sqladp.SelectCommand = new SqlCommand(selectQuery, sqlconn);
                sqladp.Fill(dtTable);

                RadComboBox1.DataValueField = "Manuf_ID";
                RadComboBox1.DataTextField = "Manuf_Name";
                RadComboBox1.DataSource = dtTable;
                RadComboBox1.DataBind();
                RadComboBox1.Items.Insert(0, new RadComboBoxItem("- Select Manufacturers Name -"));

            }
            finally
            {
                sqlconn.Close();
            }
        }
        protected void LoadModels(string Manuf_ID)
        {
            SqlConnection connection = new SqlConnection(
      ConfigurationManager.ConnectionStrings["TBSHelpDeskLiveDB_ConnectionString"].ConnectionString);

            SqlDataAdapter adapter = new SqlDataAdapter("SELECT Model_ID,Model_Name,Model_Description FROM AssetModels WHERE Model_Manuf_ID=@Manuf_ID ORDER By Model_Manuf_ID", connection);
            adapter.SelectCommand.Parameters.AddWithValue("@Manuf_ID", RadComboBox1.SelectedValue);
            DataTable dt = new DataTable();
            adapter.Fill(dt);
            RadGrid1.DataSource = dt;
            RadGrid1.DataBind();
        }

        protected void RadComboBox1_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            LoadModels(e.Text);
        }
        //protected void RadGrid1_RowDataBound1(object sender, GridViewRowEventArgs e)
        //{
        //    if (e.Row.RowType == DataControlRowType.DataRow)
        //    {
        //        e.Row.Attributes.Add("id", e.Row.RowIndex.ToString());
        //        e.Row.Attributes.Add("onclick", "MarkRow(" + e.Row.RowIndex.ToString() + ");");
        //    }
        //}
        protected void RadGrid1_ItemCommand(object source, GridCommandEventArgs e)
        {

            SqlConnection connection = new SqlConnection(
      ConfigurationManager.ConnectionStrings["TBSHelpDeskLiveDB_ConnectionString"].ConnectionString);

            DataTable dtTable = new DataTable();
            string conn = ConfigurationManager.ConnectionStrings["TBSHelpDeskLiveDB_ConnectionString"].ToString();
            SqlDataAdapter sqladp = new SqlDataAdapter();
            SqlConnection sqlconn = new SqlConnection(conn);
            SqlCommand sqlcmd = new SqlCommand();

            if (e.CommandName == RadGrid.PerformInsertCommandName)
            {
                GridEditFormInsertItem insertedItem = (GridEditFormInsertItem)e.Item;

                RadNumericTextBox Model_ID = (e.Item as GridEditFormInsertItem)["Model_ID"].Controls[0] as RadNumericTextBox;
                TextBox Model_Name = (e.Item as GridEditFormInsertItem)["Model_Name"].Controls[0] as TextBox;
                TextBox Model_Description = (e.Item as GridEditFormInsertItem)["Model_Description"].Controls[0] as TextBox;


                try
                {
                    sqlconn.Open();
                    string insertQuery = "INSERT INTO [AssetModels] ([Model_Manuf_ID],[Model_ID],[Model_Name], [Model_Description]) VALUES ('" + RadComboBox1.SelectedValue + "','" + Model_ID.Text + "','" + Model_Name.Text + "','" + Model_Description.Text + "')";
                    sqlcmd.CommandText = insertQuery;
                    sqlcmd.Connection = sqlconn;
                    sqlcmd.ExecuteNonQuery();

                    SqlDataAdapter adapter = new SqlDataAdapter("SELECT Model_ID,Model_Name,Model_Description FROM AssetModels WHERE Model_Manuf_ID=@Manuf_ID ORDER By Model_ID", connection);
                    adapter.SelectCommand.Parameters.AddWithValue("@Manuf_ID", RadComboBox1.SelectedValue);
                    DataTable dt = new DataTable();
                    adapter.Fill(dt);
                    RadGrid1.DataSource = dt;
                    RadGrid1.DataBind();
                }
                catch (Exception ex)
                {
                    RadGrid1.Controls.Add(new LiteralControl("Unable to insert Employee. Reason: " + ex.Message));
                }
                RadGrid1.MasterTableView.IsItemInserted = false;
                RadGrid1.DataBind();
                e.Canceled = true;
            }
            else if (e.CommandName == RadGrid.UpdateCommandName)
            {
                GridEditableItem editedItem = e.Item as GridEditableItem;

                RadNumericTextBox Model_ID = (e.Item as GridEditableItem)["Model_ID"].Controls[0] as RadNumericTextBox;
                TextBox Model_Name = (e.Item as GridEditableItem)["Model_Name"].Controls[0] as TextBox;
                TextBox Model_Description = (e.Item as GridEditableItem)["Model_Description"].Controls[0] as TextBox;

                try
                {
                    sqlconn.Open();
                    string updateQuery = "UPDATE [AssetModels] SET [Model_Name] = '" + Model_Name.Text + "', [Model_Description] = '" + Model_Description.Text + "' WHERE [Model_ID] = '" + Model_ID.Text + "'";
                    sqlcmd.CommandText = updateQuery;
                    sqlcmd.Connection = sqlconn;
                    sqlcmd.ExecuteNonQuery();
                    SqlDataAdapter adapter = new SqlDataAdapter("SELECT Model_ID,Model_Name,Model_Description FROM AssetModels WHERE Model_Manuf_ID=@Manuf_ID ORDER By Model_ID", connection);
                    adapter.SelectCommand.Parameters.AddWithValue("@Manuf_ID", RadComboBox1.SelectedValue);
                    DataTable dt = new DataTable();
                    adapter.Fill(dt);
                    RadGrid1.DataSource = dt;
                    RadGrid1.DataBind();
                    sqlconn.Close();
                }
                catch (Exception ex)
                {
                    RadGrid1.Controls.Add(new LiteralControl("Unable to update Employee. Reason: " + ex.Message));

                }
                RadGrid1.EditIndexes.Clear();
                RadGrid1.DataBind();
                e.Canceled = true;
            }
            else if (e.CommandName == RadGrid.DeleteCommandName)
            {
                GridDataItem item = (GridDataItem)e.Item;
                string Model_Manuf_ID = item["Model_Manuf_ID"].Text;

                try
                {
                    sqlconn.Open();
                    string deleteQuery = "DELETE FROM [AssetModels] WHERE [Model_Manuf_ID] ='" + Model_Manuf_ID + "'";
                    sqlcmd.CommandText = deleteQuery;
                    sqlcmd.Connection = sqlconn;
                    sqlcmd.ExecuteNonQuery();
                    string selectQuery = "SELECT Model_Manuf_ID, Manuf_Name, Manuf_Description, Manuf_Inactive FROM [AssetModels] order by Model_Manuf_ID asc";
                    sqladp.SelectCommand = new SqlCommand(selectQuery, sqlconn);
                    sqladp.Fill(dtTable);
                    RadGrid1.DataSource = dtTable;
                    sqlconn.Close();
                }
                catch (Exception ex)
                {
                    RadGrid1.Controls.Add(new LiteralControl("Unable to delete Id. Reason: " + ex.Message));
                    e.Canceled = true;
                }

            }
        }
    }
}

2 Answers, 1 is accepted

Sort by
0
Accepted
Princy
Top achievements
Rank 2
answered on 18 Apr 2011, 01:34 PM
Hello Mohamed,

This problem occurs because you are binding the grid in PageLoad event, which is Simple data binding technique. If you are using any advanced feature in grid(like insert/update/delete operations), then a better approach is using "AdvancedData binding" using NeedDataSource event.

For more information about this can be available here.
Advanced Data-binding (using NeedDataSource event)

Thanks,
Princy.
0
mohamed
Top achievements
Rank 1
answered on 18 Apr 2011, 01:50 PM
Thanks For Ur Replay princy.

Thanks
Tags
Grid
Asked by
mohamed
Top achievements
Rank 1
Answers by
Princy
Top achievements
Rank 2
mohamed
Top achievements
Rank 1
Share this question
or