如何在gridview中创建动态列 [英] how to create dynamic column in gridview

查看:92
本文介绍了如何在gridview中创建动态列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨所有



我想在rowdatabound中的网格视图中创建动态列。

这里我在<中完成静态列ASP:模板>但现在我想在网格视图中创建动态列: -

我的代码: -

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:-

<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>



< br $>
编码: -



coding:-

 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);
                    }
                }
            }
}





以上我在标签上给出但是这个我想创建dymanically.so请帮帮我。



above here i given in label but this i want to create dymanically.so please help me.

推荐答案

看看这个: http://stackoverflow.com/questions/11685470/how-to-add-dynamic-n-checkbox-columns-to -gridview-asp-net [ ^ ]


这是解决方案希望它有所帮助。



页面/控制标记:

Here is the solution hope it helps.

Page/control markup:
<%@ 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 :



Code Behind:

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();
        }
    }
}





使用Url QueryStrings测试:

DynamicGridview.aspx?count = 5& itemcode = Item_10& billno = 10



Test using Url QueryStrings:
DynamicGridview.aspx?count=5&itemcode=Item_10&billno=10


这篇关于如何在gridview中创建动态列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