• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

024. asp.net中第一次使用GridView (设置鼠标经过时更换背景色)

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

1. 前端HTML代码

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

<!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>
</head>
<body class="Font">
    <form id="form1" runat="server">
    <div style="text-align: left" align="left"><asp:Panel ID="Panel2" runat="server">
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowDataBound="GridView1_RowDataBound" OnSelectedIndexChanging="GridView1_SelectedIndexChanging" Font-Size="9pt" AllowPaging="True" EmptyDataText="没有相关数据可以显示!" OnPageIndexChanging="GridView1_PageIndexChanging" CellPadding="4" ForeColor="#333333" GridLines="None">
                <Columns>
                     <asp:TemplateField>
                                <ItemTemplate>
                                    <asp:CheckBox ID="cbSingleOrMore" runat="server" />
                                </ItemTemplate>
                      </asp:TemplateField>
                    <asp:BoundField DataField="cardNo" HeaderText="卡号" />
                    <asp:BoundField DataField="cardBound" HeaderText="内卡号" />
                    <asp:BoundField DataField="name" HeaderText="会员姓名" />
                    <asp:BoundField DataField="type" HeaderText="类型" />
                    <asp:BoundField DataField="createTime"  HeaderText="创建时间" DataFormatString="{0:d}" />
                    <asp:BoundField DataField="stateBit" HeaderText="生效否" />
                    <asp:BoundField DataField="mobileID" HeaderText="机器码" />
                </Columns>
                <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
                <RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
                <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
                <PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Right" />
                <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
                <AlternatingRowStyle BackColor="White" />
            </asp:GridView>
        </asp:Panel>
                    <asp:CheckBox ID="cbAll" runat="server" AutoPostBack="True" 
            Font-Size="9pt" OnCheckedChanged="cbAll_CheckedChanged"
                        Text="全选/反选" />
                    <asp:Button ID="btnDeleteMore" runat="server" Font-Size="9pt" 
            Text="部分删除或全部删除" OnClick="btnDeleteMore_Click" onload="btnDeleteMore_Load" 
            Width="134px" />
                    <asp:Button ID="btnRre" runat="server" Font-Size="9pt" Text="取消部分或全部选择" 
            OnClick="btnRre_Click" Width="126px" />
        <asp:Button ID="btnUpdateTime" runat="server" onclick="btnUpdateTime_Click" 
            Text="更新发布时间" />
            
    </div>
    </form>
</body>
</html>

2. 后台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;
using System.Data.SqlClient;


