• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

笑看红尘

笑看红尘
  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

为了实现象excel那样的横向数据统计和纵向数据统计,在.NET下实现了二维表的DATAGRID.

  1<%@ Page Language="C#" MasterPageFile="~/MasterPage/Default.master" AutoEventWireup="true"
  2    CodeFile="CategorySellPlan.aspx.cs" Inherits="Start_SellPlan_CategorySellPlan"
  3    Title="Untitled Page" %>
  4
  5<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
  6
  7    <br />
  8    <fieldset>
  9        <legend>品类计划设置</legend>
 10        <br />
 11        <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" DataTextField="PERIODNAME"
 12            DataValueField="PeriodID" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"
 13            Width="156px">
 14        </asp:DropDownList>
 15        <asp:DropDownList ID="DropDownList2" runat="server" AutoPostBack="True" DataSourceID="ObjectDataSource1"
 16            DataTextField="MONTH" DataValueField="MONTHPLANID" OnSelectedIndexChanged="DropDownList2_SelectedIndexChanged">
 17        </asp:DropDownList><br />
 18        <table style="width: 100%">
 19            <tr>
 20                <td>
 21                    这个月预测量为:<asp:Label ID="lbForestQuantity" runat="server" ForeColor="Red"></asp:Label></td>
 22                <td>
 23                    这个月修正量为:<asp:Label ID="lbFixQuantity" runat="server" ForeColor="Red"></asp:Label></td>
 24            </tr>
 25            <tr>
 26                <td>
 27                    这个月计划量为:<asp:Label ID="lbMonthPlan" runat="server" ForeColor="Red"></asp:Label>
 28                </td>
 29                <td>
 30                </td>
 31            </tr>
 32        </table>
 33        <table style="width: 100%">
 34            <tr>
 35                <td align="left">
 36                    <asp:Label ID="lbUnAuditingComment" runat="server" ForeColor="Red"></asp:Label></td>
 37            </tr>
 38            <tr>
 39                <td align="right">
 40                    <asp:ImageButton ID="ibSave" runat="server" OnClientClick="return DataGridInputChanged();" OnClick="ImageButton1_Click" SkinID="save" />
 41                    <asp:ImageButton ID="ibApply" runat="server" CommandName="Apply" OnCommand="IBCommand"
 42                        SkinID="tjsh" />
 43                    <asp:ImageButton ID="ibUnApply" runat="server" CommandName="UnApply" OnCommand="IBCommand"
 44                        SkinID="cxsh" />
 45                    <asp:ImageButton ID="ibAuditing" runat="server" CommandName="Auditing" OnCommand="IBCommand"
 46                        SkinID="shtg" />
 47                    <asp:ImageButton ID="ibUnAuditing" runat="server" CommandName="UnAuditing" OnCommand="IBCommand"
 48                        SkinID="qxsh" />
 49                </td>
 50            </tr>
 51        </table>
 52        <asp:ObjectDataSource ID="ObjectDataSource1" runat="server" OldValuesParameterFormatString="original_{0}"
 53            SelectMethod="GetMonthPlanData" TypeName="CM.Data.SellPlan.CategoryPlanTableAdapters.PL_MONTHPLANTableAdapter">
 54            <SelectParameters>
 55                <asp:ControlParameter ControlID="DropDownList1" Name="PeriodID" PropertyName="SelectedValue"
 56                    Type="String" />
 57            </SelectParameters>
 58        </asp:ObjectDataSource>
 59        <asp:Panel ID="Panel1" runat="server" Height="50px" Width="100%">
 60            <asp:Label ID="lbTable" runat="server"></asp:Label>
 61            <asp:DataGrid ID="grid" runat="server" ShowFooter="True" CellPadding="4" ForeColor="#333333"
 62                GridLines="None">
 63                <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
 64                <EditItemStyle BackColor="#2461BF" />
 65                <SelectedItemStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
 66                <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
 67                <AlternatingItemStyle BackColor="Gainsboro" Font-Bold="False" Font-Italic="False"
 68                    Font-Overline="False" Font-Strikeout="False" Font-Underline="False" />
 69                <ItemStyle BackColor="#EFF3FB" />
 70                <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
 71            </asp:DataGrid>
 72            <div id="comment" runat="server" style="border-right: #000000 1px; border-top: #000000 1px;
 73                z-index: 8888; left: 60%; border-left: #000000 1px; width: 234px; border-bottom: #000000 1px;
 74                position: absolute; top: 40%; height: 0px; background-color: #ccffff" visible="false">
 75                <table style="border-right: #000000 1px solid; border-top: #000000 1px solid; margin: 1px;
 76                    border-left: #000000 1px solid; width: 100%; border-bottom: #000000 1px solid">
 77                    <tr>
 78                        <td style="width: 50px">
 79                            原因:</td>
 80                        <td>
 81                            <asp:TextBox ID="tbComment" runat="server" Height="147px" TextMode="MultiLine" Width="100%"></asp:TextBox></td>
 82                    </tr>
 83                    <tr>
 84                        <td>
 85                            &nbsp;</td>
 86                        <td>
 87                            <asp:ImageButton ID="ibSubmit" runat="server" OnCommand="IBCommand" CommandName="UnPass"
 88                                SkinID="ok" /></td>
 89                    </tr>
 90                </table>
 91            </div>
 92        </asp:Panel>
 93        &nbsp;<br />
 94        <table style="width: 100%">
 95            <tr>
 96                <td align="center">
 97                </td>
 98            </tr>
 99        </table>
