zoukankan      html  css  js  c++  java
  • gridview 编辑 ,删除

    前台 aspx :

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridViewEditDelete.aspx.cs" Inherits="GridViewEditDelete" %>

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
        <link href="css/css.css" rel="stylesheet" type="text/css" />
        <script type="text/javascript">
            var prevselitem = null;
            function selectx(row) {
                if (prevselitem != null) {
                    prevselitem.style.backgroundColor = '#FCFCFC';
                }
                row.style.backgroundColor = '#FFD306';
                prevselitem = row;

            }
    </script>
      <script language="javascript" type="text/javascript">

          function KeyPress(obj) {

              var txtval = obj.value;

              var key = event.keyCode;

              if ((key < 48 || key > 57) && key != 46) {

                  event.keyCode = 0;

              }

              else {

                  if (key == 46) {

                      if (txtval.indexOf(".") != -1 || txtval.length == 0)

                          event.keyCode = 0;

                  }

              }

          }

          //digit:小数点位数

          function keyUp(obj, digit) {

              var digit = digit + 1;

              var key = event.keyCode;

              if (key != 110) {

                  var objVal = obj.value;

                  if (objVal.indexOf(".") != -1) {

                      if ((objVal.length - objVal.indexOf(".")) > digit) {

                          obj.value = objVal.substr(0, objVal.length - ((objVal.length - objVal.indexOf(".")) - digit));

                      }

                  }

              }

          }

        </script>
        <script type="text/javascript">

            function cnVeryCalendar() {
                //Style
                var border_frame = '#468DDD';
                var border_inner = '#f6f6f6';
                var fore_frameCaption = '#ffffff';
                var back_frameCaption = '#468DDD';
                var fore_currentMonth = '#ff0000';
                var back_weekName = '#e9e9e9';
                var back_nullDay = '#fafafa';
                var fore_dayMouseOver = '#ff6600';
                var back_dayMouseOver = '#eeeeee';
                var font_cnChar = 'font-family:宋体,sans-serif; font-size:12px;';
                var font_numChar = 'font-family:tahoma,arial,sans-seirf; font-size:11px;';
                var style_cell = 'line-height:14px; border-color:' + border_inner;
                var today_decoration = "font-weight:bold; background:url('images/calendar_today.gif') center no-repeat;"
                // "font-weight:bold"

                //Declare
                var reciever;
                var today = new Date();
                var y = today.getFullYear();
                var m = today.getMonth() + 1;


                //Return Max Days In The Month
                this.daysInMonth = function (y, m) {
                    switch (m) {
                        case 1:
                        case 3:
                        case 5:
                        case 7:
                        case 8:
                        case 10:
                        case 12:
                            return 31;
                        case 4:
                        case 6:
                        case 9:
                        case 11:
                            return 30;
                        case 2:
                            //Is Leep Year
                            if (y % 4 != 0) {
                                return 28;
                            }
                            if (y % 100 == 0) {
                                return y % 400 == 0 ? 29 : 28;
                            }
                            return 29;
                    }
                }


                //Generate Codes
                this.generateCalendarTable = function () {
                    var i;
                    var j = new Date(y, m - 1, 1).getDay();
                    var k = this.daysInMonth(y, m);
                    var body = '';

                    //Frame Table Header
                    body += "<table align='center' cellpadding='2' cellspacing='1' width='100%' height='100%' style='border:1px " + border_frame + " solid; background:white;'>";
                    body += " <tr>";
                    body += " <td style='background:" + back_frameCaption + ";" + font_cnChar + "' height='20'>";
                    body += " <div style='color:" + fore_frameCaption + "; float:left'><b>日历控件</b></div>";
                    body += " <div style='float:right'>";
                    body += " <a href=\"javascript:calendar.setValue('')\" style='color:" + fore_frameCaption + "; text-decoration:none;" + font_cnChar + "'>[擦除]</a> ";
                    body += " <a href='javascript:calendar.fadeOut()' style='color:" + fore_frameCaption + "; text-decoration:none;" + font_cnChar + "'>[关闭]</a>";
                    body += " </div>";
                    body += " </td>";
                    body += " </tr>";
                    body += " <tr>";
                    body += " <td style='padding-bottom:0px'>";
                    body += " <table align='center' width='99%' cellpadding='0' cellspacing='0'>";
                    body += " <tr>";
                    body += " <td style='" + font_cnChar + "'><a href='javascript:calendar.loadPreviousYear()' style='text-decoration:none; color:" + fore_dayMouseOver + "'><font face='webdings'>3</font></a>年<a href='javascript:calendar.loadNextYear()' style='text-decoration:none; color:" + fore_dayMouseOver + "'><font face='webdings'>4</font></a></td>";
                    body += " <td align='center' nowrap='nowrap' style='color:" + fore_currentMonth + ";" + font_cnChar + "'><b>" + y + "年" + m + "月</b></td>";
                    body += " <td align='right' style='" + font_cnChar + "'><a href='javascript:calendar.loadPreviousMonth()' style='text-decoration:none; color:" + fore_dayMouseOver + "'><font face='webdings'>3</font></a>月<a href='javascript:calendar.loadNextMonth()' style='text-decoration:none; color:" + fore_dayMouseOver + "'><font face='webdings'>4</font></a></td>";
                    body += " </tr>";
                    body += " </table>";
                    body += " </td>";
                    body += " </tr>";
                    body += " <tr>";
                    body += " <td>";

                    //Calendar Table Header
                    body += "<table align='center' width='99%' cellpadding='3' cellspacing='0' border='1' bordercolor='" + border_inner + "' style='border-collapse:collapse; table-layout:fixed;'>";
                    body += " <tr align='center' style='background:" + back_weekName + "'>";
                    body += " <td style='" + font_cnChar + style_cell + "'>日</td>";
                    body += " <td style='" + font_cnChar + style_cell + "'>一</td>";
                    body += " <td style='" + font_cnChar + style_cell + "'>二</td>";
                    body += " <td style='" + font_cnChar + style_cell + "'>三</td>";
                    body += " <td style='" + font_cnChar + style_cell + "'>四</td>";
                    body += " <td style='" + font_cnChar + style_cell + "'>五</td>";
                    body += " <td style='" + font_cnChar + style_cell + "'>六</td>";
                    body += " </tr>";

                    //Insert Null Days Before The First Day In Current Month
                    if (j != 0) {
                        body += "<tr align='center'>";
                        body += ("<td style='background:" + back_nullDay + style_cell + "' colspan='" + j + "'></td>");
                    }

                    //Loop Each Days In Current Month
                    for (i = 1; i <= k; i++) {
                        //Row Begin
                        if ((i + j) % 7 == 1) {
                            body += "<tr align='center'>";
                        }

                        //Cells Day By Day
                        body += "<td";
                        body += " onmouseover=\"this.style.backgroundColor='" + back_dayMouseOver + "'; this.style.color='" + fore_dayMouseOver + "'\"";
                        body += " onmouseout=\"this.style.backgroundColor=''; this.style.color=''\"";
                        body += " onclick=\"calendar.setValue('" + y + "-" + m + "-" + i + "')\"";
                        if (y == today.getFullYear() && m == today.getMonth() + 1 && i == today.getDate()) {
                            body += " style=\"cursor:hand; " + today_decoration + "; " + font_numChar + style_cell + "\"";
                        }
                        else {
                            body += " style='cursor:hand; " + font_numChar + style_cell + "'";
                        }
                        body += ">" + i + "</td>";

                        //Row End
                        if ((i + j) % 7 == 0) {
                            body += ("</tr>");
                        }
                    }

                    //Append Null Days After The Last Day In Current Month
                    if ((i + j) % 7 != 0) {
                        body += ("<td style='background:" + back_nullDay + style_cell + "' colspan='" + (8 - (i + j) % 7) + "'></td>");
                        body += ("</tr>");
                    }
                    if (j < (36 - k)) {
                        body += ("<tr><td colspan='7' style='background:" + back_nullDay + style_cell + "'>&nbsp;</td></tr>");
                    }
                    if (j == 0 && k == 28) {
                        body += ("<tr><td colspan='7' style='background:" + back_nullDay + style_cell + "'>&nbsp;</td></tr>");
                    }

                    //End Calendar Table
                    body += "</table>";

                    //End Frame Table
                    body += "</td></tr></table>";

                    //Return
                    return body;
                }


                //Load Previous Year
                this.loadPreviousYear = function () {
                    y--;
                    __cnVeryCalendarContainer.innerHTML = this.generateCalendarTable();
                }
                this.loadNextYear = function () {
                    y++;
                    __cnVeryCalendarContainer.innerHTML = this.generateCalendarTable();
                }
                this.loadPreviousMonth = function () {
                    m--;
                    if (m < 1) {
                        m = 12;
                        y--;
                    }
                    __cnVeryCalendarContainer.innerHTML = this.generateCalendarTable();
                }
                this.loadNextMonth = function () {
                    m++;
                    if (m > 12) {
                        m = 1;
                        y++;
                    }
                    __cnVeryCalendarContainer.innerHTML = this.generateCalendarTable();
                }


                //Get Position
                this.getAbsolutePosition = function (element) {
                    var point = { x: element.offsetLeft, y: element.offsetTop };
                    //Recursion
                    if (element.offsetParent) {
                        var parentPoint = this.getAbsolutePosition(element.offsetParent);
                        point.x += parentPoint.x;
                        point.y += parentPoint.y;
                    }
                    return point;
                };


                //Pop Layer
                this.setHook = function (dateField) {
                    if (__cnVeryCalendarContainer.style.display != 'none' && reciever.id == dateField.id) {
                        __cnVeryCalendarContainer.style.display = 'none';
                        return;
                    }
                    reciever = dateField;

                    //-- 如果不想在第二次打开日历时回归为当前月,则把下面两行注释掉或删掉 --
                    y = today.getFullYear();
                    m = today.getMonth() + 1;
                    //----------------------------

                    var point = this.getAbsolutePosition(dateField);
                    __cnVeryCalendarContainer.style.left = (point.x + dateField.offsetWidth + 5) + 'px';
                    __cnVeryCalendarContainer.style.top = point.y + 'px';
                    __cnVeryCalendarContainer.innerHTML = this.generateCalendarTable();
                    __cnVeryCalendarContainer.style.display = '';
                }


                //Hide Layer
                this.fadeOut = function () {
                    __cnVeryCalendarContainer.style.display = 'none';
                }


                //Click a Day Cell To Add The Value
                this.setValue = function (date) {
                    reciever.value = date;
                    this.fadeOut();
                }
            }

            //Render Instance
            document.write("<div id='__cnVeryCalendarContainer' style='200px; height:190px; position:absolute; float:left; display:none; z-index:999'></div>");
            var calendar = new cnVeryCalendar();
      
       </script>
    </head>
    <body>
        <form id="form1" runat="server">
        <table width="800" align="center">
        <tr>
         <td align="center">
            <asp:GridView ID="GridView1" Width="100%" runat="server" DataKeyNames="ID"
                 CellPadding="3" GridLines="None" BackColor="Black" CellSpacing="1"
                 AutoGenerateColumns="False" onrowcancelingedit="GridView1_RowCancelingEdit"
                 onrowdeleting="GridView1_RowDeleting" onrowediting="GridView1_RowEditing"
                 onrowupdating="GridView1_RowUpdating"
                 onrowdatabound="GridView1_RowDataBound" ShowFooter="True">
                   <RowStyle BackColor="#ECF5FF" ForeColor="Black" />
                   <SelectedRowStyle BackColor="#9471DE" Font-Bold="True" ForeColor="White" />
                   <PagerStyle BackColor="#C6C3C6" ForeColor="Black" HorizontalAlign="Right" />
                   <HeaderStyle BackColor="#006699" Font-Bold="True" Height="20" ForeColor="White"/>
                   <FooterStyle BackColor="#FFD39B" Font-Bold="True" Height="20"  ForeColor="White"/>
                 <Columns>
                     <asp:BoundField DataField="ID" HeaderText="ID" ReadOnly="true" Visible="false" />
                     <asp:TemplateField HeaderText="序号" InsertVisible="False">
                         <ItemStyle HorizontalAlign="Center" />
                         <HeaderStyle HorizontalAlign="Center" Width="5%" />
                             <ItemTemplate>
                               <%#Container.DataItemIndex+1%>
                             </ItemTemplate>
                     </asp:TemplateField>
                 
                     <asp:BoundField DataField="FuelType" HeaderText="油类别" ReadOnly="true" />
                     <asp:TemplateField HeaderText="标号">
                         <EditItemTemplate>
                                <asp:HiddenField ID="HDFXueli3" runat="server" Value='<%# Bind("FuelLevel") %>' />
                                <asp:DropDownList ID="DDLXueli3" runat="server">
                                </asp:DropDownList>    
                            <asp:RequiredFieldValidator ID="RequiredFieldValidator5" Display="Dynamic" ControlToValidate="DDLXueli3" runat="server" ErrorMessage="请选择标号"></asp:RequiredFieldValidator>
                         </EditItemTemplate>
                         <ItemTemplate>
                             <asp:Label ID="Label5" runat="server" Text='<%# Bind("FuelLevel") %>'></asp:Label>
                         </ItemTemplate>
                     </asp:TemplateField>
                     <asp:TemplateField HeaderText="加油地点">
                         <EditItemTemplate>
                          <asp:HiddenField ID="HDFXueli4" runat="server" Value='<%# Bind("Gasstation") %>' />
                                <asp:DropDownList ID="DDLXueli4" runat="server">
                                </asp:DropDownList>    
                              <asp:RequiredFieldValidator ID="RequiredFieldValidator6" Display="Dynamic" ControlToValidate="DDLXueli4" runat="server" ErrorMessage="选择加油站"></asp:RequiredFieldValidator>
                         </EditItemTemplate>
                         <ItemTemplate>
                             <asp:Label ID="Label6" runat="server" Text='<%# Bind("Gasstation") %>'></asp:Label>
                         </ItemTemplate>
                     </asp:TemplateField>
                                <asp:TemplateField HeaderText="票号">
                         <EditItemTemplate>
                             <asp:TextBox ID="TextBox9" class="inputtext"  Width="80px"  runat="server" Text='<%# Bind("TicketNumber") %>'
                        MaxLength="12"></asp:TextBox>
                                        
                          
                         </EditItemTemplate>
                         <ItemTemplate>
                             <asp:Label ID="Label4" runat="server" Text='<%# Bind("TicketNumber") %>'></asp:Label>
                         </ItemTemplate>
                     </asp:TemplateField>
                     <asp:TemplateField HeaderText="收据号">
                         <EditItemTemplate>
                             <asp:TextBox ID="TextBox14" class="inputtext"  Width="80px"  runat="server" Text='<%# Bind("ReceiptCode") %>'
                        MaxLength="12"></asp:TextBox>     
                         </EditItemTemplate>
                         <ItemTemplate>
                             <asp:Label ID="Label14" runat="server" Text='<%# Bind("ReceiptCode") %>'></asp:Label>
                         </ItemTemplate>
                     </asp:TemplateField>
                     <asp:TemplateField HeaderText="加油时间">
                         <EditItemTemplate>
                          <input id="Text1" name="txbFirstDate1" readonly="readonly" value= '<%# Bind("FuelTime", "{0:d}") %>'
                    class="inputcalendar" onmouseover="this.style.borderColor='#99E300'"
                    onmouseout="this.style.borderColor='#E7AD01'"  title="点击打开日期控件"
                    onclick="javascript:calendar.setHook(this)" runat="server" size="10" />
                        <asp:RequiredFieldValidator ID="RequiredFieldValidator3" Display="Dynamic" ControlToValidate="Text1" runat="server" ErrorMessage="请填写加油时间"></asp:RequiredFieldValidator>    
                         </EditItemTemplate>
                         <ItemTemplate>
                             <asp:Label ID="Label7" runat="server" Text='<%# Bind("FuelTime", "{0:d}") %>'></asp:Label>
                         </ItemTemplate>
                     </asp:TemplateField>
                     <asp:TemplateField HeaderText="加油人">
                         <EditItemTemplate>
                             <asp:TextBox ID="TextBox8" Width="30" MaxLength="3" runat="server" class="inputtext" Text='<%# Bind("FuelPerson") %>'></asp:TextBox>
                             <asp:RequiredFieldValidator ID="RequiredFieldValidator1" Display="Dynamic" ControlToValidate="TextBox8" runat="server" ErrorMessage="请填写加油人"></asp:RequiredFieldValidator>
                         </EditItemTemplate>
                         <ItemTemplate>
                             <asp:Label ID="Label8" runat="server" Text='<%# Bind("FuelPerson") %>'></asp:Label>
                         </ItemTemplate>
                     </asp:TemplateField>
                        <asp:TemplateField HeaderText="加油量">
                         <EditItemTemplate>
                             <asp:TextBox ID="TextBox3" class="inputtext"  Width="50px"  runat="server" Text='<%# Bind("FuelVolume") %>'
                        MaxLength="6" onkeypress="KeyPress(this);" onkeyup="keyUp(this,2);" onpaste="return false"></asp:TextBox>
                                          (公升)
                           <asp:RequiredFieldValidator ID="RequiredFieldValidator8" Display="Dynamic" ControlToValidate="TextBox3" runat="server" ErrorMessage="请填写加油量"></asp:RequiredFieldValidator>
                         </EditItemTemplate>
                         <ItemTemplate>
                             <asp:Label ID="Label3" runat="server" Text='<%# Bind("FuelVolume") %>'></asp:Label>
                         </ItemTemplate>
                     </asp:TemplateField>
                     <asp:CommandField HeaderText="修改" ShowEditButton="True" />
                     <asp:TemplateField HeaderText="删除" ShowHeader="False">
                         <ItemTemplate>
                             <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False"
                                 CommandName="Delete" Text="删除" OnClientClick="return confirm('您确认删除该记录吗?');"></asp:LinkButton>
                         </ItemTemplate>
                     </asp:TemplateField>
                    
                 </Columns>

             </asp:GridView>
            </td>
        </tr>
        </table>
        </form>
    </body>
    </html>

    -------------------------------

    后台 aspx.CS

    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.HtmlControls;
    using System.Web.UI.WebControls;
    using System.Data.SqlClient;
    using System.Data;

    public partial class GridViewEditDelete : System.Web.UI.Page
    {
        data newdata = new data();
        public int carid;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                GridViewBind();
            }

        }

        public void ddlBind(DropDownList ddl, string sql, string dtext, string dvalue, string dcode, string pleasestring)
        {
            DataSet ds = newdata.ExecuteDataset(sql);
            ddl.DataTextField = dtext;
            ddl.DataValueField = dvalue;
            ddl.DataSource = ds.Tables[0].DefaultView;
            ddl.DataBind();
            if (pleasestring != "")
            {
                ddl.Items.Insert(0new ListItem(pleasestring, ""));
            }
            if (dcode != "")
            {
                for (int i = 0; i < ddl.Items.Count; i++)
                {
                    if (ddl.Items[i].Value == dcode)
                    {
                        ddl.SelectedIndex = i;
                    }
                }
            }
        }

        
        public void GridViewBind()
        {
            carid = 385;
            string sql = "select * from FuelMonthReporter where CarID = '" + carid + "";
            DataSet ds = newdata.ExecuteDataset(sql);
            this.GridView1.DataSource = ds.Tables[0].DefaultView;
            this.GridView1.DataBind();
        }

        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            GridView1.EditIndex = e.NewEditIndex;
            GridViewBind();
        }

        protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            GridView1.EditIndex = -1;
            GridViewBind();
        }
        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            string id = GridView1.DataKeys[e.RowIndex].Values[0].ToString();
            string SqlStr = "delete from FuelMonthReporter where ID=" + id;
            newdata.ExecuteNonQuery(SqlStr);
            GridView1.EditIndex = -1;
            GridViewBind();
        }

        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            carid = 385;
            if (((DropDownList)e.Row.FindControl("DDLXueli3")) != null)
            {
                DropDownList ddlxueli3 = (DropDownList)e.Row.FindControl("DDLXueli3");
                string sql = "select * from FuelGrade";
                ddlBind(ddlxueli3, sql, "oilgrade""oilgrade"null"标号");
                ddlxueli3.SelectedValue = ((HiddenField)e.Row.FindControl("HDFXueli3")).Value;
            }

            if (((DropDownList)e.Row.FindControl("DDLXueli4")) != null)
            {
                DropDownList ddlxueli4 = (DropDownList)e.Row.FindControl("DDLXueli4");
                string sql2 = "select * from Gasstation";
                ddlBind(ddlxueli4, sql2, "gname""gname"null"加油站");
                ddlxueli4.SelectedValue = ((HiddenField)e.Row.FindControl("HDFXueli4")).Value;

            }

            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes.Add("onmouseover""if(this!=prevselitem){this.style.backgroundColor='#D2E9FF'}");//当鼠标停留时更改背景色 
                e.Row.Attributes.Add("onmouseout""if(this!=prevselitem){this.style.backgroundColor='#ECF5FF'}");//当鼠标移开时还原背景色 
            }

            
            if (e.Row.RowType == DataControlRowType.Footer)
            {


                string sqlc = "select  sum(FuelVolume) as UnitNum   from FuelMonthReporter where CarID = '" + carid + "";
                    decimal numm = decimal.Parse(newdata.ExecuteScalar(sqlc).ToString());
                    e.Row.Cells[1].Text = "合计";
                    e.Row.Cells[9].Text = numm.ToString() + " 升";
                    e.Row.Font.Bold = true;

            } 
        }

        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            string id = GridView1.DataKeys[e.RowIndex].Values[0].ToString();

            string xueli3 = ((DropDownList)GridView1.Rows[e.RowIndex].FindControl("DDLXueli3")).SelectedValue;
            string xueli4 = ((DropDownList)GridView1.Rows[e.RowIndex].FindControl("DDLXueli4")).SelectedValue;
            string addoil = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox3")).Text;
            string addperson = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox8")).Text;
            string oilticket = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox9")).Text;
            string oilreceipt = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox14")).Text;
            string adddate = ((HtmlInputText)GridView1.Rows[e.RowIndex].FindControl("Text1")).Value;

            string sql = "update FuelMonthReporter set TicketNumber = '" + oilticket + "',ReceiptCode = '" + oilreceipt + "',FuelLevel = '" + xueli3 + "',Gasstation = '" + xueli4 + "',FuelVolume = " + addoil + ",FuelPerson = '" + addperson + "',FuelTime = '" + adddate + "' where ID = '" + id + "'";
            newdata.ExecuteNonQuery(sql);
            GridView1.EditIndex = -1;
            GridViewBind();
        }
    }
  • 相关阅读:
    每日作业报告之《大道至简》读后感
    Java学习的第二十六天
    Java学习的第二十五天
    封装按钮组件
    回车导致地址栏出现?
    判断用户输入值的是不是整数
    String类型在JVM中的内存分配
    MySQL索引的原理及使用
    ICPC Yokohama, 2018(Domestic)C. Skyscraper “MinatoHarukas ” (暴力)
    CH6803 导弹发射塔(二分图最大匹配/多重匹配)
  • 原文地址:https://www.cnblogs.com/tiger8000/p/2289097.html
Copyright © 2011-2022 走看看