gridveiw操作大全

 

本文操作数据库使用的是OracleHelp类实现的。参见PetShop

1 gridview的绑定

调用如下:

            String ziDianMingChenSql = "select distinct 字典名称,字典编号,zidianmingcheng.SN from zidianmingcheng,xitongzidian where 模块类别= " + "'" + this.LabelLeiBei.Text + "' AND 可否编辑='是' ";
            ziDianMingChenGrid(ziDianMingChenSql);

    /// <summary>
    /// 填充GridView
    /// </summary>
    private void ziDianMingChenGrid(String querySql)
    {
        DataSet ds = new DataSet();
        ds = GetData(querySql);

        // 清空以前的数据源
        GridViewZiDianMingChen.DataSource = null;

        // 将ds作为信息栏GridView的数据源
        GridViewZiDianMingChen.DataSource = ds;

        // 绑定数据
        GridViewZiDianMingChen.DataBind();

        // 保存数据源 防止丢失 VS的破Bug
        ViewState["GridViewZiDianMingChen_DataSource"] = GridViewZiDianMingChen.DataSource;
        // 保存SQL语句
        ViewState["sqlGridViewZiDianMingChen"] = querySql;
    }

    /// <summary>
    /// 转换SQL查询结果为DataSet
    /// </summary>
    /// <returns>ds</returns>
    private DataSet GetData(String querySql)
    {
        String connStr = OracleHelper.DatabaseConnStr;

        // 创建数据集
        DataSet ds = OracleHelper.ExeSqlForDataSet(connStr, CommandType.Text, querySql, null);

        return ds;
    }

 

2   gridview 换行控制
        this.GridViewZiDianMingChen.Attributes.Add("style", "word-break:keep-all;word-wrap:normal");
        this.GridViewXinXiLan.Attributes.Add("style", "word-break:keep-all;word-wrap:normal");

 3  编辑

   /// <summary>
    /// 编辑
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void GridViewZiDianMingChen_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridViewZiDianMingChen.EditIndex = e.NewEditIndex;
        String querySql = "select distinct 字典名称,字典编号,zidianmingcheng.SN from zidianmingcheng,xitongzidian where 模块类别= " + "'" + this.LabelLeiBei.Text + "' AND 可否编辑='是' ";
        ziDianMingChenGrid(querySql);
    }

4 取消

    /// <summary>
    /// 取消
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void GridViewZiDianMingChen_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridViewZiDianMingChen.EditIndex = -1;
        String querySql = "select distinct 字典名称,字典编号,zidianmingcheng.SN from zidianmingcheng,xitongzidian where 模块类别= " + "'" + this.LabelLeiBei.Text + "' AND 可否编辑='是' ";
        ziDianMingChenGrid(querySql);
    }

5 更新   

    /// <summary>
    /// 更新
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void GridViewZiDianMingChen_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        string sn = GridViewZiDianMingChen.DataKeys[e.RowIndex].Values[0].ToString().Trim();
        String delXinWenSql = "UPDATE zidianmingcheng SET 字典名称 = '" + ((TextBox)(GridViewZiDianMingChen.Rows[e.RowIndex].Cells[1].Controls[0])).Text.ToString().Trim() + "' WHERE SN = '" + sn + "'";

        OracleConnection conn = new OracleConnection(OracleHelper.DatabaseConnStr);
        conn.Open();
        OracleTransaction trans = conn.BeginTransaction(IsolationLevel.ReadCommitted);

        try
        {
            OracleHelper.ExecuteNonQuery(trans, CommandType.Text, delXinWenSql, null);
            trans.Commit();
        }
        catch (Exception ex)
        {
            trans.Rollback();
            ex.ToString();
        }
        finally
        {
            conn.Close();
        }

        GridViewZiDianMingChen.EditIndex = -1;

        String querySql = "select distinct 字典名称,字典编号,zidianmingcheng.SN from zidianmingcheng,xitongzidian where 模块类别= " + "'" + this.LabelLeiBei.Text + "' AND 可否编辑='是' ";
        ziDianMingChenGrid(querySql);
    }

