Click here to Skip to main content
15,945,603 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi to all

I want to create dynamic column in grid view in rowdatabound.
Here i done static column in <asp:templates> but now i want to create dynamic column in grid view:-
my code:-
XML
<asp:TemplateField ItemStyle-HorizontalAlign="Right" ItemStyle-VerticalAlign="Top"
                                                       HeaderText="MRP" ItemStyle-Width="20%">
                                                       <ItemTemplate>
                                                           <asp:Label Style="font-family: 'Trebuchet MS'; font-size: 11px;" ID="lblTotal1" runat="server" />
                                                       </ItemTemplate>
                                                   </asp:TemplateField>
                                                   <asp:TemplateField ItemStyle-HorizontalAlign="Right" ItemStyle-VerticalAlign="Top"
                                                       HeaderText="GP" ItemStyle-Width="20%">
                                                       <ItemTemplate>
                                                           <asp:Label Style="font-family: 'Trebuchet MS'; font-size: 11px;" ID="lblTotalgp" runat="server" />
                                                       </ItemTemplate>
                                                   </asp:TemplateField>


coding:-
C#
 public void gvSecond_RowDataBound(object sender, GridViewRowEventArgs e)
    {
  DataSet ds = new DataSet();
                BusinessLogic bl = new BusinessLogic();
                string connection = ConfigurationManager.ConnectionStrings[Request.Cookies["Company"].Value].ToString();
                string Branch = Request.QueryString["BranchCode"].ToString();

                ds = bl.getpricefordashboard(connection, billno, Branch);
                if (ds.Tables[0].Rows.Count > 0)
                {
                    foreach (DataRow drt in ds.Tables[0].Rows)
                    {
                        int price = Convert.ToInt32(drt["Price"].ToString());
                        string pricename = drt["PriceName"].ToString();
                        string item = drt["Itemcode"].ToString();
                        int bill = Convert.ToInt32(drt["billno"].ToString());

                        string item123 = drt["PriceName"].ToString();
                        

                        if ((itemcode == item) && (billno == bill))
                        {
                            if (item123 == "MRP")
                            {
                              lblTotal1.Text = Convert.ToString(drt["Price"].ToString());
                           }
                       
                        lblTotalgp.Text =Convert.ToInt32(lblTotal.Text - lblTotal3.Text);
                    }
                }
            }
}


above here i given in label but this i want to create dymanically.so please help me.
Posted
Updated 5-Jun-15 2:47am
v2
Comments
njammy 5-Jun-15 10:24am    
Sorry this is not the direct answer to your question but one thing that stood out to me in your example code, is that your code is making a database call for EVERY data row in the gridview. This should be done as a pre-load method. Then when you generate your dynamic column, load the correct value from the pre-loaded data from other datasource.

Also, If you put the foreach() loop inside the RowDataBound event it will only set the label value to the LAST records values. You need to move this logic outside.

Here is the solution hope it helps.

Page/control markup:
XML
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DynamicGridview.aspx.cs" Inherits="CodeProject.Com.DynamicGridview" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:GridView runat="server" ID="Gridview1" AutoGenerateColumns="false" OnDataBinding="Gridview1_DataBinding" OnRowDataBound="Gridview1_RowDataBound">
            </asp:GridView>
        </div>
    </form>
</body>
</html>


Code Behind:
XML
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace CodeProject.Com
{
    public partial class DynamicGridview : System.Web.UI.Page
    {
        private IEnumerable<DashboardPrice> dashboardPrices;
        private string itemCode = "";
        private int billNo = 1;

        /// <summary>
        /// Use this event to get the default data before hand.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_PreInit(object sender, EventArgs e)
        {
            int mockDataCount = Convert.ToInt32(Request.QueryString["count"]);
            itemCode = Request.QueryString["itemcode"] ?? "";
            billNo = Convert.ToInt32(Request.QueryString["billno"]??"0");

            this.dashboardPrices = MockDashboardPrice.GetMockDashboardPrice(mockDataCount);
            ((List<DashboardPrice>)this.dashboardPrices).Add(new DashboardPrice()
            {
                Price = 10,
                PriceName = "MRP",
                Item = "Item_10",
                Bill = 10
            });
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                Gridview1.DataSource = this.dashboardPrices;

                Gridview1.DataBind();
            }
        }

        /// <summary>
        /// Before databinding completes, the fields are programatically added.
        /// To add dynamically, use reflection to go through the object properties.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Gridview1_DataBinding(object sender, EventArgs e)
        {
            AddGridviewColumn("Price");
            AddGridviewColumn("PriceName");
            AddGridviewColumn("Item");
            AddGridviewColumn("Bill");
            AddGridviewColumn("MRP");
            AddGridviewColumn("GP");
        }

        protected void Gridview1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                AddDashboardPriceToGridview((DashboardPrice)e.Row.DataItem, e.Row);
            }
        }

        private void AddGridviewColumn(string name)
        {
            TemplateField col = new TemplateField();
            col.HeaderText = name;
            Gridview1.Columns.Add(col);
        }

        /// <summary>
        /// Sets the gridview row values of dashboard price item.
        /// </summary>
        /// <param name="item"></param>
        /// <param name="row"></param>
        private void AddDashboardPriceToGridview(DashboardPrice item, GridViewRow row)
        {
            row.Cells[0].Text = Convert.ToString(item.Price);
            row.Cells[1].Text = item.PriceName;
            row.Cells[2].Text = item.Item;
            row.Cells[3].Text = Convert.ToString(item.Bill);

            if (item.Item.ToLower() == itemCode.ToLower()
                && item.Bill == billNo)
            {
                if (item.PriceName == "MRP")
                {
                    // Set MRP
                    row.Cells[4].Text = Convert.ToString(item.Price);
                }

                // Set GP
                row.Cells[5].Text = "replace this with calculation";
            }
        }
    }

    /// <summary>
    /// Data model class for the gridview row item
    /// </summary>
    public class DashboardPrice
    {
        public int Price { get; set; }
        public string PriceName { get; set; }
        public string Item { get; set; }
        public int Bill { get; set; }
    }

    /// <summary>
    /// Dummy data generator.
    /// </summary>
    public static class MockDashboardPrice
    {
        public static IEnumerable<DashboardPrice> GetMockDashboardPrice(int count)
        {
            if (count <= 0) return new List<DashboardPrice>();

            return Enumerable.Range(1, count)
                .Select(x =>
                    new DashboardPrice()
                    {
                        Price = x,
                        PriceName = "Price_" + Convert.ToString(x),
                        Item = "Item_" + Convert.ToString(x),
                        Bill = x
                    })
                .ToList();
        }
    }
}


Test using Url QueryStrings:
DynamicGridview.aspx?count=5&itemcode=Item_10&billno=10
 
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