zoukankan      html  css  js  c++  java
  • GridView禁用掉viewstate之后的新建,编辑,删除 天高地厚

    【转载】http://blog.csdn.net/crazy7/article/details/1768542

    示例程序为一个超级Mini的图书管理,DB中只有一个名为"tableBook"的表,里面也只有三个字段ID(autonumber),bookName,BookAuthor。效果图:

    Main.aspx: 

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

    <!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>Untitled Page</title>
        
        
    <script type="text/javascript">
        
            
    //将当前行生成的文本框中的值存入相应的控件,并点击“修改”
            function Update(id)
            
    {
                
    if(confirm('确定要修改吗?'))
                
    {
                    document.getElementById(
    'hiddenId').value = id;
                    document.getElementById(
    'hiddenName').value = document.getElementById('newName').value;
                    document.getElementById(
    'hiddenAuthor').value = document.getElementById('newAuthor').value;
                    document.getElementById(
    'bnUpdate').click();
                }

            }

            
            
    //将当前行中的ID放入hiddenId并点击“删除”
            function Delete(id)
            
    {
                
    if(confirm('确定要删除吗?'))
                
    {
                    document.getElementById(
    'hiddenId').value = id;
                    document.getElementById(
    'bnDelete').click();
                }

            }

            
            
    //将当前行的RowIndx放入GVIndex并点击bnShowTextBox在当前行显示文本框
            function ShowTextBox(gvIndex)
            
    {
                document.getElementById(
    'GVIndex').value = gvIndex;
                document.getElementById(
    'bnShowTextBox').click();
            }

            
            
    //点击bnShowTextBox4New,显示用于创建的控件
            function ShowControl4New()
            
    {
                document.getElementById(
    'bnShowTextBox4New').click();
            }

            
            
    //将新建数据暂存至控件并点击“创建”
            function CreateNew()
            
    {
                
    var newName = document.getElementById('createNewName').value;
                
    var newAuthor = document.getElementById('createNewAuthor').value;
                
    //检查是否为空
                if(newName == "" || newAuthor == "")
                
    {
                    alert(
    '不可为空');
                    
    return;
                }

                document.getElementById(
    'hiddenName').value = newName;
                document.getElementById(
    'hiddenAuthor').value = newAuthor;
                document.getElementById(
    'bnCreateNew').click();
            }


        
    </script>
    </head>
    <body>
        
    <form id="form1" runat="server">
        
    <div>
            
    <table width="80%">
                
    <tr>
                    
    <td align="center">
                     
    <asp:GridView ID="gvBook" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None" OnRowDataBound="gvBook_RowDataBound" ShowFooter="True" EnableViewState="False" OnRowCreated="gvBook_RowCreated">
                        
    <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
                        
    <RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
                        
    <PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
                        
    <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
                        
    <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
                        
    <AlternatingRowStyle BackColor="White" />
                         
    <Columns>
                             
    <asp:TemplateField HeaderText="操作"></asp:TemplateField>
                         
    </Columns>
                    
    </asp:GridView>
                    
    </td>
                
    </tr>
            
    </table>
        
    </div>
            
    <input id="hiddenId" style="display:none" type="text" runat="server" />
            
    <input id="hiddenName" style="display:none" type="text" runat="server" />
            
    <input id="hiddenAuthor" style="display:none" type="text" runat="server" />
            
    <input id="GVIndex" style="display:none" type="text" runat="server" />
            
    <asp:Button ID="bnUpdate" runat="server" style="display:none" Text="Update" OnClick="bnUpdate_Click" />
            
    <asp:Button ID="bnShowTextBox" runat="server" style="display:none" Text="ShowTextBox" OnClick="bnShowTextBox_Click" />
            
    <asp:Button ID="bnShowTextBox4New" runat="server" OnClick="bnShowTextBox4New_Click" Style="display:none" Text="ShowTextBox4New" />
            
    <asp:Button ID="bnCreateNew" runat="server" OnClick="bnCreateNew_Click" Style="display:none" Text="CreateNew" />
            
    <asp:Button ID="bnDelete" runat="server" OnClick="bnDelete_Click" Style="display:none" Text="Delete" />
        
    </form>
    </body>
    </html>

    Main.aspx.cs:

    using System;
    using System.Data;
    using System.Configuration;
    using System.Collections;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;

    public partial class Main : System.Web.UI.Page
    {
        
    protected void Page_Load(object sender, EventArgs e)
        
    {
            GVBind();
        }


        
    /// <summary>
        
    /// 绑定GridView数据源
        
    /// </summary>

        protected void GVBind()
        
    {
            
    if (CBook.GetData() != null)
            
    {
                gvBook.DataSource 
    = CBook.GetData();
                gvBook.DataBind();
            }

        }


        
    //向各行“操作”列写入“功能键”
        protected void gvBook_RowDataBound(object sender, GridViewRowEventArgs e)
        
    {
            
    if (e.Row.RowType == DataControlRowType.DataRow)
            
    {
                e.Row.Cells[
    0].Text = "<a href='JavaScript:ShowControl4New()'>新建</a>&nbsp;&nbsp;";
                e.Row.Cells[
    0].Text += "<a href='JavaScript:ShowTextBox(" + e.Row.RowIndex + ")'>修改</a>&nbsp;&nbsp;";
                e.Row.Cells[
    0].Text += "<a href='JavaScript:Delete(" + e.Row.Cells[1].Text + ")'>删除</a>";
            }

        }


        
    //显示用于修改的文本框
        protected void bnShowTextBox_Click(object sender, EventArgs e)
        
    {
            
    int index;
            
    if (Int32.TryParse(GVIndex.Value, out index))
            
    {
                gvBook.Rows[index].Cells[
    2].Text = "<input id='newName' type='text' value='" + gvBook.Rows[index].Cells[2].Text + "' />";
                gvBook.Rows[index].Cells[
    3].Text = "<input id='newAuthor' type='text' value='" + gvBook.Rows[index].Cells[3].Text + "' />";
                gvBook.Rows[index].Cells[
    0].Text = "<a href='JavaScript:Update(" + gvBook.Rows[index].Cells[1].Text + ")'>确定</a>";
            }

        }

        
        
    //执行修改
        protected void bnUpdate_Click(object sender, EventArgs e)
        
    {
            
    try
            
    {
                
    int id;
                
    if (Int32.TryParse(hiddenId.Value, out id) && hiddenName.Value != string.Empty && hiddenAuthor.Value != string.Empty)
                
    {
                    CBook.Update(id, hiddenName.Value, hiddenAuthor.Value);
                    CBook.ShowMessage(
    this"修改成功");
                    GVBind();
                }

                
    else
                
    {
                    CBook.ShowMessage(
    this"输入有误,请检查");
                }

            }

            
    catch (Exception ex)
            
    {
                CBook.ShowMessage(
    this, ex.Message);
            }

        }


        
    //显示用于创建的文本框及按钮
        protected void bnShowTextBox4New_Click(object sender, EventArgs e)
        
    {
            gvBook.FooterRow.Cells[
    0].Text = "请输入新记录信息:";
            gvBook.FooterRow.Cells[
    1].Text = "<input id='createNewName' type='text' size='15' />";
            gvBook.FooterRow.Cells[
    2].Text = "<input id='createNewAuthor' type='text'size='15' /> <input id='createNew' type='button' onclick='CreateNew()' value='确定' />";
        }


        
    //执行创建
        protected void bnCreateNew_Click(object sender, EventArgs e)
        
    {
            
    try
            
    {
                CBook.Insert(hiddenName.Value, hiddenAuthor.Value);
                CBook.ShowMessage(
    this"创建成功");
                GVBind();
            }

            
    catch(Exception ex)
            
    {
                CBook.ShowMessage(
    this, ex.Message);
            }

        }


        
    //执行删除
        protected void bnDelete_Click(object sender, EventArgs e)
        
    {
            
    try
            
    {
                
    int id;
                
    if (Int32.TryParse(hiddenId.Value, out id))
                
    {
                    CBook.Delete(id);
                    CBook.ShowMessage(
    this"删除成功");
                    GVBind();
                }

            }

            
    catch (Exception ex)
            
    {
                CBook.ShowMessage(
    this, ex.Message);
            }

        }


        
    //隐藏ID列
        protected void gvBook_RowCreated(object sender, GridViewRowEventArgs e)
        
    {
            
    if (e.Row.RowType == DataControlRowType.DataRow || e.Row.RowType == DataControlRowType.Header)
            
    {
                e.Row.Cells[
    1].Visible = false;
            }

        }

    }

    CBook.cs:

    using System;
    using System.Data;
    using System.Data.OleDb;
    using System.Configuration;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;

    /// <summary>
    /// Summary description for CBook
    /// </summary>

    public class CBook
    {
        
    /// <summary>
        
    /// DB连接字符串
        
    /// </summary>

        private static string connString = System.Configuration.ConfigurationManager.AppSettings["provider"].ToString() 
                                  
    + System.Web.HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["dbPath"]) + ";";
        
    public CBook()
        
    {
            
    //
            
    // TODO: Add constructor logic here
            
    //
        }


        
    /// <summary>
        
    /// Execute sql NonQuery(insert,delete,update)
        
    /// </summary>
        
    /// <param name="sql">sql</param>
        
    /// <param name="parameters">OleDbParameter数组</param>

        private static void ExeNonQuery(string sql, OleDbParameter[] parameters)
        
    {
            OleDbConnection conn 
    = new OleDbConnection(connString);
            
    try
            
    {
                conn.Open();

                OleDbCommand cmd 
    = new OleDbCommand(sql, conn);

                cmd.Parameters.AddRange(parameters);
                cmd.ExecuteNonQuery();
            }

            
    catch
            
    {
                
    throw;
            }

            
    finally
            
    {
                conn.Close();
            }

        }


        
    /// <summary>
        
    /// 修改
        
    /// </summary>

        public static void Update(int id, string bookName, string author)
        
    {
            
    string sql = "update tableBook set BookName=@bookName,BookAuthor=@author where ID=@id";

            OleDbParameter[] parameters 
    = new OleDbParameter[3];
            parameters[
    0= new OleDbParameter("@bookName", bookName);
            parameters[
    1= new OleDbParameter("@author", author);
            parameters[
    2= new OleDbParameter("@id", id);

            ExeNonQuery(sql, parameters);
        }


        
    /// <summary>
        
    /// 插入
        
    /// </summary>

        public static void Insert(string bookName, string author)
        
    {
            
    string sql = "insert into tableBook (bookName,BookAuthor)values(@bookName,@author)";

            OleDbParameter[] parameters 
    = new OleDbParameter[2];
            parameters[
    0= new OleDbParameter("@bookName", bookName);
            parameters[
    1= new OleDbParameter("@author", author);

            ExeNonQuery(sql, parameters);
        }


        
    /// <summary>
        
    /// 删除
        
    /// </summary>
        
    /// <param name="id"></param>

        public static void Delete(int id)
        
    {
            
    string sql = "delete from tableBook where ID=@id";
            OleDbParameter paraID 
    = new OleDbParameter("@id", id);

            ExeNonQuery(sql, 
    new OleDbParameter[] { paraID });
        }

        
    /// <summary>
        
    /// 返回DB中所有数据
        
    /// </summary>
        
    /// <returns></returns>

        public static DataTable GetData()
        
    {
            OleDbConnection conn 
    = new OleDbConnection(connString);
            
    try
            
    {
                conn.Open();
                
    string sql = "select * from tableBook";
                OleDbDataAdapter adapter 
    = new OleDbDataAdapter(sql, conn);
                DataSet ds 
    = new DataSet();
                adapter.Fill(ds, 
    "bookTable");
                DataTable dt 
    = ds.Tables[0];
                
    return dt;
            }

            
    catch
            
    {
                
    throw;
                
    return null;
            }

            
    finally
            
    {
                conn.Close();
            }

        }


        
    public static void ShowMessage(Page page, string msgInfo)
        
    {
            page.Response.Write(
    "<script>alert('" + msgInfo + "')</script>");
        }

    }

     
     
     
  • 相关阅读:
    Java第一次作业——Java语言基础
    P田日志<1>
    没解决的问题-git连接失败
    解决每次centos7执行java --version git --version等命令时都要重新source /etc/profile后才能执行,否则找不到命令-转载
    【Linux】VMware虚拟机中如何配置静态IP-转载
    Parallels Desktop 16 破解版 出现网络初始化失败和不能连接USB设备解决方法-转载
    Ubuntu安装git时出错,git-compat-util.h:280:25: fatal error: openssl/ssl.h: 没有那个文件或目录-转载
    遇到的问题29
    解决Idea 导入maven工程编译 Error running 'tms [clean]': Cannot run program "C:Program FilesJavajdk --转载
    jenkins执行shell命令时,提示“Command not found”处理方法-需要在jenkins调用shell脚本的最前面加一行脚本, #!/bin/bash -ilex-------转载
  • 原文地址:https://www.cnblogs.com/net2012/p/2878246.html
Copyright © 2011-2022 走看看