6 删除
    /// <summary>
    /// 删除字典项
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void GridViewXinXiLan_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        String sn = GridViewXinXiLan.DataKeys[e.RowIndex].Values[0].ToString().Trim();

        String delSql = "DELETE FROM xitongzidian WHERE SN = '" + sn + "'";

        OracleConnection conn = new OracleConnection(OracleHelper.DatabaseConnStr);
        conn.Open();
        OracleTransaction trans = conn.BeginTransaction(IsolationLevel.ReadCommitted);

        try
        {
            OracleHelper.ExecuteNonQuery(trans, CommandType.Text, delSql, null);
            trans.Commit();
        }
        catch (Exception ex)
        {
            trans.Rollback();
            ex.ToString();
        }
        finally
        {
            conn.Close();
        }

        GridViewXinXiLan.EditIndex = -1;
        String ziDianBianHao = this.GridViewZiDianMingChen.Rows[this.GridViewZiDianMingChen.SelectedRow.RowIndex].Cells[2].Text.ToString().Trim();
        String querySql = "SELECT 序号,名称,SN FROM xitongzidian WHERE ID='" + ziDianBianHao + "'";
        fillGridView(querySql);
    }

7 删除弹出对话框

    /// <summary>
    /// 实现删除弹出对话框
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void GridViewXinXiLan_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        //如果是绑定数据行
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate)
            {
                ((LinkButton)e.Row.Cells[4].Controls[0]).Attributes.Add("onclick", "javascript:return confirm('你确认要删除:\"" + e.Row.Cells[1].Text.Trim() + "\"吗?')");
            }
        }

    }

上面的代码如果一列中有2个控件会报错.用下面的即可.

        //如果是绑定数据行
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate)
            {
                //((LinkButton)e.Row.Cells[12].Controls[0]).Attributes.Add("onclick", "javascript:return confirm('你确认要删除:\"" + e.Row.Cells[1].Text.Trim() + "\"吗?')");
                ((LinkButton)e.Row.FindControl("LinkButton3")).Attributes.Add("onclick", "javascript:return confirm('你确认要删除:\"" + e.Row.Cells[1].Text.Trim() + "\"吗?')");
            }
        }

运行图如下:

gridveiw操作大全_第1张图片

图2: 点击选择按钮后显示另一个gridview。

gridveiw操作大全_第2张图片

3 编辑左边的gridview。可以设置字典编号为只读而使得其不可编辑

gridveiw操作大全_第3张图片

4 点击右边的删除按钮

gridveiw操作大全_第4张图片

5 点击右边的新增按钮

gridveiw操作大全_第5张图片

详细代码:

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

