asp.net gridview动态添加列,并获取其数据;

1,绑定数据前先动态添加列,见方法CreateGridColumn(只在第一次加载动态添加);

2,gvlist_RowDataBound为对应列添加控件;

前台代码:

 1 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="modifysetLeaveconfig2.aspx.cs"
 2     Inherits="web.system.modifysetLeaveconfig2" %>
 3 
 4 <%@ Register Assembly="AspNetPager" Namespace="Wuqi.Webdiyer" TagPrefix="webdiyer" %>
 5 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 6 <html xmlns="http://www.w3.org/1999/xhtml">
 7 <head id="Head1" runat="server">
 8     <title></title>
 9     <link href="/css/default.css" rel="stylesheet" type="text/css" />
10     <link href="/css/jquery.ui.all.css" rel="stylesheet" type="text/css" />
11     <script type="text/javascript" src="/js/jquery-1.9.1.js"></script>
12     <script type="text/javascript" src="/js/jquery.ui.core.js"></script>
13     <script type="text/javascript" src="/js/jquery.ui.widget.js"></script>
14     <script type="text/javascript" src="/js/jquery.ui.mouse.js"></script>
15     <script type="text/javascript" src="/js/jquery.ui.draggable.js"></script>
16     <script type="text/javascript" src="/js/jquery.ui.position.js"></script>
17     <script type="text/javascript" src="/js/jquery.ui.resizable.js"></script>
18     <script type="text/javascript" src="/js/jquery.ui.button.js"></script>
19     <script type="text/javascript" src="/js/jquery.ui.dialog.js"></script>
20     <script type="text/javascript" src="/js/jquery.ui.datepicker.js"></script>
21     <script type="text/javascript" src="/js/common.js"></script>
22     <script type="text/javascript" src="/js/jquery.validate.js"></script>
23 </head>
24 <body>
25     <form id="form1" runat="server">
26     <asp:HiddenField runat="server" ID="hfscmcid" />
27     <asp:HiddenField runat="server" ID="hfplatform" />
28     <div class="container">
29         <div class="content">
30             <div class="cPanel">
31                 <div class="detailPanel">
32                     <asp:GridView ID="gvlist" GridLines="None" runat="server" CellSpacing="0" BorderWidth="0"
33                         CellPadding="0" class="oderListTbl" AutoGenerateColumns="False" EmptyDataText="没有找到数据"
34                         OnRowCommand="gvlist_RowCommand" OnRowDataBound="gvlist_RowDataBound">
35                         <Columns>
36                             <asp:TemplateField ItemStyle-Width="60px">
37                                 <HeaderTemplate>
38                                     <asp:CheckBox ID="cbAll" runat="server" Text="" onclick="javascript:SelectAll(this)" />
39                                     <br />
40                                     <asp:LinkButton ID="lbtall" runat="server" OnClientClick="javascript:return confirm('您确定要批量更新该数据吗?');"
41                                         CommandName="updateall" CommandArgument='<%# Eval("scmcid")+","+Eval("policytype") %>'>批量更新</asp:LinkButton>
42                                 </HeaderTemplate>
43                                 <ItemTemplate>
44                                     <asp:CheckBox ID="cbItem" runat="server" />
45                                     <asp:HiddenField ID="hfpolicytype" runat="server" Value='<%# Eval("policytype")%>' />
46                                 </ItemTemplate>
47                             </asp:TemplateField>
48                             <asp:TemplateField HeaderText="政策类型" ItemStyle-Width="50px">
49                                 <ItemTemplate>
50                                     <%# Eval("name")%>
51                                 </ItemTemplate>
52                             </asp:TemplateField>
53                             <asp:TemplateField HeaderText="状态" ItemStyle-Width="50px">
54                                 <ItemTemplate>
55                                     <asp:LinkButton ID="lbtModify" runat="server" CommandName="udtallstate" CommandArgument='<%# Eval("scmcid")+","+Eval("policytype") %>'
56                                         ToolTip="点击更改状态" Text="启/禁用"></asp:LinkButton>
57                                 </ItemTemplate>
58                             </asp:TemplateField>
59                         </Columns>
60                     </asp:GridView>
61                     <div class="pager">
62                         <webdiyer:AspNetPager ID="pager" CssClass="paginator" CurrentPageButtonClass="cpb"
63                             runat="server" AlwaysShow="True" FirstPageText="首页" LastPageText="尾页" NextPageText="下一页"
64                             PageSize="1000000" PrevPageText="上一页" ShowCustomInfoSection="Left" ShowInputBox="Never"
65                             OnPageChanging="pager_PageChanging" CustomInfoTextAlign="Left" LayoutType="Table"
66                             CustomInfoHTML="总条数:%RecordCount%  当前页数 %CurrentPageIndex% of %PageCount%">
67                         </webdiyer:AspNetPager>
68                     </div>
69                 </div>
70             </div>
71         </div>
72         <div class="clr">
73         </div>
74     </div>
75     </form>
76     <script type="text/javascript">
77 
78         $(function () {
79             $("#gvlist tr:odd").addClass("highLight");
80         });
81         function SelectAll(aControl) {
82             var tempControl = aControl;
83             var isChecked = tempControl.checked;
84 
85             elem = tempControl.form.elements;
86             for (i = 0; i < elem.length; i++)
87                 if (elem[i].type == "checkbox" && elem[i].id != tempControl.id) {
88                     if (elem[i].checked != isChecked)
89                         elem[i].click();
90                 }
91         }
92     </script>
93 </body>
94 </html>
View Code