public partial class Index : System.Web.UI.Page
{
    SqlConnection sqlcon;
    string strCon = "server=.;database=TYW;uid=sa;pwd=123.456;";
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            this.GV_DataBind();
        }

    }
    public void GV_DataBind()
    {
        string sqlstr = "select * from card ";
        sqlcon = new SqlConnection(strCon);
        SqlDataAdapter da = new SqlDataAdapter(sqlstr, sqlcon);
        DataSet ds = new DataSet();
        sqlcon.Open();
        da.Fill(ds, "card");
        sqlcon.Close();
        this.GridView1.DataSource = ds;
        
        //设置主键列, 作为后续操作(删除/更新/修改/查询)的重要依据, 可设置多列
        this.GridView1.DataKeyNames = new string[] { "cardNo" };
this.GridView1.DataBind();
        /*模拟GridView1.rows.count不大于0
        this.GridView1.DataSource = null;
        this.GridView1.DataBind();*/
        if (GridView1.Rows.Count > 0)
        {
            return;//有数据,不要处理
        }
        else//显示表头并显示没有数据的提示信息
        {
            StrHelper.GridViewHeader(GridView1);
        }
    }
    /*在创建gridView控件时,必须先为GridView的每一行创建一个GridViewRow对象,创建每一行时,将引发一个RowCreated事件;当行创建完毕,每一行GridViewRow就要绑定数据源中的数据,当绑定完成后,将引发RowDataBound事件.可以利用RowCreated事件来控制每一行绑定的控件,利用RowDataBound事件来控制每一行绑定的数据,也就是让数据如何呈现*/
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        //当鼠标经过时更换行的背景色
        if (e.Row.RowType == DataControlRowType.DataRow)//判定当前的行是否属于datarow类型的行
        {
            //当鼠标放上去的时候 先保存当前行的背景颜色 并给附一颜色
            e.Row.Attributes.Add("onmouseover", "currentcolor=this.style.backgroundColor;this.style.backgroundColor='#7f9edb',this.style.fontWeight='';");
            //当鼠标离开的时候 将背景颜色还原的以前的颜色
            e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=currentcolor,this.style.fontWeight='';");
        }
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            string gIntro = e.Row.Cells[4].Text;
            e.Row.Cells[4].Text = StrHelper.GetFirstString(gIntro, 12);//如果字符串太长使用. . . 代替
        }
       
                //内容提示为GridView第二行数据显示的内容,其索引值为1(注意:.NET中索引值都是从0开始)
                //((LinkButton)e.Row.Cells[8].Controls[0]).Attributes.Add("onclick", "javascript:return confirm('确认要删除信息主题:\"" + e.Row.Cells[1].Text + "\"吗?')");
    }

    /*SelectedIndexChanging 发生在单击某一行的“选择”按钮以后,GridView 控件对相应的选择操作进行处理之前。*/
    protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
    {
        string id = this.GridView1.DataKeys[e.NewSelectedIndex].Value.ToString();
        sqlcon = new SqlConnection(strCon);
        SqlCommand com = new SqlCommand("select [check] from card where cardNo='" + id + "'", sqlcon);
        sqlcon.Open();
        string count = Convert.ToString(com.ExecuteScalar());
        if (count == "False")
        {
            count = "1";
        }
        else
        {
            count = "0";
        }
        com.CommandText = "update card set [check]=" + count + " where cardNo=" + id;
        com.ExecuteNonQuery();
        sqlcon.Close();
        this.GV_DataBind();
    }
    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        this.GridView1.PageIndex = e.NewPageIndex;
        this.GV_DataBind();
    }

    //更改Checked
    protected void cbAll_CheckedChanged(object sender, EventArgs e)
    {
        for (int i = 0; i <= GridView1.Rows.Count - 1; i++)
        {
            CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("cbSingleOrMore");
            if (cbAll.Checked == true)
            {
                cbox.Checked = true;
            }
            else
            {
                cbox.Checked = false;
            }
        }
    }

    //执行删除操作
    protected void btnDeleteMore_Click(object sender, EventArgs e)
    {
        sqlcon = new SqlConnection(strCon);//创建数据库连接
        SqlCommand sqlcom;//创建命令对象变量
        for (int i = 0; i <= GridView1.Rows.Count - 1; i++)//循环遍历GridView控件每一项
        {
            CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("cbSingleOrMore");//查找嵌套在GridView控件中的单选框
            if (cbox.Checked == true)//如果操作为选中状态
            {
                string strSql = "delete from card where cardNo=@id";//定义带参数的删除语句
                if (sqlcon.State.Equals(ConnectionState.Closed))
                    sqlcon.Open();//打开数据加连接
                sqlcom = new SqlCommand(strSql, sqlcon);//创建执行删除操作的命令对象
                SqlTransaction tran = sqlcon.BeginTransaction();//实例化事务对象
                sqlcom.Transaction = tran;//将事务对象与命令对象关联
                SqlParameter prame = new SqlParameter("@id", SqlDbType.VarChar, 8);//定义参数
                sqlcom.Parameters.Add(prame);//添加参数
                sqlcom.Parameters["@id"].Value = GridView1.DataKeys[i].Value.ToString();//参数赋值
                try
                {
                    sqlcom.ExecuteNonQuery();//执行SQL语句
                    tran.Commit();//提交事务
                }
                catch (SqlException ex)
                {
                    StrHelper.Alert(string.Format("SQL语句发生了异常,异常如下所示:\n{0}", ex.Message));
                    tran.Rollback();//事务回滚
                }
                finally
                {
                    sqlcon.Close();//关闭数据库连接
                }
            }
        }
        GV_DataBind();//重新绑定数据控件
    }
    protected void btnRre_Click(object sender, EventArgs e)
    {
        cbAll.Checked = false;
        for (int i = 0; i <= GridView1.Rows.Count - 1; i++)
        {
            CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("cbSingleOrMore");
            cbox.Checked = false;
        }
    }
    
    protected void btnDeleteMore_Load(object sender, EventArgs e)
    {
        //删除前进行提醒
        ((Button)sender).Attributes["onclick"] = "return confirm('您确定要删除吗?')";
    }

    //更新时间
    protected void btnUpdateTime_Click(object sender, EventArgs e)
    {
        sqlcon = new SqlConnection(strCon);//创建数据库连接
        SqlCommand sqlcom;//创建命令对象变量
        for (int i = 0; i <= GridView1.Rows.Count - 1; i++)//循环遍历GridView控件每一项
        {
            CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("cbSingleOrMore");
            if (cbox.Checked == true)
            {
                string strSql = "Update card set createTime=@UpdateTime where cardNo=@id";
                if (sqlcon.State.Equals(ConnectionState.Closed))
                    sqlcon.Open();//打开数据库连接
                sqlcom = new SqlCommand(strSql, sqlcon);
                SqlParameter[] prams = {new SqlParameter("@UpdateTime",SqlDbType.DateTime), new SqlParameter("@id",SqlDbType.VarChar,32)};
                prams[0].Value = DateTime.Now;
                prams[1].Value = GridView1.DataKeys[i].Value;
                foreach (SqlParameter parameter in prams)
                {
                    sqlcom.Parameters.Add(parameter);
                }
                if (sqlcom.ExecuteNonQuery() > 0)
                {
                    StrHelper.Alert("更新成功!");
                }
                else
                {
                    StrHelper.Alert("更新失败!");
                }
                sqlcon.Close();
            }
        }
        GV_DataBind();
    }
}