<!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="http://www.cnblogs.com/css/style.css" _fcksavedurl=""http://www.cnblogs.com/css/style.css"" _fcksavedurl=""http://www.cnblogs.com/css/style.css"" _fcksavedurl=""http://www.cnblogs.com/css/style.css"" _fcksavedurl=""http://www.cnblogs.com/css/style.css"" _fcksavedurl=""http://www.cnblogs.com/css/style.css"" _fcksavedurl=""http://www.cnblogs.com/css/style.css"" rel="stylesheet" type="text/css" />
</head>
<body>
    <form id="formDictSet" runat="server">
    <div>
        <table>
            <tr>
                <td>
                    <asp:Label ID="LabelDangQianZhuanTai" runat="server" Font-Size="10pt" Text="当前状态:"></asp:Label></td>
                <td>
                    &nbsp;<asp:Label ID="LabelMouKua" runat="server" Text="模块字典设置" ForeColor="#FF8000"></asp:Label></td>
            </tr>
        </table>
        <img alt="图象" height="5" src="http://www.cnblogs.com/Images/funcLine.JPG" width="933" /><br />
    <table>
    <tr>
    <td valign="top" >
        </td>
    <td valign="top" style="height: 168px">
    <asp:GridView ID="GridViewZiDianMingChen" runat="server" AutoGenerateColumns="False"
            CellPadding="4" ForeColor="#333333" GridLines="None" PageSize="1" EmptyDataText=" " OnRowCancelingEdit="GridViewZiDianMingChen_RowCancelingEdit" OnRowEditing="GridViewZiDianMingChen_RowEditing" OnRowUpdating="GridViewZiDianMingChen_RowUpdating" DataKeyNames="SN" OnSelectedIndexChanged="GridViewZiDianMingChen_SelectedIndexChanged1">
            <PagerSettings Visible="False" />
            <FooterStyle BackColor="#507CD1" Font-Bold="True" Font-Size="Small" ForeColor="White" />
            <Columns>
                <asp:TemplateField HeaderText="选择" ShowHeader="False">
                    <ItemStyle Wrap="False" HorizontalAlign="Center" />
                    <ItemTemplate>
                        <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Select"
                            Text="选择"></asp:LinkButton>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="字典名称" HeaderText="字典名称">
                    <ItemStyle Wrap="False" HorizontalAlign="Left" Width="132px" />
                </asp:BoundField>
                <asp:BoundField DataField="字典编号" HeaderText="字典编号" ReadOnly="True" >
                    <ItemStyle HorizontalAlign="Left" />
                </asp:BoundField>
                <asp:BoundField DataField="SN" HeaderText="SN" Visible="False" />
                <asp:CommandField CancelText="取消" DeleteText="删除" EditText="编辑" HeaderText="编辑" InsertText="插入"
                    NewText="新建" SelectText="选择" ShowEditButton="True" UpdateText="更新" >
                    <ItemStyle HorizontalAlign="Center" />
                </asp:CommandField>
            </Columns>
            <RowStyle BackColor="#EFF3FB" />
            <EditRowStyle BackColor="#2461BF" />
            <SelectedRowStyle BackColor="DodgerBlue" Font-Bold="False" ForeColor="#333333" />
            <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
            <HeaderStyle BackColor="#507CD1" Font-Bold="True" Font-Size="10pt" ForeColor="White" />
            <AlternatingRowStyle BackColor="White" />
        </asp:GridView>
    </td>
    <td style="height: 168px" valign="top">
     <asp:GridView ID="GridViewXinXiLan" runat="server" CellPadding="4"
            ForeColor="#333333" GridLines="None" AutoGenerateColumns="False" DataKeyNames="SN" Width="400px" OnRowCancelingEdit="GridViewXinXiLan_RowCancelingEdit" OnRowDeleting="GridViewXinXiLan_RowDeleting" OnRowEditing="GridViewXinXiLan_RowEditing" OnRowUpdating="GridViewXinXiLan_RowUpdating" OnRowDataBound="GridViewXinXiLan_RowDataBound">
            <PagerSettings Visible="False" />
            <FooterStyle BackColor="#507CD1" Font-Bold="True" Font-Size="Small" ForeColor="White" />
            <Columns>
                <asp:BoundField DataField="序号" HeaderText="序号" >
                    <ItemStyle HorizontalAlign="Left" Width="60px" Wrap="False" />
                </asp:BoundField>
                <asp:BoundField DataField="名称" HeaderText="名称" >
                    <ItemStyle HorizontalAlign="Left" Width="132px" Wrap="False" />
                </asp:BoundField>
                <asp:BoundField DataField="SN" HeaderText="SN" Visible="False" />
                <asp:CommandField CancelText="取消" DeleteText="删除" EditText="编辑" HeaderText="编辑" ShowEditButton="True"
                    UpdateText="更新" >
                    <ItemStyle HorizontalAlign="Center" Wrap="False" />
                </asp:CommandField>
                <asp:CommandField DeleteText="删除" HeaderText="删除" ShowDeleteButton="True" >
                    <ItemStyle HorizontalAlign="Center" Wrap="False" />
                </asp:CommandField>
            </Columns>
            <RowStyle BackColor="#EFF3FB" />
            <EditRowStyle BackColor="#2461BF" />
            <SelectedRowStyle BackColor="DodgerBlue" Font-Bold="False" ForeColor="#333333" />
            <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
            <HeaderStyle BackColor="#507CD1" Font-Bold="True" Font-Size="10pt" ForeColor="White" />
            <AlternatingRowStyle BackColor="White" />
        </asp:GridView>
        <asp:TextBox ID="TextBoxXuHao" runat="server" Visible="False" Width="60px"></asp:TextBox>
        <asp:TextBox ID="TextBoxMingCheng" runat="server" Visible="False"></asp:TextBox>
        <asp:Button ID="ButtonTianJia" runat="server" OnClick="ButtonTianJia_Click" Text="新增" Visible="False" />
        <asp:Button ID="ButtonBaoCun" runat="server" OnClick="ButtonBaoCun_Click" Text="保存"
            Visible="False" />
        <asp:Button ID="ButtonCancel" runat="server" OnClick="ButtonCancel_Click" Text="取消"
            Visible="False" /></td>
    </tr>
    </table>
        <img alt="图象" height="5" src="http://www.cnblogs.com/Images/funcLine.JPG" width="933" /><br />
        <br />

        <asp:Label ID="LabelLeiBei" runat="server" Text="1" Visible="False"></asp:Label>
        <br />
        <asp:Label ID="LabelZhuJian" runat="server" Text="隐藏主键" Visible="False"></asp:Label>
        </div>
    </form>
</body>
</html>

cs代码:

/*----------------------------------------------------------------
// Copyright (C) 2007
// 作者:马如林
// 时间:2007/06/03
// 文件名:
// 文件功能描述:
//                  系统字典管理页面
//                 
//
// 修改标识:
// 修改描述:
//
//----------------------------------------------------------------*/

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;

using System.Globalization;
using System.Data.OracleClient;
using System.IO;
using System.Text;