后台代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Data;
using webframework.common;
using web.code;

namespace web.system
{
    public partial class modifysetLeaveconfig2 : code.BasePage
    {
        webframework.bll.systemconfiguration.bllsetlog blllog = new webframework.bll.systemconfiguration.bllsetlog();
        webframework.bll.systemconfiguration.bllsetLeaveconfig bll = new webframework.bll.systemconfiguration.bllsetLeaveconfig();
        protected string platform = "";
        protected static int pageIndex = 1;
        private List<webframework.model.modelsystem> lpolicytype = new List<webframework.model.modelsystem>();
        private static List<webframework.model.modelsystem> listshop = new List<webframework.model.modelsystem>();
        private static List<webframework.model.modelsetLeaveconfig> listslc = new List<webframework.model.modelsetLeaveconfig>();
        private static int times = 0;
        protected void Page_Load(object sender, EventArgs e)
        {
            hfplatform.Value = Request.QueryString["platform"];
            platform = hfplatform.Value;
            hfscmcid.Value = Request.QueryString["id"];
            if (!IsPostBack)
            {
                times = 0;
                PageRender();
            }
            //PageRender();
        }

        void PageRender()
        {
            listshop = code.CacheCollection.GetSystem("000001", platform);//动态添加列 
            pageIndex = pageIndex > 1 ? pageIndex : pager.CurrentPageIndex;
            string sql = code.SqlHelper.GetTableByPager("select name,svalue AS [policytype],-1 AS [id], " + hfscmcid.Value.ToString() + " AS [scmcid] " + (listshop.Count == 0 ? "" : "," + string.Join(",", listshop.Select(p => p.svalue + " as [" + p.svalue + "]").ToList())) + " from t_system WHERE typecode='000004' and svalue IN (2,4,9) ", "name,policytype,id,scmcid " + (listshop.Count == 0 ? "" : "," + string.Join(",", listshop.Select(p => "[" + p.svalue + "]").ToList())),
                "id", true, "", pageIndex, base.PageNum);
            sql += ";select count(1) from t_system WHERE typecode='000004' and svalue IN (2,4,9)";

            DataSet ds = code.SqlHelper.ExecuteDataset(Config.CONSQL_172_16_6_1_READ, CommandType.Text, sql);

            if (times == 0)
            {
                foreach (var item in listshop)
                {
                    CreateGridColumn(item.svalue, item.name, item.svalue, 0, "", "150px;text-align:left;", gvlist);
                }
                times++;
            }
            lpolicytype = code.CacheCollection.GetSystem("000004", "").Where(p => p.svalue == "2" || p.svalue == "4" || p.svalue == "9").ToList();

            listslc = bll.GetModelList();

            gvlist.DataSource = ds.Tables[0];
            gvlist.DataBind();

            pager.PageSize = base.PageNum;
            pager.RecordCount = Convert.ToInt32(ds.Tables[1].Rows[0][0]);
            pager.CurrentPageIndex = pageIndex;
        }

        protected void gvlist_RowCommand(object sender, GridViewCommandEventArgs e)
        {

            if (e.CommandName == "udtallstate")
            {
                #region udt
                try
                {
                    GridViewRow r = (GridViewRow)((e.CommandSource as LinkButton).NamingContainer);
                    int countmodify = 0;
                    int countadd = 0;
                    //listshop = code.CacheCollection.GetSystem("000001", platform);
                    //listslc = bll.GetModelList();
                    string[] valueStr = e.CommandArgument.ToString().Split(',');
                    int scmcid = StringUtils.StrToInt(valueStr[0], -1);
                    int policytype = StringUtils.StrToInt(valueStr[1], -1);

                    LinkButton lbt = ((LinkButton)r.FindControl("lbtModify"));
                    bool state = lbt.Text == "禁用" ? false : true;
                    bool tagerstate = !state;

                    string seq = (r.RowIndex + 2).ToString().PadLeft(2, '0');
                    foreach (var item in listshop)
                    {
                        int slcid = StringUtils.StrToInt(Request.Form[string.Format("gvlist$ctl{0}$hfslcid_{1}_{2}", seq, policytype, item.svalue)], -1);
                        var list = listslc.Where(p => p.id == slcid && p.state == (state ? "Y" : "N")).ToList();
                        if (list.Count > 0)
                        {
                            countmodify += bll.UpdateByStatus(slcid, (tagerstate ? "Y" : "N")) ? 1 : 0;
                            string upStr = "状态" + list.First().state + "=>" + (tagerstate ? "Y" : "N");
                            blllog.Add(slcid.ToString(), UserOnline.Current.UserID, UserOnline.Current.UserName, upStr, "t_set_Leave_config");
                        }
                    }
                    if (countmodify > 0 || countadd > 0)
                    {
                        base.Alert("保存成功");
                        //base.Alert(string.Format("更新数量:{0},新增数量:{1}", countmodify, countadd));
                    }
                    PageRender();
                }
                catch (Exception ex)
                {
                    base.Alert("保存失败");
                }
                #endregion udt
            }
            else if (e.CommandName == "updateall")
            {
                try
                {
                    //listshop = code.CacheCollection.GetSystem("000001", platform);
                    CheckBox chk;
                    int countmodify = 0;
                    int countadd = 0;
                    foreach (GridViewRow r in gvlist.Rows)
                    {
                        chk = (CheckBox)r.FindControl("cbItem");
                        if (chk != null)
                        {
                            if (chk.Checked)
                            {
                                int policytype = StringUtils.StrToInt(((HiddenField)r.FindControl("hfpolicytype")).Value, -1);
                                //"gvData$ctl" + (i + 2).ToString().PadLeft(2, '0') + "$
                                //Request.Form["gvlist$ctl02$txtliupiaoprice_2_1"]
                                string seq = (r.RowIndex + 2).ToString().PadLeft(2, '0');
                                foreach (var item in listshop)
                                {
                                    int slcid = StringUtils.StrToInt(Request.Form[string.Format("gvlist$ctl{0}$hfslcid_{1}_{2}", seq, policytype, item.svalue)], -1);
                                    int scmcid = StringUtils.StrToInt(hfscmcid.Value, -1);
                                    if (slcid > 0)
                                    {
                                        string upStr = "";
                                        if (ModifyByForm(ref upStr, slcid, scmcid, seq, policytype.ToString(), item.svalue))
                                        {
                                            countmodify++;
                                            if (!string.IsNullOrEmpty(upStr))
                                                blllog.Add(slcid.ToString(), UserOnline.Current.UserID, UserOnline.Current.UserName, upStr, "t_set_Leave_config");
                                        }
                                    }
                                    else
                                    {
                                        int newid = 0;
                                        if (AddByForm(ref newid, scmcid, seq, policytype.ToString(), item.svalue))
                                        {
                                            blllog.Add(newid.ToString(), UserOnline.Current.UserID, UserOnline.Current.UserName, "新增配置留点留钱(id:" + newid.ToString(), "t_set_Leave_config");
                                            countadd++;
                                        }
                                    }
                                }



                            }
                        }
                    }
                    if (countmodify > 0 || countadd > 0)
                    {
                        //base.Alert(string.Format("更新数量:{0},新增数量:{1}", countmodify, countadd));
                        ScriptHelper.PopMessageRunScript(string.Format("更新数量:{0},新增数量:{1}", countmodify, countadd), "DialogCloseAndReload();");
                    }
                    else
                    {
                        base.Alert("请选择要更新的选项");
                    }
                }
                catch (Exception ex)
                {
                    base.Alert("保存失败");
                }
            }



        }

        protected void btnsearch_Click(object sender, EventArgs e)
        {
            pager.CurrentPageIndex = 1;
            PageRender();
        }

        protected void pager_PageChanging(object src, Wuqi.Webdiyer.PageChangingEventArgs e)
        {
            pager.CurrentPageIndex = e.NewPageIndex;
            pageIndex = pager.CurrentPageIndex;
            PageRender();
        }

        protected void gvlist_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                if (DataBinder.Eval(e.Row.DataItem, "scmcid") != null)
                {
                    int scmcid = StringUtils.StrToInt(DataBinder.Eval(e.Row.DataItem, "scmcid").ToString(), -1);
                    string policytype = DataBinder.Eval(e.Row.DataItem, "policytype").ToString();
                    var list = listslc.Where(p => p.scmcid == scmcid && p.state == "Y" && p.policytype.Value.ToString() == policytype).ToList();
                    LinkButton lbt = (LinkButton)e.Row.FindControl("lbtModify");
                    lbt.Text = (list.Count > 0 && listshop.Count > 0) ? "启用" : "禁用";
                }

                Label lbl = new Label();
                TextBox txt = new TextBox();
                foreach (var item in listshop)
                {
                    if (DataBinder.Eval(e.Row.DataItem, item.svalue) != null && DataBinder.Eval(e.Row.DataItem, "id") != null)
                    {
                        int indexcol = GetGridViewColumnIndex(gvlist, item.svalue);
                        string policytype = DataBinder.Eval(e.Row.DataItem, "policytype").ToString();
                        string shopname = DataBinder.Eval(e.Row.DataItem, item.svalue).ToString();
                        var list = listslc.Where(p => p.shopname == int.Parse(shopname) && p.policytype.Value.ToString() == policytype && DataBinder.Eval(e.Row.DataItem, "scmcid").ToString() == p.scmcid.ToString()).ToList();

                        #region 动态添加控件
                        //留票面    返点    返钱    cpc返点    cpc返钱    有效起始    有效结束 状态
                        //e.Row.Cells[indexcol].Text = "";
                        lbl = new Label();
                        lbl.ID = "lblliupiaoprice" + "_" + policytype + "_" + shopname;
                        lbl.Text = "留票面:";
                        e.Row.Cells[indexcol].Controls.Add(lbl);
                        txt = new TextBox();
                        txt.ID = "txtliupiaoprice" + "_" + policytype + "_" + shopname;
                        txt.Width = new Unit("70px");
                        txt.EnableViewState = true;
                        txt.Text = list.Count == 0 ? "" : list.First().liupiaoprice.ToString();
                        e.Row.Cells[indexcol].Controls.Add(txt);
                        e.Row.Cells[indexcol].Controls.Add(new Literal() { Text = "<br/>" });
                        lbl = new Label();
                        lbl.ID = "lblliupoint" + "_" + policytype + "_" + shopname;
                        lbl.Text = "返点:";
                        e.Row.Cells[indexcol].Controls.Add(lbl);
                        txt = new TextBox();
                        txt.ID = "txtliupoint" + "_" + policytype + "_" + shopname;
                        txt.Width = new Unit("70px");
                        txt.EnableViewState = true;
                        txt.Text = list.Count == 0 ? "" : list.First().liupoint.ToString();
                        e.Row.Cells[indexcol].Controls.Add(txt);
                        e.Row.Cells[indexcol].Controls.Add(new Literal() { Text = "<br/>" });
                        lbl = new Label();
                        lbl.ID = "lblliumoney" + "_" + policytype + "_" + shopname;
                        lbl.Text = "返钱:";
                        e.Row.Cells[indexcol].Controls.Add(lbl);
                        txt = new TextBox();
                        txt.ID = "txtliumoney" + "_" + policytype + "_" + shopname;
                        txt.Width = new Unit("70px");
                        txt.EnableViewState = true;
                        txt.Text = list.Count == 0 ? "" : list.First().liumoney.ToString();
                        e.Row.Cells[indexcol].Controls.Add(txt);
                        e.Row.Cells[indexcol].Controls.Add(new Literal() { Text = "<br/>" });
                        lbl = new Label();
                        lbl.ID = "lblstarttime" + "_" + policytype + "_" + shopname;
                        lbl.Text = "有效起始:";
                        e.Row.Cells[indexcol].Controls.Add(lbl);
                        txt = new TextBox();
                        txt.ID = "txtstarttime" + "_" + policytype + "_" + shopname;
                        txt.Width = new Unit("70px");
                        txt.EnableViewState = true;
                        txt.Text = list.Count == 0 ? "" : (string.IsNullOrEmpty(list.First().starttime.ToString()) ? "" : Convert.ToDateTime(list.First().starttime).ToString("yyyy-MM-dd"));
                        txt.Attributes.Add("rel", "datetime");
                        e.Row.Cells[indexcol].Controls.Add(txt);
                        e.Row.Cells[indexcol].Controls.Add(new Literal() { Text = "<br/>" });
                        lbl = new Label();
                        lbl.ID = "lblendtime" + "_" + policytype + "_" + shopname;
                        lbl.Text = "有效结束:";
                        e.Row.Cells[indexcol].Controls.Add(lbl);
                        txt = new TextBox();
                        txt.ID = "txtendtime" + "_" + policytype + "_" + shopname;
                        txt.Width = new Unit("70px");
                        txt.EnableViewState = true;
                        txt.Text = list.Count == 0 ? "" : (string.IsNullOrEmpty(list.First().endtime.ToString()) ? "" : Convert.ToDateTime(list.First().endtime).ToString("yyyy-MM-dd"));
                        txt.Attributes.Add("rel", "datetime");
                        e.Row.Cells[indexcol].Controls.Add(txt);
                        e.Row.Cells[indexcol].Controls.Add(new Literal() { Text = "<br/>" });
                        lbl = new Label();
                        lbl.ID = "lblstate" + "_" + policytype + "_" + shopname;
                        lbl.Text = "状态:";
                        e.Row.Cells[indexcol].Controls.Add(lbl);
                        DropDownList ddl = new DropDownList();
                        ddl.ID = "ddlstate" + "_" + policytype + "_" + shopname;
                        ddl.Items.Add(new ListItem("启用", "Y"));
                        ddl.Items.Add(new ListItem("禁用", "N"));
                        ddl.Width = new Unit("70px");
                        ddl.EnableViewState = true;
                        ddl.SelectedValue = list.Count == 0 ? "Y" : list.First().state;
                        e.Row.Cells[indexcol].Controls.Add(ddl);
                        e.Row.Cells[indexcol].Controls.Add(new Literal() { Text = "<br/>" });
                        if (platform == "0")
                        {
                            lbl = new Label();
                            lbl.ID = "lblcpcliupoint" + "_" + policytype + "_" + shopname;
                            lbl.Text = "cpc返点:";
                            e.Row.Cells[indexcol].Controls.Add(lbl);
                            txt = new TextBox();
                            txt.ID = "txtcpcliupoint" + "_" + policytype + "_" + shopname;
                            txt.Width = new Unit("70px");
                            txt.EnableViewState = true;
                            txt.Text = list.Count == 0 ? "" : list.First().cpcliupoint.ToString();
                            e.Row.Cells[indexcol].Controls.Add(txt);
                            e.Row.Cells[indexcol].Controls.Add(new Literal() { Text = "<br/>" });
                            lbl = new Label();
                            lbl.ID = "lblcpcliumoney" + "_" + policytype + "_" + shopname;
                            lbl.Text = "cpc返钱:";
                            e.Row.Cells[indexcol].Controls.Add(lbl);
                            txt = new TextBox();
                            txt.ID = "txtcpcliumoney" + "_" + policytype + "_" + shopname;
                            txt.Width = new Unit("70px");
                            txt.EnableViewState = true;
                            txt.Text = list.Count == 0 ? "" : list.First().cpcliumoney.ToString();
                            e.Row.Cells[indexcol].Controls.Add(txt);
                            e.Row.Cells[indexcol].Controls.Add(new Literal() { Text = "<br/>" });
                        }
                        e.Row.Cells[indexcol].Controls.Add(new HiddenField() { Value = (list.Count == 0 ? "-1" : list.First().id.ToString()), ID = "hfslcid" + "_" + policytype + "_" + shopname });

                        #endregion

                    }
                }
            }
        }

        bool AddByForm(ref int newid, int scmcid, string seq, string policytype, string shopname)
        {
            webframework.model.modelsetLeaveconfig model = new webframework.model.modelsetLeaveconfig();

            string liupiaoprice = Request.Form[string.Format("gvlist$ctl{0}$txtliupiaoprice_{1}_{2}", seq, policytype, shopname)].Trim();
            string liupoint = Request.Form[string.Format("gvlist$ctl{0}$txtliupoint_{1}_{2}", seq, policytype, shopname)].Trim();
            string liumoney = Request.Form[string.Format("gvlist$ctl{0}$txtliumoney_{1}_{2}", seq, policytype, shopname)].Trim();
            string starttime = Request.Form[string.Format("gvlist$ctl{0}$txtstarttime_{1}_{2}", seq, policytype, shopname)].Trim();
            string endtime = Request.Form[string.Format("gvlist$ctl{0}$txtendtime_{1}_{2}", seq, policytype, shopname)].Trim();
            string state = Request.Form[string.Format("gvlist$ctl{0}$ddlstate_{1}_{2}", seq, policytype,
shopname)].Trim();
            model.scmcid = scmcid;
            model.liupiaoprice = StringUtils.StrToDecimal(liupiaoprice, 0);
            model.liumoney = StringUtils.StrToDecimal(liumoney, 0);
            model.liupoint = StringUtils.StrToDecimal(liupoint, 0);
            model.starttime = StringUtils.StrToDataTime(starttime, null);
            model.endtime = StringUtils.StrToDataTime(endtime, null);
            model.platform = int.Parse(hfplatform.Value);
            model.shopname = int.Parse(shopname);
            model.policytype = int.Parse(policytype);
            model.state = state;
            model.createtime = DateTime.Now;
            model.createuser = UserOnline.Current.UserName;
            if (platform == "0")
            {
                string cpcliupoint = Request.Form[string.Format("gvlist$ctl{0}$txtcpcliupoint_{1}_{2}", seq, policytype, shopname)].Trim();
                string cpcliumoney = Request.Form[string.Format("gvlist$ctl{0}$txtcpcliumoney_{1}_{2}", seq, policytype, shopname)].Trim();
                model.cpcliumoney = StringUtils.StrToDecimal(cpcliumoney, 0);
                model.cpcliupoint = StringUtils.StrToDecimal(cpcliupoint, 0);
            }

            newid = bll.Add(model);
            return newid > 0 ? true : false;
        }
        bool ModifyByForm(ref string upStr, int slcid, int scmcid, string seq, string policytype, string shopname)
        {
            webframework.model.modelsetLeaveconfig model = bll.GetModel(slcid);
            bool isupdate = false;
            string liupiaoprice = Request.Form[string.Format("gvlist$ctl{0}$txtliupiaoprice_{1}_{2}", seq, policytype, shopname)].Trim();
            string liupoint = Request.Form[string.Format("gvlist$ctl{0}$txtliupoint_{1}_{2}", seq, policytype, shopname)].Trim();
            string liumoney = Request.Form[string.Format("gvlist$ctl{0}$txtliumoney_{1}_{2}", seq, policytype, shopname)].Trim();
            string cpcliupoint = platform == "0" ? Request.Form[string.Format("gvlist$ctl{0}$txtcpcliupoint_{1}_{2}", seq, policytype, shopname)].Trim() : "0";
            string cpcliumoney = platform == "0" ? Request.Form[string.Format("gvlist$ctl{0}$txtcpcliumoney_{1}_{2}", seq, policytype, shopname)].Trim() : "0";
            string starttime = Request.Form[string.Format("gvlist$ctl{0}$txtstarttime_{1}_{2}", seq, policytype, shopname)].Trim();
            string endtime = Request.Form[string.Format("gvlist$ctl{0}$txtendtime_{1}_{2}", seq, policytype, shopname)].Trim();
            string state = Request.Form[string.Format("gvlist$ctl{0}$ddlstate_{1}_{2}", seq, policytype,
shopname)].Trim();
            model.platform = int.Parse(hfplatform.Value);
            model.shopname = int.Parse(shopname);
            model.scmcid = scmcid;

            decimal dtry = 0;
            if (!decimal.TryParse(liupiaoprice, out dtry))
            {
                //base.Alert("留票面必须为小数");
                return false;
            }
            if (!decimal.TryParse(liumoney, out dtry))
            {
                //base.Alert("返钱必须为小数");
                return false;
            }
            if (!decimal.TryParse(liupoint, out dtry))
            {
                //base.Alert("返点必须为小数");
                return false;
            }

            if (model.state != state)
            {
                upStr += "[状态:" + model.state + "" + state + "]";
                model.state = state;
                isupdate = true;
            }
            if (model.liupiaoprice != null && model.liupiaoprice.Value != decimal.Parse(liupiaoprice))
            {
                upStr += "[留票面:" + model.liupiaoprice + "" + liupiaoprice + "]";
                model.liupiaoprice = decimal.Parse(liupiaoprice);
                isupdate = true;
            }
            if (model.liupiaoprice != null && model.liupiaoprice.Value != decimal.Parse(liupiaoprice))
            {
                upStr += "[留票面:" + model.liupiaoprice + "" + liupiaoprice + "]";
                model.liupiaoprice = decimal.Parse(liupiaoprice);
                isupdate = true;
            }
            if (model.liumoney != null && model.liumoney.Value != decimal.Parse(liumoney))
            {
                upStr += "[返钱:" + model.liumoney + "" + liumoney + "]";
                model.liumoney = decimal.Parse(liumoney);
                isupdate = true;
            }
            if (model.liupoint != null && model.liupoint.Value != decimal.Parse(liupoint))
            {
                upStr += "[返点:" + model.liupoint + "" + liupoint + "]";
                model.liupoint = decimal.Parse(liupoint);
                isupdate = true;
            }

            if (platform == "0")   //去哪儿平台才有cpc
            {
                if (model.cpcliumoney != null && !string.IsNullOrEmpty(cpcliumoney) && model.cpcliumoney.Value != decimal.Parse(cpcliumoney))
                {
                    upStr += "[cpc返钱:" + model.cpcliumoney + "" + cpcliumoney + "]";
                    model.cpcliumoney = decimal.Parse(cpcliumoney);
                    isupdate = true;
                }

                if (model.cpcliupoint != null && !string.IsNullOrEmpty(cpcliupoint) && model.cpcliupoint.Value != decimal.Parse(cpcliupoint))
                {
                    upStr += "[cpc返点:" + model.cpcliupoint + "" + cpcliupoint + "]";
                    model.cpcliupoint = decimal.Parse(cpcliupoint);
                    isupdate = true;
                }
            }

            if (model.starttime == null || model.starttime.ToString() == "")
            {
                if (!string.IsNullOrEmpty(starttime))
                {
                    upStr += "[有效起始日期:''→" + starttime + "]";
                    model.starttime = DateTime.Parse(starttime);
                }
                isupdate = true;
            }
            else if (model.starttime != null && model.starttime.ToString() != starttime)
            {
                upStr += "[有效起始日期:" + model.starttime.ToString() + "" + starttime + "]";
                if (!string.IsNullOrEmpty(starttime))
                {
                    model.starttime = DateTime.Parse(starttime);
                }
                else
                {
                    model.starttime = DateTime.Now.Date; ;
                }
                isupdate = true;
            }
            if (model.endtime == null || model.endtime.ToString() == "")
            {
                if (!string.IsNullOrEmpty(endtime))
                {
                    upStr += "[有效结束日期:''→" + endtime + "]";
                    model.endtime = DateTime.Parse(endtime);
                    isupdate = true;
                }
            }
            else if (model.endtime != null && model.endtime.ToString() != endtime)
            {
                upStr += "[有效结束日期:" + model.endtime.ToString() + "" + endtime + "]";
                if (!string.IsNullOrEmpty(endtime))
                {
                    model.endtime = DateTime.Parse(endtime);
                }
                else
                {
                    model.endtime = DateTime.Parse(DateTime.Now.ToString("yyyy-12-31"));
                }
                isupdate = true;
            }
            if (isupdate)
            {
                model.updatetime = DateTime.Now;
                model.updateuser = UserOnline.Current.UserName;
            }

            return bll.Update(model);
        }
        //创建GridView列的方法
        private void CreateGridColumn(string dataField, string headerText, string footerText, int width, string headerStyle, string itemStyle, GridView gv)
        {
            BoundField bc = new BoundField();
            bc.FooterText = footerText;
            bc.DataField = dataField;
            bc.HeaderText = headerText;
            if (!string.IsNullOrEmpty(headerStyle))
                bc.HeaderStyle.CssClass = headerStyle;  //若有默认样式,此行代码及对应的参数可以移除
            if (!string.IsNullOrEmpty(itemStyle))
                bc.ItemStyle.CssClass = itemStyle;   //若有默认样式,此行代码及对应的参数可以移除
            gv.Columns.Add(bc);  //把动态创建的列,添加到GridView中  
            if (width > 0)
                gv.Width = new Unit(gv.Width.Value + width); //每添加一列后,要增加GridView的总体宽度  

        }

        private int GetGridViewColumnIndex(GridView grid, string colName)
        {
            int ndx = 0;
            foreach (DataControlField oCol in grid.Columns)
            {
                if (oCol.GetType() == typeof(BoundField))
                {
                    BoundField bfield = (BoundField)oCol;
                    if (bfield.DataField.ToUpper() == colName.ToUpper())
                    {
                        return ndx;
                    }
                }
                ndx++;
            }
            return ndx;
        }

    }
}
View Code

BasePage:

 1 using System;
 2 using System.Collections.Generic;
 3 
 4 using System.Web;
 5 
 6 namespace web.code
 7 {
 8     public class BasePage : System.Web.UI.Page
 9     {
10         protected override void OnInit(EventArgs e)
11         {
12             if (!UserOnline.Current.IsLogin)
13             {
14                 Response.Redirect("/login.aspx", true);
15             }
16             //base.OnInit(e);
17         }
18 
19 
20         protected int PageNum = 25;
21 
22         protected void Alert(string str)
23         {
24             this.Page.ClientScript.RegisterStartupScript(this.GetType(), "success", "alert('" + str + "');", true);
25         }
26 
27     }
28 }
View Code

注意:动态添加列通过如下获取

//"gvlist$ctl" + (i + 2).ToString().PadLeft(2, '0') + "$controlid" 
//Request.Form["gridviewID$ctl行号$控件ID"]

参考:

http://www.cnblogs.com/jiutianxingchen/p/5520844.html

原文地址:https://www.cnblogs.com/systemkk/p/5912943.html