100        <br />
101        <asp:Label ID="Label1" runat="server"></asp:Label>
102        <br />
103        <asp:Label ID="Label2" runat="server"></asp:Label>
104    </fieldset>
105
106    <script language="javascript" type="text/javascript">
107function trim(str)
108{
109    re1=/^[ \t]*/;    //一个空白开头的匹配。
110
111    re2=/[ \t]*$/;    //一个空白结尾的匹配。
112
113    s=str.replace(re1,"").replace(re2,"");
114    return s;
115}

116function DataGridInputChanged()
117{
118    var isfloat = true;
119    var bodyTable = document.getElementById('ctl00_ContentPlaceHolder1_grid');
120    var isFloat = /^\d+(\.\d+)?$/;//
121    //alert(isFloat.test("255.255.255.aaaa"));
122
123    if (bodyTable == null) return;
124    //alert(bodyTable.rows.length);
125    for (var i = 2; i < bodyTable.rows.length - 1; i++)
126    {    
127        /**//*行合计*/
128        var pricetotal = 0;
129        for (var j = 0; j < (bodyTable.rows(2).cells.length-2)/2; j++)
130        {
131            var sel = bodyTable.rows(i).cells(2*j+2).children.item(0);
132            //alert(sel.value);
133            if (sel != null)
134            {
135                if (trim(sel.value).length > 0)
136                {
137                    if(!isFloat.test(sel.value))
138                    {
139                        //alert("您输入的数量格式不正确!");
140                        isfloat = false;
141                        //return;
142                    }

143                    else
144                    {
145                        pricetotal += parseFloat(sel.value);
146                    }

147                }

148                else
149                {
150                    //alert("您输入的数量格式不正确!");
151                    isfloat = false;
152                    //return;
153                }

154            }

155            else
156            {
157                sel = bodyTable.rows(i).cells(2*j+2);
158                if (sel != null && trim(sel.innerText).length > 0)
159                {
160                    pricetotal += parseFloat(sel.innerText);
161                }

162            }

163        }

164        //alert(pricetotal);
165        bodyTable.rows(i).cells(bodyTable.rows(2).cells.length-1).innerText = pricetotal.toFixed(0);
166    }

167    
168    /**//*列合计*/
169      for (var j = 0; j < (bodyTable.rows(2).cells.length-2)/2; j++)
170    {
171        forestQuantity = 0;
172        fixQuantity = 0;
173        for (var i = 2; i < bodyTable.rows.length - 1; i++)
174        {    
175            var sel1 = bodyTable.rows(i).cells(2*j+1).children.item(0);
176            if (sel != null)
177            {
178                if (trim(sel1.value).length > 0)
179                {
180                    if(!isFloat.test(sel.value))
181                    {
182                        //alert("您输入的数量格式不正确!");
183                           isfloat = false;
184                        //return;
185                    }

186                    else
187                        forestQuantity += parseFloat(sel1.value);
188                }

189                else
190                {
191                    //alert("您输入的数量格式不正确!");
192                    isfloat = false;
193                    //return;
194                }

195            }

196            else
197            {
198                sel1 = bodyTable.rows(i).cells(2*j+1);
199                
200                if (sel1 != null && trim(sel1.innerText).length > 0)
201                {    
202                    forestQuantity += parseFloat(sel1.innerText);
203                }

204            }

205            var sel = bodyTable.rows(i).cells(2*j+2).children.item(0);
206            if (sel != null)
207            {
208                if (trim(sel.value).length > 0)
209                {    
210                    if(!isFloat.test(sel.value))
211                    {
212                        //alert("您输入的数量格式不正确!");
213                        isfloat = false;
214                        //return;
215                    }

216                    else
217                        fixQuantity += parseFloat(sel.value);
218                }

219                else
220                {
221                    //alert("您输入的数量格式不正确!");
222                    isfloat = false;
223                    //return;
224                }

225            }

226            else
227            {
228                sel = bodyTable.rows(i).cells(2*j+2);
229                
230                if (sel != null && trim(sel.innerText).length > 0)
231                {    
232                    fixQuantity += parseFloat(sel.innerText);
233                }

234            }

235        }

236        bodyTable.rows(bodyTable.rows.length -1).cells(2*j+1).innerHTML = forestQuantity.toFixed(0);
237        bodyTable.rows(bodyTable.rows.length -1).cells(2*j+2).innerHTML = fixQuantity.toFixed(0);
238    }

239    
240        var totalQuantity = 0;
241        for (var i = 2; i < bodyTable.rows.length - 1; i++)
242        {    
243            var sel = bodyTable.rows(i).cells(bodyTable.rows(2).cells.length-1);
244            if (sel != null)
245            {
246                if (trim(sel.innerText).length > 0)
247                {    
248                    totalQuantity += parseFloat(sel.innerText);
249                }

250            }

251        }

252        bodyTable.rows(bodyTable.rows.length -1).cells(bodyTable.rows(2).cells.length-1).innerHTML = totalQuantity.toFixed(0);
253         if(!isfloat)
254            alert("您输入的数量格式不正确!");
255        return isfloat;
256}
 