using Hhxx.App_Code.DatabaseOperate;
using Hhxx.App_Code.Database;
using Hhxx.App_Code.Common;


public partial class InterFace_SysDict_DictsSet : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            // 获取传送的第一个参数 用来表明是国内还是国外还是行业新闻 参见left.cs跳转页面
            String leiBei = Request.Params[0].ToString();
            switch (leiBei)
            {
                case "one": LabelLeiBei.Text = "1";
                    this.LabelMouKua.Text = "信息中心模块设置";
                    break;
                case "two": LabelLeiBei.Text = "2";
                    this.LabelMouKua.Text = "经营中心模块设置";
                    break;
                case "three": LabelLeiBei.Text = "3";
                    this.LabelMouKua.Text = "管理中心模块设置";
                    break;
                case "four": LabelLeiBei.Text = "4";
                    this.LabelMouKua.Text = "办公中心模块设置";
                    break;
                case "five": LabelLeiBei.Text = "5";
                    this.LabelMouKua.Text = "报表中心模块设置";
                    break;
                case "six": LabelLeiBei.Text = "6";
                    this.LabelMouKua.Text = "系统设置模块设置";
                    break;
                case "seven": LabelLeiBei.Text = "7";
                    this.LabelMouKua.Text = "便捷服务模块设置";
                    break;
                default: break;
            }

            String ziDianMingChenSql = "select distinct 字典名称,字典编号,zidianmingcheng.SN from zidianmingcheng,xitongzidian where 模块类别= " + "'" + this.LabelLeiBei.Text + "' AND 可否编辑='是' ";
            ziDianMingChenGrid(ziDianMingChenSql);

        }

        // gridview 换行控制
        this.GridViewZiDianMingChen.Attributes.Add("style", "word-break:keep-all;word-wrap:normal");
        this.GridViewXinXiLan.Attributes.Add("style", "word-break:keep-all;word-wrap:normal");
    }

    /// <summary>
    /// 填充GridView
    /// </summary>
    private void ziDianMingChenGrid(String querySql)
    {
        DataSet ds = new DataSet();
        ds = GetData(querySql);

        // 清空以前的数据源
        GridViewZiDianMingChen.DataSource = null;

        // 将ds作为信息栏GridView的数据源
        GridViewZiDianMingChen.DataSource = ds;

        // 绑定数据
        GridViewZiDianMingChen.DataBind();

        // 保存数据源 防止丢失 VS的破Bug
        ViewState["GridViewZiDianMingChen_DataSource"] = GridViewZiDianMingChen.DataSource;
        // 保存SQL语句
        ViewState["sqlGridViewZiDianMingChen"] = querySql;
    }


    /// <summary>
    /// 填充GridView
    /// </summary>
    private void fillGridView(String querySql)
    {
        DataSet ds = new DataSet();
        ds = GetData(querySql);

        // 清空以前的数据源
        GridViewXinXiLan.DataSource = null;

        // 将ds作为信息栏GridView的数据源
        GridViewXinXiLan.DataSource = ds;

        // 绑定数据
        GridViewXinXiLan.DataBind();

        // 保存数据源 防止丢失 VS的破Bug
        ViewState["GridViewXinXiLan_DataSource"] = GridViewXinXiLan.DataSource;
        // 保存SQL语句
        ViewState["sql"] = querySql;
    }

    /// <summary>
    /// 转换SQL查询结果为DataSet
    /// </summary>
    /// <returns>ds</returns>
    private DataSet GetData(String querySql)
    {
        String connStr = OracleHelper.DatabaseConnStr;

        // 创建数据集
        DataSet ds = OracleHelper.ExeSqlForDataSet(connStr, CommandType.Text, querySql, null);

        return ds;
    }

    /// <summary>
    /// 选择改变
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void GridViewZiDianMingChen_SelectedIndexChanged(object sender, EventArgs e)
    {
        // 字典编号
        String ziDianBianHao = this.GridViewZiDianMingChen.Rows[this.GridViewZiDianMingChen.SelectedRow.RowIndex].Cells[2].Text.ToString().Trim();
        // 初始化默认Gridview的SQL语句

        String querySql = "SELECT 序号,名称,SN FROM xitongzidian WHERE  ID='" + ziDianBianHao + "'";

        fillGridView(querySql);

    }

    /// <summary>
    /// 编辑
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void GridViewZiDianMingChen_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridViewZiDianMingChen.EditIndex = e.NewEditIndex;
        String querySql = "select distinct 字典名称,字典编号,zidianmingcheng.SN from zidianmingcheng,xitongzidian where 模块类别= " + "'" + this.LabelLeiBei.Text + "' AND 可否编辑='是' ";
        ziDianMingChenGrid(querySql);
    }

    /// <summary>
    /// 取消
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void GridViewZiDianMingChen_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridViewZiDianMingChen.EditIndex = -1;
        String querySql = "select distinct 字典名称,字典编号,zidianmingcheng.SN from zidianmingcheng,xitongzidian where 模块类别= " + "'" + this.LabelLeiBei.Text + "' AND 可否编辑='是' ";
        ziDianMingChenGrid(querySql);
    }

    /// <summary>
    /// 更新
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void GridViewZiDianMingChen_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        string sn = GridViewZiDianMingChen.DataKeys[e.RowIndex].Values[0].ToString().Trim();
        String delXinWenSql = "UPDATE zidianmingcheng SET 字典名称 = '" + ((TextBox)(GridViewZiDianMingChen.Rows[e.RowIndex].Cells[1].Controls[0])).Text.ToString().Trim() + "' WHERE SN = '" + sn + "'";

        OracleConnection conn = new OracleConnection(OracleHelper.DatabaseConnStr);
        conn.Open();
        OracleTransaction trans = conn.BeginTransaction(IsolationLevel.ReadCommitted);

        try
        {
            OracleHelper.ExecuteNonQuery(trans, CommandType.Text, delXinWenSql, null);
            trans.Commit();
        }
        catch (Exception ex)
        {
            trans.Rollback();
            ex.ToString();
        }
        finally
        {
            conn.Close();
        }

        GridViewZiDianMingChen.EditIndex = -1;

        String querySql = "select distinct 字典名称,字典编号,zidianmingcheng.SN from zidianmingcheng,xitongzidian where 模块类别= " + "'" + this.LabelLeiBei.Text + "' AND 可否编辑='是' ";
        ziDianMingChenGrid(querySql);
    }

    /// <summary>
    /// 选择改变
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void GridViewZiDianMingChen_SelectedIndexChanged1(object sender, EventArgs e)
    {
        String ziDianBianHao = this.GridViewZiDianMingChen.Rows[this.GridViewZiDianMingChen.SelectedRow.RowIndex].Cells[2].Text.ToString().Trim();
        // 初始化默认Gridview的SQL语句

        String querySql = "SELECT 序号,名称,SN FROM xitongzidian WHERE  ID='" + ziDianBianHao + "'";

        fillGridView(querySql);

        ButtonTianJia.Visible = true;
        ButtonTianJia.Enabled = true;
    }

    /// <summary>
    /// 字典更新
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void GridViewXinXiLan_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        string sn = GridViewXinXiLan.DataKeys[e.RowIndex].Values[0].ToString().Trim();
        String updateSql = "UPDATE xitongzidian SET 序号='" + ((TextBox)(GridViewXinXiLan.Rows[e.RowIndex].Cells[0].Controls[0])).Text.ToString().Trim()
                               + "', 名称 = '" + ((TextBox)(GridViewXinXiLan.Rows[e.RowIndex].Cells[1].Controls[0])).Text.ToString().Trim()
                               + "' WHERE SN = '" + sn + "'";

        OracleConnection conn = new OracleConnection(OracleHelper.DatabaseConnStr);
        conn.Open();
        OracleTransaction trans = conn.BeginTransaction(IsolationLevel.ReadCommitted);

        try
        {
            OracleHelper.ExecuteNonQuery(trans, CommandType.Text, updateSql, null);
            trans.Commit();
        }
        catch (Exception ex)
        {
            trans.Rollback();
            ex.ToString();
        }
        finally
        {
            conn.Close();
        }

        GridViewXinXiLan.EditIndex = -1;
        String ziDianBianHao = this.GridViewZiDianMingChen.Rows[this.GridViewZiDianMingChen.SelectedRow.RowIndex].Cells[2].Text.ToString().Trim();
        String querySql = "SELECT 序号,名称,SN FROM xitongzidian WHERE ID='" + ziDianBianHao + "'";
        fillGridView(querySql);
    }

    /// <summary>
    /// 删除字典项
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void GridViewXinXiLan_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        String sn = GridViewXinXiLan.DataKeys[e.RowIndex].Values[0].ToString().Trim();

        String delSql = "DELETE FROM xitongzidian WHERE SN = '" + sn + "'";

        OracleConnection conn = new OracleConnection(OracleHelper.DatabaseConnStr);
        conn.Open();
        OracleTransaction trans = conn.BeginTransaction(IsolationLevel.ReadCommitted);

        try
        {
            OracleHelper.ExecuteNonQuery(trans, CommandType.Text, delSql, null);
            trans.Commit();
        }
        catch (Exception ex)
        {
            trans.Rollback();
            ex.ToString();
        }
        finally
        {
            conn.Close();
        }

        GridViewXinXiLan.EditIndex = -1;
        String ziDianBianHao = this.GridViewZiDianMingChen.Rows[this.GridViewZiDianMingChen.SelectedRow.RowIndex].Cells[2].Text.ToString().Trim();
        String querySql = "SELECT 序号,名称,SN FROM xitongzidian WHERE ID='" + ziDianBianHao + "'";
        fillGridView(querySql);
    }

    /// <summary>
    /// 编辑
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void GridViewXinXiLan_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridViewXinXiLan.EditIndex = e.NewEditIndex;
        String ziDianBianHao = this.GridViewZiDianMingChen.Rows[this.GridViewZiDianMingChen.SelectedRow.RowIndex].Cells[2].Text.ToString().Trim();
        String querySql = "SELECT 序号,名称,SN FROM xitongzidian WHERE ID='" + ziDianBianHao + "'";
        fillGridView(querySql);
    }

    /// <summary>
    /// 取消
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void GridViewXinXiLan_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridViewXinXiLan.EditIndex = -1;
        String ziDianBianHao = this.GridViewZiDianMingChen.Rows[this.GridViewZiDianMingChen.SelectedRow.RowIndex].Cells[2].Text.ToString().Trim();
        String querySql = "SELECT 序号,名称,SN FROM xitongzidian WHERE ID='" + ziDianBianHao + "'";
        fillGridView(querySql);
    }

    /// <summary>
    /// 新增
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void ButtonTianJia_Click(object sender, EventArgs e)
    {
        TextBoxXuHao.Text = "0";
        TextBoxXuHao.Visible = true;
        TextBoxMingCheng.Text = "请输入";
        TextBoxMingCheng.Visible = true;
        ButtonBaoCun.Enabled = true;
        ButtonBaoCun.Visible = true;
        ButtonCancel.Enabled = true;
        ButtonCancel.Visible = true;
        ButtonTianJia.Enabled = false;
        ButtonTianJia.Visible = false;
    }

    /// <summary>
    /// 保存
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void ButtonBaoCun_Click(object sender, EventArgs e)
    {


        String insertSql = "INSERT INTO xitongzidian(序号,名称,ID,SN) VALUES(:xh,:mc,:id,:sn) ";
        OracleParameter[] parms = {
                new OracleParameter(":xh", OracleType.Number, 8),
                new OracleParameter(":mc", OracleType.Char, 30),
                new OracleParameter(":id", OracleType.Char, 10),
                new OracleParameter(":sn", OracleType.Char, 32)
                };

        parms[0].Value = TextBoxXuHao.Text.Trim();
        parms[1].Value = TextBoxMingCheng.Text.Trim();
        parms[2].Value = this.GridViewZiDianMingChen.Rows[this.GridViewZiDianMingChen.SelectedRow.RowIndex].Cells[2].Text.ToString().Trim();
        parms[3].Value = System.Guid.NewGuid().ToString().Replace("-", "");

        OracleConnection conn = new OracleConnection(OracleHelper.DatabaseConnStr);
        conn.Open();
        OracleTransaction trans = conn.BeginTransaction(IsolationLevel.ReadCommitted);

        try
        {
            OracleHelper.ExecuteNonQuery(trans, CommandType.Text, insertSql, parms);
            trans.Commit();
        }
        catch (Exception ex)
        {
            trans.Rollback();
            ex.ToString();
        }
        finally
        {
            conn.Close();
        }
        String ziDianBianHao = this.GridViewZiDianMingChen.Rows[this.GridViewZiDianMingChen.SelectedRow.RowIndex].Cells[2].Text.ToString().Trim();
        String querySql = "SELECT 序号,名称,SN FROM xitongzidian WHERE ID='" + ziDianBianHao + "'";
        fillGridView(querySql);

        TextBoxXuHao.Text = "0";
        TextBoxXuHao.Visible = false;
        TextBoxMingCheng.Text = "请输入";
        TextBoxMingCheng.Visible = false;

        ButtonBaoCun.Enabled = false;
        ButtonBaoCun.Visible = false;
        ButtonCancel.Enabled = false;
        ButtonCancel.Visible = false;
        ButtonTianJia.Enabled = true;
        ButtonTianJia.Visible = true;
    }

    /// <summary>
    /// 取消
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void ButtonCancel_Click(object sender, EventArgs e)
    {
        TextBoxXuHao.Text = "0";
        TextBoxXuHao.Visible = false;
        TextBoxMingCheng.Text = "请输入";
        TextBoxMingCheng.Visible = false;

        ButtonBaoCun.Enabled = false;
        ButtonBaoCun.Visible = false;
        ButtonCancel.Enabled = false;
        ButtonCancel.Visible = false;
        ButtonTianJia.Enabled = true;
        ButtonTianJia.Visible = true;
    }

    /// <summary>
    /// 实现删除弹出对话框
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void GridViewXinXiLan_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        //如果是绑定数据行
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate)
            {
                ((LinkButton)e.Row.Cells[4].Controls[0]).Attributes.Add("onclick", "javascript:return confirm('你确认要删除:\"" + e.Row.Cells[1].Text.Trim() + "\"吗?')");
            }
        }

    }
}

 

 