3. 工具类StrHelper代码:

  1 using System;
  2 using System.Data;
  3 using System.Configuration;
  4 using System.Linq;
  5 using System.Web;
  6 using System.Web.Security;
  7 using System.Web.UI;
  8 using System.Web.UI.HtmlControls;
  9 using System.Web.UI.WebControls;
 10 using System.Web.UI.WebControls.WebParts;
 11 using System.Xml.Linq;
 12 //引入如下命名空间
 13 using System.Text.RegularExpressions;
 14 using System.Text;
 15 
 16 /// <summary>
 17 ///StrHelper 的摘要说明
 18 /// </summary>
 19 public class StrHelper
 20 {
 21     public StrHelper(){}
 22     /// <summary>
 23     /// 截取字符串函数
 24     /// </summary>
 25     /// <param name="str">所要截取的字符串</param>
 26     /// <param name="num">截取字符串的长度</param>
 27     /// <returns></returns>
 28     static public string GetSubString(string str, int num)
 29     {
 30         #region
 31         return (str.Length > num) ? str.Substring(0, num) + "..." : str;
 32         #endregion
 33     }
 34     /// <summary>
 35     /// 截取字符串优化版
 36     /// </summary>
 37     /// <param name="stringToSub">所要截取的字符串</param>
 38     /// <param name="length">截取字符串的长度</param>
 39     /// <returns></returns>
 40     public static string GetFirstString(string stringToSub, int length)
 41     {
 42         #region
 43         Regex regex = new Regex("[\u4e00-\u9fa5]+", RegexOptions.Compiled);
 44         char[] stringChar = stringToSub.ToCharArray();
 45         StringBuilder sb = new StringBuilder();
 46         int nLength = 0;
 47         bool isCut = false;
 48         for (int i = 0; i < stringChar.Length; i++)
 49         {
 50             if (regex.IsMatch((stringChar[i]).ToString()))//regex.IsMatch指示正则表达式在输入字符串中是否找到匹配项
 51             {
 52                 sb.Append(stringChar[i]);//将信息追加到当前 StringBuilder 的结尾
 53                 nLength += 2;
 54             }
 55             else
 56             {
 57                 sb.Append(stringChar[i]);
 58                 nLength = nLength + 1;
 59             }
 60             if (nLength > length)//替换字符串
 61             {
 62                 isCut = true;
 63                 break;
 64             }
 65         }
 66         if (isCut)
 67             return sb.ToString() + "...";
 68         else
 69             return sb.ToString();
 70         #endregion
 71     }
 72     /// 弹出JavaScript小窗口
 73     /// </summary>
 74     /// <param name="js">窗口信息</param>
 75     public static void Alert(string message)
 76     {
 77         #region
 78         string js = @"<Script language='JavaScript'>
 79                     alert('" + message + "');</Script>";
 80         HttpContext.Current.Response.Write(js);
 81 
 82         #endregion
 83     }
 84     public static void GridViewHeader(GridView gdv)//显示表头并显示没有数据的提示信息
 85     {
 86         //表头的设置. 注意在呈现 GridView 控件之前,必须先为该控件中的每一行创建一个 GridViewRow 对象。
 87         // 参数:-1  rowIndex:行号; -1  这个参数0也可以,-1 也可以,可能ASP.NET Framework并未用到此值,所以DataControlRowType枚举为Header,Footer都將此值設為-1; DataControlRowType 一个枚举, 枚举该行是数据行/导航行/分割行等; DataControlRowState枚举, 指示该行的状态可用值有正常状态/选定状态/编辑状态/新插入状态
 88         GridViewRow row = new GridViewRow(-1, -1, DataControlRowType.EmptyDataRow, DataControlRowState.Normal);
 89         foreach (DataControlField field in gdv.Columns) //本来有7列, 加上checkbox有8列
 90         {
 91             TableCell cell = new TableCell();
 92             cell.Text = field.HeaderText;
 93             cell.Width = field.HeaderStyle.Width;
 94             cell.Height = field.HeaderStyle.Height;
 95             cell.ForeColor = field.HeaderStyle.ForeColor;
 96             cell.Font.Size = field.HeaderStyle.Font.Size;
 97             cell.Font.Bold = field.HeaderStyle.Font.Bold;
 98             cell.Font.Name = field.HeaderStyle.Font.Name;
 99             cell.Font.Strikeout = field.HeaderStyle.Font.Strikeout;
100             cell.Font.Underline = field.HeaderStyle.Font.Underline;
101             cell.BackColor = field.HeaderStyle.BackColor;
102             cell.VerticalAlign = field.HeaderStyle.VerticalAlign;
103             cell.HorizontalAlign = field.HeaderStyle.HorizontalAlign;
104             cell.CssClass = field.HeaderStyle.CssClass;
105             cell.BorderColor = field.HeaderStyle.BorderColor;
106             cell.BorderStyle = 
                       
                    
                    

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
FineUI开源版(ASP.Net)初学手册-部分JS整理发布时间:2022-07-10
下一篇:
asp.net的生成曲线图(1)发布时间:2022-07-10
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap