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

create new row in radgrid dyanamically

3 Answers 353 Views
Grid
This is a migrated thread and some comments may be shown as answers.
shivesh
Top achievements
Rank 1
shivesh asked on 10 Nov 2010, 08:08 AM
hi,
 I am using radgrid here in my button click display blank grid with a single row after inserting data in this grid i want to create a new row on button click inside grid.
in this grid have dropdown for item selection label for rate display and amount display and textbox for enter quantity amount.
here is my code with the help of that i want ot create row generation after first row plz find below...
i am using view state and plz tell me how can i store value in viewstate and then from view state to database whatever i did i am giving to u..
<asp:Button ID="btnAdd" runat="server" Text="Add" OnClick="btnAdd_click" Width="70px" />
       <br />
       <telerik:RadGrid ShowFooter="true" ID="radGrid1" runat="server" OnInsertCommand="radGrid1_InsertCommand"
           OnPreRender="radgrid1_PreRender" AutoGenerateColumns="False" GridLines="None"
           AutoGenerateEditColumn="true" AllowMultiRowEdit="True" AllowAutomaticInserts="true"
           AllowAutomaticUpdates="true" OnItemDataBound="radGrid1_ItemDataBound" OnNeedDataSource="radGrid1_NeedDataSource">
           <MasterTableView EditMode="InPlace" PageSize="5" CommandItemDisplay="None">
               <Columns>
               <telerik:GridTemplateColumn DataField="rowNumber" HeaderText="S.No.">
               <ItemTemplate>
               <asp:Label ID="lblrowNumber" runat="server" Text='<%#Eval("rowNumber")%>'></asp:Label>
               </ItemTemplate>
               </telerik:GridTemplateColumn>
                   
                   <telerik:GridTemplateColumn UniqueName="Product_Name" ReadOnly="true" HeaderText="Product Name">
                       <ItemTemplate>
                           <asp:DropDownList ID="ddl1" runat="server" AutoPostBack="true" DataTextField="product_Name"
                               DataValueField="product_Name" OnSelectedIndexChanged="ddl1_SelectedIndexChanged">
                           </asp:DropDownList>
                       </ItemTemplate>
                   </telerik:GridTemplateColumn>
                   <telerik:GridTemplateColumn UniqueName="Product_Rate" ReadOnly="true" HeaderText="Product Rate">
                       <ItemTemplate>
                           <asp:Label ID="lblRate" runat="server" Text='<%#Eval("Product_Rate") %>'></asp:Label>
                       </ItemTemplate>
                   </telerik:GridTemplateColumn>
                   <telerik:GridTemplateColumn UniqueName="Product_Quantity" HeaderText="Product Quantity">
                       <ItemTemplate>
                           <telerik:RadNumericTextBox ID="txtQuantity" AutoPostBack="true" runat="server" OnTextChanged="txtQuantity_TextChanged">
                           </telerik:RadNumericTextBox>
                       </ItemTemplate>
                   </telerik:GridTemplateColumn>
                   <telerik:GridTemplateColumn UniqueName="Product_Amount" ReadOnly="true" HeaderText="Product Amount">
                       <ItemTemplate>
                           <asp:Label ID="lblAmount" runat="server"></asp:Label>
                       </ItemTemplate>
                       <FooterStyle HorizontalAlign="Right" />
                       <FooterTemplate>
                           <asp:Button ID="btnNewRow" runat="server" Visible="true" Text="Add Item" OnClick="btnNewRow_click" /></FooterTemplate>
                   </telerik:GridTemplateColumn>
               </Columns>
           </MasterTableView>
       </telerik:RadGrid>
       <table border="0" cellpadding="0" cellspacing="0" width="100%">
           <tr>
               <td align="center">
                   <center>
                       <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="Submit" />
                       <asp:Button ID="Button1" runat="server" Text="Clear" OnClick="Clear" />
                   </center>
               </td>
           </tr>
       </table>
public partial class Test_Order : System.Web.UI.Page
    {
        DataTable dt = new DataTable();
        TableRow dr;
 
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                create_datatable();
            }
        }
        public void create_datatable()
        {
 
            dr = new TableRow();
            dt.Columns.Add(new DataColumn("rowNumber", typeof(string)));
            dt.Columns.Add("Product_Name");
            dt.Columns.Add("Product_Rate");
            dt.Columns.Add("Product_Quantity");
            dt.Columns.Add("Product_Amount");
            ViewState["Address"] = dt;
 
            radGrid1.DataSource = dt;
            radGrid1.DataBind();
 
        }
 
protected void radGrid1_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
        {
            SqlConnection connection = new SqlConnection();
            connection = new SqlConnection(ConfigurationManager.ConnectionStrings["chalk_hillConnectionString"].ConnectionString);
            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = new SqlCommand("select product_id,product_name from product_detail", connection);
 
 
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                dt.Rows.Add(dr);
                dt.AcceptChanges();
                try
                {
                    da.Fill(dt);
                }
                finally
                {
                    connection.Close();
                }
            }
            radGrid1.DataSource = dt;
 
        }
 
protected void radGrid1_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item is GridDataItem)
            {
                GridDataItem item = (GridDataItem)e.Item;
                DropDownList list = (DropDownList)item.FindControl("ddl1");
                list.Items.Insert(0, new ListItem("select", "-1"));
                SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["chalk_hillConnectionString"].ConnectionString);
                SqlDataAdapter da = new SqlDataAdapter();
                da.SelectCommand = new SqlCommand("select product_id,product_name from product_detail", con);
                DataSet ds = new DataSet();
                da.Fill(ds);
                if (ds != null)
                {
                    list.DataSource = ds;
                    list.DataTextField = "product_name";
                    list.DataValueField = "product_id";
                    list.DataBind();
                }
                list.Items.Insert(0, new ListItem("Select Item..", "0"));
                list.SelectedIndex = 0;
            }
        }
 
 protected void radGrid1_InsertCommand(object sender, EventArgs e)
        {
            isinsert = true;
        }
        protected void ddl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            DropDownList list = (DropDownList)sender;
            GridDataItem item = (GridDataItem)list.NamingContainer;
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["chalk_hillConnectionString"].ConnectionString);
            con.Open();
            SqlCommand cmd = new SqlCommand("select product_rate from product_detail where product_name='" + list.SelectedItem.Text + "'", con);
            SqlDataReader reader; ;
            reader = cmd.ExecuteReader();
            if (reader.Read())
            {
                (item.FindControl("lblRate") as Label).Text = reader["product_rate"].ToString();
            }
 
        }
 
 protected void txtQuantity_TextChanged(object sender, EventArgs e)
        {
            RadNumericTextBox textQuantity = sender as RadNumericTextBox;
 
            GridEditableItem item = textQuantity.NamingContainer as GridEditableItem;
            Label lbl1 = item["Product_Rate"].FindControl("lblRate") as Label;
            Label lbl3 = item["Product_Amount"].FindControl("lblAmount") as Label;
            lbl3.Text = (int.Parse(lbl1.Text) * int.Parse(textQuantity.Text)).ToString();
            create_datatable_row();
             
        }
        protected void btnNewRow_click(object sender, EventArgs e)
        {
            AddNewRowToGrid();
        }
         
        private void AddNewRowToGrid()
        {
            
            if (ViewState["Address"] != null)
            {
                DataTable dtCurrenttable = (DataTable)ViewState["Address"];
                DataRow drCurrentRow = null;
                if (dtCurrenttable.Rows.Count > 0)
                {
                    drCurrentRow = dtCurrenttable.NewRow();
                    drCurrentRow["rowNumber"] = dtCurrenttable.Rows.Count + 1;
                    dtCurrenttable.Rows.Add(drCurrentRow);
                    ViewState["Address"] = dtCurrenttable;
                           radGrid1.DataSource = dtCurrenttable;
                    radGrid1.DataBind();
                }
            }
            else
            {
                Response.Write("ViewState is null");
            }
        }
 
        //for display blank grid on button click creation....
 
        protected void btnAdd_click(object sender, EventArgs e)
        {
 
            dt = (DataTable)ViewState["Address"];
            if (dt.Rows.Count != 0)
            {
                if (dt.Columns.Count != 0)
                {
                    create_datatable();
                }
                else
                {
                    create_datatable_row();
                }
            }
            DataRow dr = dt.NewRow();
            dr["rowNumber"] = 1;
            dt.Rows.Add(dr);
            radGrid1.DataSource = dt;
            radGrid1.DataBind();
        }
        private void create_datatable_row()
        {
            DataRow dr = dt.NewRow();
            dt.Rows.Add(dr);
        }
        bool isinsert = false;
        protected void radgrid1_PreRender(object sender, EventArgs e)
        {
            if (isinsert)
            {
                isinsert = false;
                radGrid1.MasterTableView.IsItemInserted = true;
                radGrid1.MasterTableView.Rebind();
            }
 
        }
 
 
    }

it is createing new row but last row value destroy when i click on button newitwm inside radgrid plz tell me how can i save these value in viewstate and after final submit all value in database and one more thing same item selected twice from user while i want user select on item in one order.

3 Answers, 1 is accepted

Sort by
0
Marin
Telerik team
answered on 12 Nov 2010, 05:09 PM
Hello shivesh,

The main purpose of ViewState it to persist values of control properties across postbacks and track their changes. It is not good idea to store huge application data there since this could affect performance. Storing data in the ViewState can accomplished in the standard way by assigning value to a key: ViewState["key"]=value and then accessing it back at any time. 
When you bind the grid using Advance databinding with the NeedDataSource event the state of the grid is automatically persisted and recreated again on postback. In order to perform CRUD operations directly to the database you can handle the respective command event (insert/update/delete) and perform the relevant operation there (as shown in this help article). These commands can be fired automatically from inside the grid when the CommandName property of the source is set to the correct value (e.g. <asp:Button ID="btnInser" runat="server" Text="Insert" CommandName="PerformInsert" />) or manually from code-behind when calling the relevant method of GridTableView (PerformInsert, PerformUpdate, PerformDelete) with an argument the respective GridDataItem. More information on this approach can be found here. You can also manually extract the value entered by the user and store them in the database accessing them directly or using the ExtractValuesFromItem to retrieve them.


Kind regards,
Marin
the Telerik team
Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items
0
shivesh
Top achievements
Rank 1
answered on 15 Nov 2010, 08:28 AM
Hi Marin,
As you seen my code i am generating row manually on button click in this case when adding new row then last row data lost and
my requirement is that first user make all item entry then push submit button and all data save to database in database i am using order table
and order detail table order table save only order no while order detail table save all item records with same order id.
how can i perform this task may be i am facing problem due to i m new in .net as well as rad control so plz help
Thanks
0
Marin
Telerik team
answered on 16 Nov 2010, 09:27 AM
Hello shivesh,

You can achieve your goal the following way:
In the method for the button that adds a new row (I assume this is btnAdd_click) you may persist in ViewState all the values of the items already entered by the user and then at the end of the method after grid is rebind (this is done with the rebind method radgrid1.Rebind()) you can restore the values back and set them to the corresponding controls. Here is a code sample showing the modifications of the click handler for the add button that accomplishes this task:
protected void btnAdd_click(object sender, EventArgs e)
    {
        foreach (GridDataItem item in radGrid1.Items)
        {
            ViewState["gridItem_Product_Name"+item.ItemIndex] = (item["Product_Name"].Controls[1] as DropDownList).SelectedIndex;
            ViewState["gridItem_Product_Rate" + item.ItemIndex] = (item["Product_Rate"].Controls[1] as Label).Text;
            ViewState["gridItem_Product_Quantity" + item.ItemIndex] = (item["Product_Quantity"].Controls[1] as RadNumericTextBox).Text;
            ViewState["gridItem_Product_Amount" + item.ItemIndex] = (item["Product_Amount"].Controls[1] as Label).Text;
  
        }
        dt = (DataTable)ViewState["Address"];
        if (dt.Rows.Count != 0)
        {
            if (dt.Columns.Count == 0)
            {
                create_datatable();
            }
        }
        DataRow dr = dt.NewRow();
        dr["rowNumber"] = 1;
        dt.Rows.Add(dr);
        radGrid1.DataSource = dt;
        radGrid1.Rebind();
        foreach (GridDataItem item in radGrid1.Items)
        {
            if (ViewState["gridItem_Product_Name" + item.ItemIndex] != null)
            {
                (item["Product_Name"].Controls[1] as DropDownList).SelectedIndex =
                     (int)ViewState["gridItem_Product_Name" + item.ItemIndex];
            }
            if (ViewState["gridItem_Product_Rate" + item.ItemIndex] != null)
            {
                (item["Product_Rate"].Controls[1] as Label).Text =
                    ViewState["gridItem_Product_Rate" + item.ItemIndex].ToString();
            }
            if (ViewState["gridItem_Product_Quantity" + item.ItemIndex] != null)
            {
                (item["Product_Quantity"].Controls[1] as RadNumericTextBox).Text =
                    ViewState["gridItem_Product_Quantity" + item.ItemIndex].ToString();
            }
            if (ViewState["gridItem_Product_Amount" + item.ItemIndex] != null)
            {
                (item["Product_Amount"].Controls[1] as Label).Text =
                    ViewState["gridItem_Product_Amount" + item.ItemIndex].ToString();
            }
  
        }
    }

If you wish to save the data entered by user on the submit button clickm, you may simply obtain a reference to the DataTable that you have previously stored in the ViewState and  then using standard ADO.NET features to save it in a database. Here is a sample code (for simplicity I have omitted tha actual realization on persisting the data)
protected void Submit(object sender, EventArgs e)
    {
        DataTable dataTable = (ViewState["Address"] as DataTable);
        //save dataTable to database
    }

I am also attaching the actual modified files so you can check it at your end (I have used a sample database for illustration purposes).

Let me know how this works for you and if you have any other questions.

Regards,
Marin
the Telerik team
Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items
Tags
Grid
Asked by
shivesh
Top achievements
Rank 1
Answers by
Marin
Telerik team
shivesh
Top achievements
Rank 1
Share this question
or