6 gridview移动框

<div style="overflow: scroll; height: 300px">

 <asp:GridView ID="GridViewZiDianMingChen" runat="server" AutoGenerateColumns="False"
            CellPadding="4" ForeColor="#333333" PageSize="1" EmptyDataText=" " OnRowCancelingEdit="GridViewZiDianMingChen_RowCancelingEdit" OnRowEditing="GridViewZiDianMingChen_RowEditing" OnRowUpdating="GridViewZiDianMingChen_RowUpdating" DataKeyNames="SN" OnSelectedIndexChanged="GridViewZiDianMingChen_SelectedIndexChanged1" Height="5px">
            .........
</asp:GridView>
</div>

效果图:(其中的GirdLines设置为Both)好象好看点.

gridveiw操作大全_第6张图片
7 空数据时显示表头

         <EmptyDataTemplate>
             序号 名称
         </EmptyDataTemplate>

gridveiw操作大全_第7张图片

8 添加一行空行

        DataTable dt = new DataTable();
        DataRow row = dt.NewRow();
        dt.Columns.Add("建立日期", typeof(string));
        dt.Columns.Add("姓名", typeof(string));
        dt.Columns.Add("类型", typeof(string));
        dt.Columns.Add("名称", typeof(string));
        dt.Columns.Add("开始时间", typeof(string));
        dt.Columns.Add("结束时间", typeof(string));
        dt.Columns.Add("取得证书", typeof(string));
        dt.Columns.Add("备注", typeof(string));
        dt.Columns.Add("经办人", typeof(string));
        dt.Columns.Add("SN", typeof(string));
        row[0] = "2006-6-18";
        row[1] = "张三";
        row[2] = "培训";
        row[3] = "干部培训";
        row[4] = "2006-6-18";
        row[5] = "2006-6-18";
        row[6] = "资格证书";
        row[7] = "无";
        row[8] = "王二";
        row[9] = "234234234";
        dt.Rows.Add(row);
 
        // 清空以前的数据源
        GridViewTianJia.DataSource = null;

        // 将ds作为信息栏GridView的数据源
        GridViewTianJia.DataSource = dt;

        // 绑定数据
        GridViewTianJia.DataBind();