257    </script>
258
259    <script language="javascript" type="text/javascript">
260         DataGridInputChanged();
261    </script>
262</asp:Content>
263
页面主要做客户端验证功能.
下面是服务锻动态生成datagrid代码.
  1using System;
  2using System.Data;
  3using System.Data.SqlClient;
  4using System.Configuration;
  5using System.Collections;
  6using System.Web;
  7using System.Web.Security;
  8using System.Web.UI;
  9using System.Web.UI.WebControls;
 10using System.Web.UI.WebControls.WebParts;
 11using System.Web.UI.HtmlControls;
 12using System.Drawing;
 13using CM.Data.Forest;
 14
 15public partial class Start_SellPlan_CategorySellPlan : System.Web.UI.Page
 16{
 17    private static DataTable dtRole = new DataTable();
 18    private static DataTable dtPrice = new DataTable();
 19
 20    public Start_SellPlan_CategorySellPlan()
 21    {
 22        this.Init += new EventHandler(Start_SellPlan_CategorySellPlan_Init);
 23    }

 24
 25    void Start_SellPlan_CategorySellPlan_Init(object sender, EventArgs e)
 26    {
 27        Bind();
 28        BindMonthPlan();
 29        BindDataView();
 30    }

 31
 32    protected void Page_Load(object sender, EventArgs e)
 33    {
 34        if (Session["PersonsID"] == null)
 35            Response.Write("<script language='javascript'>top.location.href='/cmindex.aspx'</script>");
 36        if (!Page.IsPostBack)
 37        {
 38            this.ibSave.Enabled = HasPermissions.HasPermission(CM.Data.UserRolePermission.MonthCategoryPlan.保存);
 39            CheckComment();
 40        }

 41        this.Label1.Text = "";
 42        this.Label2.Text = "";
 43    }

 44    private void BindDataView()
 45    {
 46        CreateGrid();
 47        grid.DataSource = CreateSource();
 48        grid.DataBind();
 49    }

 50
 51    private void Bind()
 52    {
 53        CM.Data.Category.CategoryTableAdapters.PL_CATEGORYPERIODTableAdapter a = new CM.Data.Category.CategoryTableAdapters.PL_CATEGORYPERIODTableAdapter();
 54        DataTable dt = a.GetData();
 55        this.DropDownList1.DataSource = dt;
 56        this.DropDownList1.DataBind();
 57        this.DropDownList2.DataBind();
 58    }

 59
 60    private void BindMonthPlan()
 61    {
 62        this.lbMonthPlan.Text = "";
 63        if (this.DropDownList2.SelectedItem != null)
 64        {
 65            DataTable dt = CM.Data.SellPlan.SellPlan.GetPeriodMonthPlan(this.DropDownList1.SelectedValue, this.DropDownList2.SelectedItem.Text);
 66            if (dt.Rows.Count > 0)
 67            {
 68                this.lbForestQuantity.Text = dt.Rows[0]["ForestQuantity"].ToString();
 69                this.lbFixQuantity.Text = dt.Rows[0]["FixQuantity"].ToString();
 70                this.lbMonthPlan.Text = dt.Rows[0]["AssignMentQuantity"].ToString();
 71            }

 72        }

 73        else
 74            Response.Write("<script language='javascript'>alert('您还没做这个半年计划!请做好计划再分配!');location.href='MonthSellPlan.aspx';</script>");
 75    }

 76    private void CreateGrid()
 77    {
 78        bool enabled = true;
 79        try
 80        {
 81            if (Int32.Parse(this.DropDownList2.SelectedItem.Text) < DateTime.Now.Month)
 82                enabled = false;
 83            else
 84                enabled = true;
 85        }

 86        catch
 87        {
 88            Response.Write("<script language='javascript'>alert('您还没做半年计划!请做好计划再分配!');location.href='MonthSellPlan.aspx';</script>");
 89        }

 90        MyRegion#region MyRegion
 91        
 92        grid.ItemCreated += new DataGridItemEventHandler(grid_ItemCreated);
 93        grid.Columns.Clear();
 94        grid.CellPadding = 2;
 95        grid.Attributes.Add("align", "center");
 96        grid.CellSpacing = 0;
 97        grid.Width = System.Web.UI.WebControls.Unit.Percentage(98);
 98        grid.BorderWidth = 1;
 99        grid.BorderColor = ColorTranslator.FromHtml("Black");
100        grid.AutoGenerateColumns = false;
101        grid.ForeColor = ColorTranslator.FromHtml("Black");
102        grid.Font.Size = 9;
103        grid.Font.Name = "宋体";
104        grid.AllowSorting = true;
105        grid.ItemStyle.Height = 25;
106        grid.GridLines = GridLines.Both;
107
108        /**////sort命令的事件处理器
109
110        //grid.SortCommand += new DataGridSortCommandEventHandler(Sort_Grid);
111
112        /**////设置headerstyle
113        //grid.HeaderStyle.BackColor = ColorTranslator.FromHtml("Gold");
114        //grid.HeaderStyle.ForeColor = ColorTranslator.FromHtml("Black");
115        grid.HeaderStyle.Font.Name = "宋体";
116        grid.HeaderStyle.Font.Size = 9;
117        grid.HeaderStyle.Font.Bold = true;
118        grid.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
119
120        /**////设置footerstyle
121        //grid.FooterStyle.BackColor = ColorTranslator.FromHtml("Gold");
122        //grid.FooterStyle.ForeColor = ColorTranslator.FromHtml("Black");
123        grid.FooterStyle.Font.Name = "宋体";
124        grid.FooterStyle.Font.Size = 9;
125        grid.FooterStyle.Font.Bold = true;
126        grid.FooterStyle.HorizontalAlign = HorizontalAlign.Center;
127
128        /**////设置alternating style
129        //grid.AlternatingItemStyle.BackColor = ColorTranslator.FromHtml("Silver");
130        //grid.AlternatingItemStyle.ForeColor = ColorTranslator.FromHtml("Black");
131
132        /**////设置itemstyle
133        grid.ItemStyle.HorizontalAlign = HorizontalAlign.Left;
134
135        /**////创建绑定列和属性
136
137        ///

138        grid.DataKeyField = "CategoryPriceID";
139        BoundColumn columnPrice = new BoundColumn();
140
141        columnPrice.HeaderText = "";
142        columnPrice.DataField = "NAME";
143        columnPrice.ItemStyle.HorizontalAlign = HorizontalAlign.Left;
144        //columnPrice.SortExpression = "NAME";
145
146        grid.Columns.AddAt(0, columnPrice); 
147        #endregion

148
149        CM.Data.Category.CategoryRoleTableAdapters.CATEGORYROLETA cta = new CM.Data.Category.CategoryRoleTableAdapters.CATEGORYROLETA();
150        dtRole = cta.GetData(this.DropDownList1.SelectedValue);
151        if (dtRole != null)
152        {
153            for (int i = 0; i < dtRole.Rows.Count; i++)
154            {
155                MyRegion#region MyRegion
156                /**/////BoundColumn column = new BoundColumn();
157                //BoundColumn column1 = new BoundColumn();
158                //BoundColumn column2 = new BoundColumn();
159
160                /**/////column.HeaderText = "预测量";
161                ////column.DataField = "FORESTQUANTITY" + Convert.ToString(3 * i + 1);
162                ////column.SortExpression = "FORESTQUANTITY";

163
164                //column1.HeaderText = "修正值";
165                //column1.DataField = "FIXQUANTITY" + Convert.ToString(2 * i + 1);
166                //column1.SortExpression = "FIXQUANTITY";
167
168                //column2.HeaderText = "计划量";
169                //column2.DataField = "ASSIGNMENTQUANTITY" + Convert.ToString(2 * i + 2);
170                //column2.SortExpression = "ASSIGNMENTQUANTITY";
171
172                /**/////grid.Columns.AddAt(3 * i + 1, column);
173                //grid.Columns.AddAt(2 * i + 1, column1);
174                //grid.Columns.AddAt(2 * i + 2, column2); 
175                #endregion

176
177                /**////设置模板列属性和ItemStyle模板
178                ///

179                ColumnTextBoxTemplate ctbt1 = new ColumnTextBoxTemplate("FIXQUANTITY" + Convert.ToString(2 * i + 1), "CategoryID" + Convert.ToString(2 * i + 1), false, enabled);
180                TemplateColumn tm1 = new TemplateColumn();
181                tm1.HeaderText = "修正值";
182                tm1.HeaderStyle.BackColor = ColorTranslator.FromHtml("#cccccc");
183                tm1.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
184                //tm1.ItemStyle.BackColor = ColorTranslator.FromHtml("#FFFFFF");
185                tm1.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
186                
187
188                /**////创建列模板。
189
190                ///列模板从ITemplate继承

191                tm1.ItemTemplate = ctbt1;
192                grid.Columns.Add(tm1);
193
194                ColumnTextBoxTemplate ctbt2 = new ColumnTextBoxTemplate("ASSIGNMENTQUANTITY" + Convert.ToString(2 * i + 2), "CategoryID" + Convert.ToString(2 * i + 2), false, enabled);
195                TemplateColumn tm2 = new TemplateColumn();
196                tm2.HeaderText = "计划值";
197                tm2.HeaderStyle.BackColor = ColorTranslator.FromHtml("#cccccc");
198                tm2.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
199                //tm2.ItemStyle.BackColor = ColorTranslator.FromHtml("#FFFFFF");
200                tm2.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
201
202                /**////创建列模板。
203
204                ///列模板从ITemplate继承

205                tm2.ItemTemplate = ctbt2;
206                grid.Columns.Add(tm2);
207            }

208        }

209        BoundColumn columnPriceTotal = new BoundColumn();
210
211        columnPriceTotal.HeaderText = "";
212        columnPriceTotal.DataField = "";
213        columnPriceTotal.ItemStyle.ForeColor = Color.Blue;
214        columnPriceTotal.ItemStyle.Font.Bold = true;
215        columnPriceTotal.ItemStyle.HorizontalAlign = HorizontalAlign.Right;
216        grid.Columns.Add(columnPriceTotal);
217        /**////绑定和返回
218
219
220        grid.ItemDataBound += new DataGridItemEventHandler(grid_ItemDataBound);
221      
222    }

223
224    void grid_ItemDataBound(object sender, DataGridItemEventArgs e)
225    {
226        if (e.Item.ItemType == ListItemType.Footer)
227        {
228            e.Item.SetRenderMethodDelegate(new RenderMethod(FootRenderMethod));
229        }

230    }

231
232    void grid_ItemCreated(object sender, DataGridItemEventArgs e)
233    {
234        if (e.Item.ItemType == ListItemType.Header)
235        {
236            e.Item.SetRenderMethodDelegate(new RenderMethod(NewRenderMethod));
237        }

238    }

239    private void FootRenderMethod(HtmlTextWriter writer, Control ctl)
240    {
241        writer.Write("<TD style=\"color:#ff0000;\" align=\"center\">总量统计:</TD>\n");
242        for (int i = 0; i < dtRole.Rows.Count; i++)
243        {
244            try
245            {
246                writer.Write("<td style=\"color:#ff0000;\" align=center>");
247
248                decimal count1 = 0;
249
250                foreach (DataGridItem item in grid.Items)
251                {
252                    count1 += decimal.Parse(((TextBox)item.Cells[2 * i + 1].Controls[0]).Text);
253                }

254                writer.Write(count1.ToString());
255                writer.Write("</td>");
256                writer.Write("<td style=\"color:#ff0000;\" align=center>");
257
258                decimal count = 0;
259                foreach (DataGridItem item in grid.Items)
260                {
261                    count += decimal.Parse(((TextBox)item.Cells[2 * i + 2].Controls[0]).Text);
262                }

263                writer.Write(count.ToString());
264                writer.Write("</td>");
265            }

266            catch
267            {
268                //Response.Write("<script langugage='javascript'>alert('输入的数量格式不正确!');</script>");
269            }

270        }

271        writer.Write("<td style='color:Blue;font-weight:bold;' align='right'></td>");
272    }

273    private void NewRenderMethod(HtmlTextWriter writer, Control ctl)
274    {
275        writer.Write("<TD style=\"color:#ff0000;\" align=\"center\" rowspan=2>价格区间</TD>\n");
276        for (int i = 0; i < dtRole.Rows.Count; i++)
277        {
278            DataTable dt = CM.Data.SellPlan.SellPlan.GetMonthRolePlan(dtRole.Rows[i]["RoleID"].ToString(), this.DropDownList2.SelectedValue);
279            writer.Write("<td style=\"color:#ff0000;\" align=center colspan=2>");
280            if (dt.Rows.Count > 0)
281            {
282                writer.Write(dtRole.Rows[i]["RoleName"] + "[" + dt.Rows[0]["AssignMentQuantity"] + "]");
283            }

284            else
285            {
286                writer.Write(dtRole.Rows[i]["RoleName"] + "[0]");
287            }

288            writer.Write("</td>");
289        }

290        writer.Write("<TD style=\"color:#ff0000;\" align=\"center\" rowspan=2>价格区间<br>计划总计</TD>\n");
291        writer.Write("</tr>");
292        for (int i = 1; i <= ctl.Controls.Count - 2; i++)
293        {
294            ctl.Controls[i].RenderControl(writer);
295        }

296    }
  
297    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
298    {
299        this.DropDownList2.DataBind();
300        BindMonthPlan();
301        BindDataView();
302        CheckComment();
303    }

304    public class ColumnTextBoxTemplate : ITemplate
305    {
306        public string columnname = "";
307        public string categoryid = "";
308        public bool islabel = true;//显示修正值为LABEL
309        public bool isenabled = true;//是否可编辑
310 //       public string monthplanid = "";
311        /**//// <summary>
312        /// 
313        /// </summary>
314        /// <param name="columnName">绑定列字段名</param>

315        public ColumnTextBoxTemplate(string columnName, string categoryID, bool show, bool enabled)
316        {
317            columnname = columnName;
318            categoryid = categoryID;
319            islabel = show;
320            isenabled = enabled;
321 //           monthplanid = monthPlanID;
322        }

323
324        public void InstantiateIn(Control container)
325        {
326            if (!islabel)
327            {
328                TextBox tb = new TextBox();
329                tb.DataBinding += new EventHandler(tb_DataBinding);
330                tb.Width = 40;
331                container.Controls.Add(tb);
332            }

333            else
334            {
335                Label lb = new Label();
336                lb.DataBinding += new EventHandler(lb_DataBinding);
337                lb.Width = 50;
338                container.Controls.Add(lb);
339            }

340        }

341
342        void lb_DataBinding(object sender, EventArgs e)
343        {
344            Label l = (Label)sender;//TextBox发送绑定请求
345
346            DataGridItem container = (DataGridItem)l.NamingContainer;
347            l.Text = ((DataRowView)container.DataItem)[columnname].ToString();//绑定字段
348        }

349
350        void tb_DataBinding(object sender, EventArgs e)
351        {
352            TextBox l = (TextBox)sender;//TextBox发送绑定请求
353
354            DataGridItem container = (DataGridItem)l.NamingContainer;
355            l.Text = ((DataRowView)container.DataItem)[columnname].ToString();//绑定字段
356            l.Enabled = isenabled;
357            l.Attributes.Add("categoryID",((DataRowView)container.DataItem)[categoryid].ToString());//绑定字段
358            l.Attributes.Add("onchange", "javascript:DataGridInputChanged();");
359        }

360    }

361    public DataView CreateSource()
362    {
363        dtPrice = CM.Data.Report.ReportMethod.GetCategoryPrice(this.DropDownList1.SelectedValue);
364        CM.Data.Category.CategoryRoleTableAdapters.CATEGORYROLETA cta = new CM.Data.Category.CategoryRoleTableAdapters.CATEGORYROLETA();
365        dtRole = cta.GetData(this.DropDownList1.SelectedValue);
366        DataTable dt = new DataTable();
367        if (dtRole.Rows.Count > 0)
368        {
369            DataColumn columnPriceID = new DataColumn("CategoryPriceID");
370            dt.Columns.Add(columnPriceID);
371            DataColumn columnPrice = new DataColumn("Name");
372            dt.Columns.Add(columnPrice);
373
374            for (int i = 0; i < dtRole.Rows.Count; i++)
375            {
376                //DataColumn column = new DataColumn("FORESTQUANTITY" + Convert.ToString(3 * i + 1));
377                DataColumn column1 = new DataColumn("FIXQUANTITY" + Convert.ToString(2 * i + 1));
378                DataColumn column2 = new DataColumn("ASSIGNMENTQUANTITY" + Convert.ToString(2 * i + 2));
379                DataColumn column3 = new DataColumn("CategoryID" + Convert.ToString(2 * i + 1));
380                DataColumn column4 = new DataColumn("CategoryID" + Convert.ToString(2 * i + 2));
381                //dt.Columns.Add(column);
382                dt.Columns.Add(column1);
383                dt.Columns.Add(column2);
384                dt.Columns.Add(column3);
385                dt.Columns.Add(column4);
386            }

387        }

388        if (dtPrice.Rows.Count > 0)
389        {
390            for (int i = 0; i < dtPrice.Rows.Count; i++)
391            {
392                DataRow row = dt.NewRow();
393                row["CategoryPriceID"] = dtPrice.Rows[i]["CategoryPriceID"].ToString();
394                row["Name"] = dtPrice.Rows[i]["Name"].ToString();
395                if (dtRole.Rows.Count > 0)
396                {
397                    for (int j = 0; j < dtRole.Rows.Count; j++)
398                    {
399                        
400                        string categoryID = "";
401                        DataTable dtCategory = CM.Data.Report.ReportMethod.GetCategory(dtRole.Rows[j]["RoleID"].ToString(), dtPrice.Rows[i]["CategoryPriceID"].ToString());
402                        if (dtCategory.Rows.Count > 0)
403                        {
404                            categoryID = dtCategory.Rows[0]["CategoryID"].ToString();
405
406                            DataTable dtMonthCategory = CM.Data.SellPlan.SellPlan.GetMonthCategoryPlan(categoryID, this.DropDownList2.SelectedValue);
407                            if (dtMonthCategory.Rows.Count > 0)
408                            {
409                                row["FIXQUANTITY" + Convert.ToString(2 * j + 1)] = dtMonthCategory.Rows[0]["FIXQUANTITY"].ToString();
410                                row["ASSIGNMENTQUANTITY" + Convert.ToString(2 * j + 2)] = dtMonthCategory.Rows[0]["ASSIGNMENTQUANTITY"].ToString();
411                            }

412                            else
413                            {
414                                DataTable dtMonthCategoryForest = CM.Data.SellPlan.SellPlan.GetMonthCategoryForest(this.DropDownList1.SelectedValue, categoryID);
415                                if (dtMonthCategoryForest.Rows.Count > 0)
416                                {
417                                    string forest = (dtMonthCategoryForest.Rows[0]["forestquantity"].ToString() == "") ? "0" : dtMonthCategoryForest.Rows[0]["forestquantity"].ToString();
418                                    string total = (dtMonthCategoryForest.Rows[0]["total"].ToString() == "" || dtMonthCategoryForest.Rows[0]["total"].ToString() == "0") ? "1" : dtMonthCategoryForest.Rows[0]["total"].ToString();
419                                    double percent = double.Parse(forest) / double.Parse(total);
420                                    double fix = double.Parse((this.lbFixQuantity.Text == "") ? "0" : this.lbFixQuantity.Text);
421                                    double plan = double.Parse((this.lbMonthPlan.Text == "") ? "0" : this.lbMonthPlan.Text);
422                                    row["FIXQUANTITY" + Convert.ToString(2 * j + 1)] = Convert.ToString(percent * fix).Split('.')[0];
423                                    row["ASSIGNMENTQUANTITY" + Convert.ToString(2 * j + 2)] = Convert.ToString(percent * plan).Split('.')[0];
424                                }

425                                else
426                                {
427                                    row["FIXQUANTITY" + Convert.ToString(2 * j + 1)] = 0;
428                                    row["ASSIGNMENTQUANTITY" + Convert.ToString(2 * j + 2)] = 0;
429                                }

430                            }

431                            row["CategoryID" + Convert.ToString(2 * j + 1)] = dtCategory.Rows[0]["CategoryID"].ToString();
432                            row["CategoryID" + Convert.ToString(2 * j + 2)] = dtCategory.Rows[0]["CategoryID"].ToString();
433                        }

434                        //else
435                        //{
436                        //    //row["FIXQUANTITY" + Convert.ToString(2 * j + 1)] = 0;
437                        //    //row["ASSIGNMENTQUANTITY" + Convert.ToString(2 * j + 2)] = 0;
438                        //    //row["CategoryID" + Convert.ToString(2 * j + 1)] = 0;
439                        //    //row["CategoryID" + Convert.ToString(2 * j + 2)] = 0;
440                        //    Response.Write("<script language='javascript'>alert('您还没维护好品牌分类组合,请先分好再操作!');location.href='/Start/ProductCategory/CategoryList.aspx';</script>");
441                        //}
442                    }

443                }

444                dt.Rows.Add(row);
445            }

446        }

447        return dt.DefaultView;
448    }

449    protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
450    {
451        BindMonthPlan();
452        BindDataView();
453        CheckComment();
454    }

455
456    protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
457    {
458        try
459        {
460            DataGrid dg = grid;
461
462            //for (int i = 0; i < dtRole.Rows.Count; i++)
463            //{
464            //    decimal listCount = 0;
465            //    foreach (DataGridItem item in dg.Items)
466            //    {
467            //        string tbText = (((TextBox)item.Cells[2 * i + 2].Controls[0]).Text == "") ? "0" : ((TextBox)item.Cells[2 * i + 2].Controls[0]).Text;
468            //        listCount += decimal.Parse(tbText);
469            //    }
470            //    this.Label1.Text += "第<font color=blue>" + Convert.ToString(2 * i + 2) + "</font>列总量为<font color=red>" + listCount.ToString() + "</font>";
471            //}
472            //for (int j = 0; j < dg.Items.Count; j++)
473            //{
474            //    decimal rowCount = 0;
475            //    for (int i = 0; i < dtRole.Rows.Count; i++)
476            //    {
477            //        string tbText = (((TextBox)dg.Items[j].Cells[2 * i + 2].Controls[0]).Text == "") ? "0" : ((TextBox)dg.Items[j].Cells[2 * i + 2].Controls[0]).Text;
478            //        rowCount += decimal.Parse(tbText);
479            //    }
480            //    this.Label2.Text += "第<font color=blue>" + j.ToString() + "</font>行总量为<font color=red>" + rowCount.ToString() + "</font>";
481            //}
482            foreach (DataGridItem item in dg.Items)
483            {
484                for (int i = 0; i < dtRole.Rows.Count; i++)
485                {
486                    string categoryID = ((TextBox)item.Cells[2 * i + 2].Controls[0]).Attributes["CategoryID"].ToString();
487                    decimal fixquantity = decimal.Parse(((TextBox)item.Cells[2 * i + 1].Controls[0]).Text);
488                    decimal quantity = decimal.Parse(((TextBox)item.Cells[2 * i + 2].Controls[0]).Text);
489                    string monthplanid = this.DropDownList2.SelectedValue;
490                    DataTable dtMonthCategory = CM.Data.SellPlan.SellPlan.GetMonthCategoryPlan(categoryID, monthplanid);
491                    if (dtMonthCategory.Rows.Count > 0)
492                        CM.Data.SellPlan.SellPlan.UpdateMonthCategoryPlan(categoryID, monthplanid, fixquantity, quantity);
493                    else
494                        CM.Data.SellPlan.SellPlan.AddMonthCategoryPlan(categoryID, monthplanid, fixquantity, quantity);
495                }

496            }

497            BindDataView();
498            CheckComment();
499            Response.Write("<script language='javascript'>alert('保存成功!');</script>");
500        }

501        catch
502        {
503            Response.Write("<script language='javascript'>alert('输入的数量格式不正确!');</script>");
504        }

505    }

506    protected void IBCommand(object sender, CommandEventArgs e)
507    {
508        //CurrentMonth = this.DropDownList2.SelectedItem.Text;
509        string auditingid, applyerid, assessorid, applydate, auditingdate, isapplyed, isaudited, auditedcomment, auditingtype;
510        auditingid = this.DropDownList2.SelectedValue;
511        applyerid = HttpContext.Current.Session["PersonsID"].ToString();
512        assessorid = "";
513        applydate = System.DateTime.Now.ToString("yyyyMMdd");
514        auditingdate = "";
515        isapplyed = "1";
516        isaudited = "-1";
517        auditedcomment = "";
518        auditingtype = ((int)AuditingType.CategoryPlan).ToString();
519
520        ArrayList arr = new ArrayList();
521        arr.Add(auditingid);
522        arr.Add(applyerid);
523        arr.Add(assessorid);
524        arr.Add(applydate);
525        arr.Add(auditingdate);
526        arr.Add(isapplyed);
527        arr.Add(isaudited);
528        arr.Add(auditedcomment);
529        arr.Add(auditingtype);
530
531        AuditingInfo ainfo = Auditing.GetAuditingInfo(auditingid, AuditingType.CategoryPlan);
532        string cmd = e.CommandName;
533        switch (cmd)
534        {
535            case "Apply":
536                if (ainfo == null)
537                    CM.Data.Forest.Auditing.AddAuditingInfo(arr);
538                else
539                    CM.Data.Forest.Auditing.UpdateAuditingInfo(auditingid, applyerid, applydate, AuditingType.CategoryPlan);
540                break;
541            case "UnApply":
542                if (ainfo != null)
543                    CM.Data.Forest.Auditing.UpdateAuditingInfo(auditingid, AuditingType.CategoryPlan);
544
545                break;
546            case "Auditing":
547                if (ainfo != null)
548                {
549                    assessorid = HttpContext.Current.Session["PersonsID"].ToString();
550                    auditingdate = System.DateTime.Now.ToString("yyyyMMdd");
551                    CM.Data.Forest.Auditing.UpdateAuditingInfo1(auditingid, assessorid, auditingdate, AuditingType.CategoryPlan);
552                }

553                break;
554            case "UnAuditing":
555                this.comment.Visible = true;
556                this.ibSubmit.Enabled = true;
557                break;
558            case "UnPass":
559                if (ainfo != null)
560                    CM.Data.Forest.Auditing.UpdateAuditingInfo(auditingid, assessorid, auditingdate, this.tbComment.Text.Trim(), AuditingType.CategoryPlan);
561                this.comment.Visible = false;
562                break;
563        }

564        CheckComment();
565        BindDataView();
566    }

567
568    protected void CheckComment()
569    {
570        this.lbUnAuditingComment.Text = "";
571        this.ibApply.Enabled = false;
572        this.ibUnApply.Enabled = false;
573        this.ibAuditing.Enabled = false;
574        this.ibUnAuditing.Enabled = false;
575        AuditingInfo ainfo = Auditing.GetAuditingInfo(this.DropDownList2.SelectedValue, AuditingType.CategoryPlan);
576        if (ainfo == null)
577        {
578            this.ibApply.Enabled = true;
579            this.lbUnAuditingComment.Text = "还未提交审核!";
580        }

581        else
582        {
583            if (ainfo.isApplyed == "0")
584            {
585                this.ibApply.Enabled = true;
586                this.lbUnAuditingComment.Text = "已撤消审核!";
587            }

588            else
589            {
590                this.ibApply.Enabled = false;
591                this.ibUnApply.Enabled = true;
592                this.ibAuditing.Enabled = true;
593                this.ibUnAuditing.Enabled = true;
594                if (ainfo.isAudited == "0")
595                {
596                    this.ibUnAuditing.Enabled = false;
597                    this.lbUnAuditingComment.Text = "不通过原因:<font color=red>" + ainfo.auditedComment + "</font>";
598                }

599                if (ainfo.isAudited == "1")
600                {
601                    this.lbUnAuditingComment.Text = "已通过审核";
602                    this.ibUnApply.Enabled = false;
603                    this.ibAuditing.Enabled = false;
604                }

605                if (ainfo.isAudited == "-1")
606                {
607                    this.lbUnAuditingComment.Text = "未审核";
608                }

609            }

610        }

611        //this.ibApply.Enabled = HasPermissions.HasPermission(CM.Data.UserRolePermission.CategoryForcast.结构预测申请审核);
612        //this.ibUnApply.Enabled = HasPermissions.HasPermission(CM.Data.UserRolePermission.CategoryForcast.结构预测撤消申请审核);
613        //this.ibAuditing.Enabled = HasPermissions.HasPermission(CM.Data.UserRolePermission.CategoryForcast.结构预测审核通过);
614        //this.ibUnAuditing.Enabled = HasPermissions.HasPermission(CM.Data.UserRolePermission.CategoryForcast.结构预测审核不通过);
615    }

616}

617
程序写的比较繁琐,多次绑定了datagrid,不知哪位高手可以给个精简一点的方法.

posted on 2006-04-25 16:47  孙彬  阅读(1384)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3