本来有个更好的,不知道怎么写了现在 郁闷!

9 隐藏一列

      GridViewTianJia.Columns[10].Visible = false;

10 隐藏单元
      GridViewTianJia.Rows[0].Cells[10].Visible = false;

11 与dropdownlist的结合

.aspx

                             < asp:TemplateField  HeaderText ="类型" >
                                
< EditItemTemplate >
                                    
< asp:TextBox  ID ="TextBox1"  runat ="server"  Text ='<%#  Bind("类型") % > '> </ asp:TextBox >
                                
</ EditItemTemplate >
                                
< ItemStyle  Wrap ="False"   />
                                
< ItemTemplate >
                                    
< asp:HiddenField  ID ="HDLeiXing"  runat ="server"  Value ='<%#  Eval("类型") % > ' />
                                    
< asp:DropDownList  ID ="DropDownListLeiXing"  runat ="server" >
                                    
</ asp:DropDownList >
                                
</ ItemTemplate >
                            
</ asp:TemplateField >

.cs

     /// <summary>
    
/// 数据绑定
    
/// </summary>
    
/// <param name="sender"></param>
    
/// <param name="e"></param>

     protected   void  GridViewTianJia_RowDataBound( object  sender, GridViewRowEventArgs e)
    
{
        
//为DropDownList绑定值
        if (((DropDownList)e.Row.FindControl("DropDownListLeiXing")) != null)
        
{
            DropDownList ddlXL 
= (DropDownList)e.Row.FindControl("DropDownListLeiXing");
            
//ddlXL.Items.Clear();
            
//ddlXL.Items.Add("培训");
            
//ddlXL.Items.Add("进修");
            
// 奖惩类型
            String conn = OracleHelper.DatabaseConnStr;
            ddlXL.Items.Clear();
            String queryLeiXing 
= "SELECT 名称 FROM XITONGZIDIAN WHERE ID='03010301' ORDER BY 序号";
            OracleDataReader drLeiXing 
= OracleHelper.ExecuteReader(conn, CommandType.Text, queryLeiXing, null);
            
while (drLeiXing.Read())
            
{
                ddlXL.Items.Add(drLeiXing.GetString(
0).Trim());
            }

            drLeiXing.Close();

            
//ddlXL.SelectedValue = ((HiddenField)e.Row.FindControl("HDLeiXing")).Value.ToString().Trim();
            ddlXL.Items.Remove(((HiddenField)e.Row.FindControl("HDLeiXing")).Value.ToString().Trim());
            ddlXL.Items.Insert(
0, ((HiddenField)e.Row.FindControl("HDLeiXing")).Value.ToString().Trim());
        }

    }

运行显示:

gridveiw操作大全_第8张图片

12

gridveiw操作大全_第9张图片

  < asp:TemplateField HeaderText = " 编辑 "  ShowHeader = " False " >
                                
< EditItemTemplate >
                                    
< asp:LinkButton ID = " LinkButton1 "  runat = " server "  CausesValidation = " True "  CommandName = " Update "
                                        Text
= " 更新 " ></ asp:LinkButton >
                                    
< asp:LinkButton ID = " LinkButton2 "  runat = " server "  CausesValidation = " False "  CommandName = " Cancel "
                                        Text
= " 取消 " ></ asp:LinkButton >
                                
</ EditItemTemplate >
                                
< ItemStyle Wrap = " False "   />
                                
< ItemTemplate >
                                    
< asp:LinkButton ID = " LinkButton1 "  runat = " server "  CausesValidation = " False "  CommandName = " Edit "
                                        Text
= " 编辑 " ></ asp:LinkButton >& nbsp;
                                
</ ItemTemplate >
                            
</ asp:TemplateField >
                            
< asp:TemplateField HeaderText = " 操作 "  ShowHeader = " False " >
                                
< ItemStyle Wrap = " False "   />
                                
< ItemTemplate >
                                    
< asp:LinkButton ID = " LinkButton3 "  runat = " server "  CausesValidation = " False "  CommandName = " Delete "
                                        Text
= " 删除 " ></ asp:LinkButton >
                                    
< asp:LinkButton ID = " LinkButtonTianJia "  runat = " server "  Visible = " False "  OnClick = " LinkButtonTianJia_Click " > 添加保存 </ asp:LinkButton >
                                    
< asp:LinkButton ID = " LinkButtonQuXiao "  runat = " server "  OnClick = " LinkButtonQuXiao_Click "
                                        Visible
= " False " > 取消 </ asp:LinkButton >
                                
</ ItemTemplate >
                            
</ asp:TemplateField >

gridveiw操作大全_第10张图片

 

                                <EditItemTemplate>
                                    <asp:TextBox ID="TextBoxKaiShiShiJian" runat="server" Text='<%# Bind("开始时间") %>' Width="70" CausesValidation="True" ValidationGroup="vgpKaiShiShiJian"></asp:TextBox>
                                    <asp:RequiredFieldValidator ID="reqFromDate" runat="server" ControlToValidate="TextBoxKaiShiShiJian" ErrorMessage="请输入开始时间" ValidationGroup="vgpKaiShiShiJian" Display="Dynamic"  />
                                    <asp:CustomValidator ID="CVKaiShiShiJian" runat="server" ErrorMessage="日期格式错误()" ControlToValidate="TextBoxKaiShiShiJian" Display="Dynamic" OnServerValidate="CVKaiShiShiJian_ServerValidate"></asp:CustomValidator>
                                </EditItemTemplate>
 


    /// <summary>
    /// 时间格式验证
    /// </summary>
    /// <param name="source"></param>
    /// <param name="args"></param>
    protected void CVKaiShiShiJian_ServerValidate(object source, ServerValidateEventArgs args)
    {
        try
        {
            int num = Int32.Parse(args.Value);
            if (num % 2 == 0)
            {
                args.IsValid = true;
                return;
            }
        }
        catch (Exception) { }
        args.IsValid = false;
    }

        if (Page.IsValid)
        {
            ////

        }

gridveiw操作大全_第11张图片

 
 

Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=1767322

你可能感兴趣的:(grid)