DevExpress ASP.NET 使用经验谈(8)-ASPxGridView自定义列和基本事件

为演示本节示例,我们在原来Users表增加【性别Gender】、【兴趣爱好Hobbies】,【CreateTime创建时间】,【ModifyTime】修改时间这4个字段,

ALTER TABLE [dbo].[Users] add [Gender] varchar(10) NULL
GO
ALTER TABLE [dbo].[Users] add [Hobbies] varchar(50) NULL
GO
ALTER TABLE [dbo].[Users] add [CreateTime] datetime NULL
GO
ALTER TABLE [dbo].[Users] add [ModifyTime] datetime NULL

完成建表语句如下:

CREATE TABLE [dbo].[Users] ( 
    [UserID] int IDENTITY(1, 1) NOT NULL, 
    [UserName] nvarchar(50) NULL, 
    [FirstName] nvarchar(50) NULL, 
    [LastName] nvarchar(50) NULL, 
    [MiddleName] nvarchar(50) NULL, 
    [EmailID] nvarchar(50) NULL, 
    [Gender] varchar(10) NULL, 
    [Hobbies] varchar(50) NULL, 
    [ModifyTime] datetime NULL, 
    [CreateTime] datetime NULL, 
    CONSTRAINT [PK_Users] PRIMARY KEY ([UserID])
)

【性别】:我们选择ASPxGridView的GridViewDataComboBoxColumn列类型,通过如下代码实现下拉选择性别“男”和“女”。

 <dx:GridViewDataComboBoxColumn FieldName="Gender" VisibleIndex="6" Caption="性别" Width="80px">
                        <EditFormSettings VisibleIndex="4" Visible="True" Caption="性别" />
                        <CellStyle HorizontalAlign="Center" />
                        <HeaderStyle HorizontalAlign="Center" />
                        <PropertiesComboBox>
                            <Items>
                                <dx:ListEditItem Text="男" Value="男" />
                                <dx:ListEditItem Text="女" Value="女" />
                            </Items>
                        </PropertiesComboBox>
</dx:GridViewDataComboBoxColumn>

 【兴趣爱好】:通过编辑模板EditItemTemplate,建立自定义的兴趣爱好CheckBox选项的模板列。

 <dx:GridViewDataTextColumn FieldName="Hobbies" VisibleIndex="7" Caption="兴趣爱好" Width="100px">
                        <EditFormSettings VisibleIndex="5" Visible="True" Caption="兴趣爱好" />
                        <CellStyle HorizontalAlign="Center" />
                        <HeaderStyle HorizontalAlign="Center" />
                        <EditItemTemplate>
                            <table border="0">
                                <tr>
                                    <td>
                                        <dx:ASPxCheckBox ID="ASPxCheckBox_H1" runat="server" ClientInstanceName="cb_hob1" Text="阅读" Layout="Flow" OnInit="ASPxCheckBox_Hobbies_Init">
                                        </dx:ASPxCheckBox>
                                    </td>
                                    <td> </td>
                                    <td>
                                        <dx:ASPxCheckBox ID="ASPxCheckBox_H2" ClientInstanceName="cb_hob2" runat="server" Text="思考" Layout="Flow" OnInit="ASPxCheckBox_Hobbies_Init">
                                        </dx:ASPxCheckBox>
                                    </td>
                                    <td> </td>
                                    <td>
                                        <dx:ASPxCheckBox ID="ASPxCheckBox_H3" runat="server" ClientInstanceName="cb_hob3" Text="运动" Layout="Flow" OnInit="ASPxCheckBox_Hobbies_Init">
                                        </dx:ASPxCheckBox>
                                    </td>
                                    <td> </td>
                                    <td>
                                        <dx:ASPxCheckBox ID="ASPxCheckBox_H4" runat="server" ClientInstanceName="cb_hob4" Text="社交" Layout="Flow" OnInit="ASPxCheckBox_Hobbies_Init">
                                        </dx:ASPxCheckBox>
                                    </td>
                                </tr>
                            </table>
                        </EditItemTemplate>
</dx:GridViewDataTextColumn>

【 创建时间】与【修改时间】在界面上均不显示,分别记录每条数据的创建时间和最后一次修改时间。

 <dx:GridViewDataDateColumn FieldName="CreateTime" VisibleIndex="7" Caption="创建时间" Width="100px" Visible="false">
                        <EditFormSettings VisibleIndex="5" Visible="False" Caption="创建时间" />
                        <CellStyle HorizontalAlign="Center" />
                        <HeaderStyle HorizontalAlign="Center" />
                    </dx:GridViewDataDateColumn>
<dx:GridViewDataDateColumn FieldName="ModifyTime" VisibleIndex="7" Caption="修改时间" Width="100px" Visible="false">
                        <EditFormSettings VisibleIndex="5" Visible="True" Caption="修改时间" />
                        <CellStyle HorizontalAlign="Center" />
                        <HeaderStyle HorizontalAlign="Center" />
</dx:GridViewDataDateColumn>

关于这4个字段的后台赋值,我们暂先放一边,来看一下,目前编辑界面的效果。

DevExpress ASP.NET 使用经验谈(8)-ASPxGridView自定义列和基本事件_第1张图片

                                                                         图一 添加字段后的编辑页

【性别】字段,可以直接下拉选择并保存,但是【兴趣爱好】选项选取后保存无效,【创建时间】,【修改时间】因为并未开放编辑,且后台并未赋值,

所以仍为空值。那么如何才能保存这三个字段呢?

这里我们就要利用ASPxGridView的OnRowInserting事件、OnRowUpdating事件来执行赋值和保存。

后台OnRowInserting事件代码如下:

 protected void ASPxGridView1_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e)
    {
        //在RowInserting时,将当前时间赋值给“创建时间列”CreateTime赋值
        e.NewValues["CreateTime"] = DateTime.Now;

        GridViewDataColumn columnHobbies = ASPxGridView1.Columns["Hobbies"] as GridViewDataColumn; //取出GridView的Column
        //通过ASPxGridView1.FindEditRowCellTemplateControl找出自定义的CheckBox
        ASPxCheckBox cbH1 = (ASPxGridView1.FindEditRowCellTemplateControl(columnHobbies, "ASPxCheckBox_H1") as ASPxCheckBox);
        ASPxCheckBox cbH2 = (ASPxGridView1.FindEditRowCellTemplateControl(columnHobbies, "ASPxCheckBox_H2") as ASPxCheckBox);
        ASPxCheckBox cbH3 = (ASPxGridView1.FindEditRowCellTemplateControl(columnHobbies, "ASPxCheckBox_H3") as ASPxCheckBox);
        ASPxCheckBox cbH4 = (ASPxGridView1.FindEditRowCellTemplateControl(columnHobbies, "ASPxCheckBox_H4") as ASPxCheckBox);

        ArrayList listHobbies = new ArrayList();
        if (cbH1.Checked == true)
        {
            listHobbies.Add(cbH1.Text);
        }
        if (cbH2.Checked == true)
        {
            listHobbies.Add(cbH2.Text);
        }
        if (cbH3.Checked == true)
        {
            listHobbies.Add(cbH3.Text);
        }
        if (cbH4.Checked == true)
        {
            listHobbies.Add(cbH4.Text);
        }
        //通过 e.NewValues["Hobbies"]赋值
        e.NewValues["Hobbies"] = string.Join(",", listHobbies.ToArray());
    }

我们可以通过e.NewValues["列名"]赋值来存取数据,通过ASPxGridView1.FindEditRowCellTemplateControl方法,可以找到模板列中的

自定义控件。

同理,后台RowUpdating事件如下:

 protected void ASPxGridView1_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e)
    {
        //在RowUpdating时,将当前时间赋值给“创建时间列”ModifyTime赋值
        e.NewValues["ModifyTime"] = DateTime.Now;

        GridViewDataColumn columnHobbies = ASPxGridView1.Columns["Hobbies"] as GridViewDataColumn;//取出GridView的Column
        //通过ASPxGridView1.FindEditRowCellTemplateControl找出自定义的CheckBox
        ASPxCheckBox cbH1 = (ASPxGridView1.FindEditRowCellTemplateControl(columnHobbies, "ASPxCheckBox_H1") as ASPxCheckBox);
        ASPxCheckBox cbH2 = (ASPxGridView1.FindEditRowCellTemplateControl(columnHobbies, "ASPxCheckBox_H2") as ASPxCheckBox);
        ASPxCheckBox cbH3 = (ASPxGridView1.FindEditRowCellTemplateControl(columnHobbies, "ASPxCheckBox_H3") as ASPxCheckBox);
        ASPxCheckBox cbH4 = (ASPxGridView1.FindEditRowCellTemplateControl(columnHobbies, "ASPxCheckBox_H4") as ASPxCheckBox);

        ArrayList listHobbies = new ArrayList();
        if (cbH1.Checked == true)
        {
            listHobbies.Add(cbH1.Text);
        }
        if (cbH2.Checked == true)
        {
            listHobbies.Add(cbH2.Text);
        }
        if (cbH3.Checked == true)
        {
            listHobbies.Add(cbH3.Text);
        }
        if (cbH4.Checked == true)
        {
            listHobbies.Add(cbH4.Text);
        }
        //通过 e.NewValues["Hobbies"]赋值
        e.NewValues["Hobbies"] = string.Join(",", listHobbies.ToArray());
    }

通过上面代码,我们已经能将【兴趣爱好】、【创建时间】、【修改时间】的数据保存到数据库,但是再次编辑时,【兴趣爱好】列数据并未绑定控件,

这时,就需要用到ASPxCheckBox控件的OnInit事件。

 <dx:ASPxCheckBox ID="ASPxCheckBox_H2" ClientInstanceName="cb_hob2" runat="server" Text="思考" Layout="Flow" OnInit="ASPxCheckBox_Hobbies_Init">
 </dx:ASPxCheckBox>

 ASPxCheckBox_Hobbies_Init事件代码如下:

    protected void ASPxCheckBox_Hobbies_Init(object sender, EventArgs e)
    {
        ASPxCheckBox cblHb = sender as ASPxCheckBox;
        GridViewEditItemTemplateContainer container = cblHb.NamingContainer as GridViewEditItemTemplateContainer;
        string strHobbies = string.Empty;
        if (DataBinder.Eval(container.DataItem, "Hobbies") != null)
            strHobbies = DataBinder.Eval(container.DataItem, "Hobbies").ToString().Trim();

        if (strHobbies.Contains(cblHb.Text))
        {
            cblHb.Checked = true;
        }
    }

此时,我们新增一条数据,录入信息如下,点击保存,再次点击编辑图标打开编辑界面,已经显示【兴趣爱好】列的选择状态数据绑定,因为是

新增数据,所以【修改时间】为空。

DevExpress ASP.NET 使用经验谈(8)-ASPxGridView自定义列和基本事件_第2张图片

                                                      图二 增加后台取值赋值代码,执行新增并保存后的界面

再次编辑,修改【兴趣爱好】选项,取消“运动“选项,增加”思考“选项,再保存,这时【修改时间】更新。

DevExpress ASP.NET 使用经验谈(8)-ASPxGridView自定义列和基本事件_第3张图片

                                                                图三 再执行编辑并保存后的界面

最后贴出完整代码:

1、前台ASPX页面代码:

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

<%@ Register Assembly="DevExpress.Xpo.v12.2.Web, Version=12.2.4.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" Namespace="DevExpress.Xpo" TagPrefix="dx" %>

<%@ Register Assembly="DevExpress.Web.v12.2, Version=12.2.4.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" Namespace="DevExpress.Web.ASPxGridView" TagPrefix="dx" %>

<%@ Register Assembly="DevExpress.Web.v12.2, Version=12.2.4.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" Namespace="DevExpress.Web.ASPxEditors" TagPrefix="dx" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <p>
                <h1>ASPxGridView自定义列和事件</h1>
            </p>
            <dx:ASPxGridView ID="ASPxGridView1" runat="server" AutoGenerateColumns="False"
                OnRowInserting="ASPxGridView1_RowInserting"
                OnRowUpdating="ASPxGridView1_RowUpdating"
                DataSourceID="XpoDataSource1" KeyFieldName="UserID" Theme="Aqua">
                <Columns>
                    <dx:GridViewCommandColumn VisibleIndex="0" ButtonType="Image" Width="80px">
                        <EditButton Visible="true">
                            <Image ToolTip="编辑" Url="Assets/images/edit.png"></Image>
                        </EditButton>
                        <NewButton Visible="true">
                            <Image ToolTip="新增" Url="Assets/images/new.png"></Image>
                        </NewButton>
                        <DeleteButton Visible="true">
                            <Image ToolTip="删除" Url="Assets/images/delete.png"></Image>
                        </DeleteButton>
                        <UpdateButton Visible="true">
                            <Image ToolTip="保存" Url="Assets/images/save.gif"></Image>
                        </UpdateButton>
                        <CancelButton Visible="true">
                            <Image ToolTip="取消" Url="Assets/images/cancel.gif"></Image>
                        </CancelButton>
                    </dx:GridViewCommandColumn>
                    <dx:GridViewDataTextColumn FieldName="UserID" ReadOnly="True" VisibleIndex="1" Visible="false">
                    </dx:GridViewDataTextColumn>
                    <dx:GridViewDataTextColumn FieldName="UserName" VisibleIndex="2" Caption="用户姓名" >
                        <EditFormSettings VisibleIndex="2" Visible="True" Caption="用户姓名" />
                    </dx:GridViewDataTextColumn>
                    <dx:GridViewDataTextColumn FieldName="FirstName" VisibleIndex="3" Caption="名" Width="80px">
                        <EditFormSettings VisibleIndex="3" Visible="True" Caption="名" />
                        <CellStyle HorizontalAlign="Center" />
                        <HeaderStyle HorizontalAlign="Center" />
                    </dx:GridViewDataTextColumn>
                    <dx:GridViewDataTextColumn FieldName="LastName" VisibleIndex="4" Caption="姓" Width="80px">
                        <EditFormSettings VisibleIndex="4" Visible="True" Caption="姓" />
                        <CellStyle HorizontalAlign="Center" />
                        <HeaderStyle HorizontalAlign="Center" />
                    </dx:GridViewDataTextColumn>
                    <dx:GridViewDataTextColumn FieldName="MiddleName" VisibleIndex="5" Caption="教名" Width="100px">
                        <EditFormSettings VisibleIndex="5" Visible="False" Caption="教名" />
                        <CellStyle HorizontalAlign="Center" />
                        <HeaderStyle HorizontalAlign="Center" />
                    </dx:GridViewDataTextColumn>
                    <dx:GridViewDataComboBoxColumn FieldName="Gender" VisibleIndex="6" Caption="性别" Width="80px">
                        <EditFormSettings VisibleIndex="4" Visible="True" Caption="性别" />
                        <CellStyle HorizontalAlign="Center" />
                        <HeaderStyle HorizontalAlign="Center" />
                        <PropertiesComboBox>
                            <Items>
                                <dx:ListEditItem Text="男" Value="男" />
                                <dx:ListEditItem Text="女" Value="女" />
                            </Items>
                        </PropertiesComboBox>
                    </dx:GridViewDataComboBoxColumn>
                    <dx:GridViewDataTextColumn FieldName="Hobbies" VisibleIndex="7" Caption="兴趣爱好" Width="100px">
                        <EditFormSettings VisibleIndex="5" Visible="True" Caption="兴趣爱好" />
                        <CellStyle HorizontalAlign="Center" />
                        <HeaderStyle HorizontalAlign="Center" />
                        <EditItemTemplate>
                            <table border="0">
                                <tr>
                                    <td>
                                        <dx:ASPxCheckBox ID="ASPxCheckBox_H1" runat="server" ClientInstanceName="cb_hob1" Text="阅读" Layout="Flow" OnInit="ASPxCheckBox_Hobbies_Init">
                                        </dx:ASPxCheckBox>
                                    </td>
                                    <td> </td>
                                    <td>
                                        <dx:ASPxCheckBox ID="ASPxCheckBox_H2" ClientInstanceName="cb_hob2" runat="server" Text="思考" Layout="Flow" OnInit="ASPxCheckBox_Hobbies_Init">
                                        </dx:ASPxCheckBox>
                                    </td>
                                    <td> </td>
                                    <td>
                                        <dx:ASPxCheckBox ID="ASPxCheckBox_H3" runat="server" ClientInstanceName="cb_hob3" Text="运动" Layout="Flow" OnInit="ASPxCheckBox_Hobbies_Init">
                                        </dx:ASPxCheckBox>
                                    </td>
                                    <td> </td>
                                    <td>
                                        <dx:ASPxCheckBox ID="ASPxCheckBox_H4" runat="server" ClientInstanceName="cb_hob4" Text="社交" Layout="Flow" OnInit="ASPxCheckBox_Hobbies_Init">
                                        </dx:ASPxCheckBox>
                                    </td>
                                </tr>
                            </table>
                        </EditItemTemplate>
                    </dx:GridViewDataTextColumn>
                    <dx:GridViewDataTextColumn FieldName="EmailID" VisibleIndex="6" Caption="邮箱" Width="200px">
                        <EditFormSettings VisibleIndex="6" Visible="True" Caption="邮箱" ColumnSpan="2" />
                    </dx:GridViewDataTextColumn>
                    <dx:GridViewDataDateColumn FieldName="CreateTime" VisibleIndex="7" Caption="创建时间" Width="100px" >
                        <EditFormSettings VisibleIndex="5" Visible="False" Caption="创建时间" />
                        <CellStyle HorizontalAlign="Center" />
                        <HeaderStyle HorizontalAlign="Center" />
                    </dx:GridViewDataDateColumn>
                    <dx:GridViewDataDateColumn FieldName="ModifyTime" VisibleIndex="7" Caption="修改时间" Width="100px" >
                        <EditFormSettings VisibleIndex="5" Visible="False" Caption="修改时间" />
                        <CellStyle HorizontalAlign="Center" />
                        <HeaderStyle HorizontalAlign="Center" />
                    </dx:GridViewDataDateColumn>
                </Columns>
                <SettingsBehavior ConfirmDelete="true" AllowFocusedRow="true" AllowSelectSingleRowOnly="true" AllowSelectByRowClick="true" />
                <SettingsEditing EditFormColumnCount="2" />
                <Settings ShowFooter="True" />
                <SettingsText EmptyDataRow="无记录" ConfirmDelete="确定删除吗?" />
                <SettingsPager Mode="ShowPager" PageSize="3" />
            </dx:ASPxGridView>
        </div>
        <dx:XpoDataSource ID="XpoDataSource1" runat="server" TypeName="XPOModel.DemoDB.Users"></dx:XpoDataSource>
    </form>
</body>
</html>

 2、后台代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using DevExpress.Xpo;
using DevExpress.Xpo.DB;
using DevExpress.Web.ASPxGridView;
using DevExpress.Web.ASPxEditors;
using System.Collections;
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Init(object sender, EventArgs e)
    {
        string provider = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;//获取数据库连接
        IDataLayer datalayer = new SimpleDataLayer(XpoDefault.GetConnectionProvider(provider, AutoCreateOption.DatabaseAndSchema));//建立数据层XPO独有的
        DevExpress.Xpo.Session session = new DevExpress.Xpo.Session(datalayer); //将数据层和会话绑定
        XpoDataSource1.Session = session;
    }

    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void ASPxCheckBox_Hobbies_Init(object sender, EventArgs e)
    {
        ASPxCheckBox cblHb = sender as ASPxCheckBox;
        GridViewEditItemTemplateContainer container = cblHb.NamingContainer as GridViewEditItemTemplateContainer;
        string strHobbies = string.Empty;
        if (DataBinder.Eval(container.DataItem, "Hobbies") != null)
            strHobbies = DataBinder.Eval(container.DataItem, "Hobbies").ToString().Trim();

        if (strHobbies.Contains(cblHb.Text))
        {
            cblHb.Checked = true;
        }
    }

    protected void ASPxGridView1_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e)
    {
        //在RowInserting时,将当前时间赋值给“创建时间列”CreateTime赋值
        e.NewValues["CreateTime"] = DateTime.Now;

        GridViewDataColumn columnHobbies = ASPxGridView1.Columns["Hobbies"] as GridViewDataColumn; //取出GridView的Column
        //通过ASPxGridView1.FindEditRowCellTemplateControl找出自定义的CheckBox
        ASPxCheckBox cbH1 = (ASPxGridView1.FindEditRowCellTemplateControl(columnHobbies, "ASPxCheckBox_H1") as ASPxCheckBox);
        ASPxCheckBox cbH2 = (ASPxGridView1.FindEditRowCellTemplateControl(columnHobbies, "ASPxCheckBox_H2") as ASPxCheckBox);
        ASPxCheckBox cbH3 = (ASPxGridView1.FindEditRowCellTemplateControl(columnHobbies, "ASPxCheckBox_H3") as ASPxCheckBox);
        ASPxCheckBox cbH4 = (ASPxGridView1.FindEditRowCellTemplateControl(columnHobbies, "ASPxCheckBox_H4") as ASPxCheckBox);

        ArrayList listHobbies = new ArrayList();
        if (cbH1.Checked == true)
        {
            listHobbies.Add(cbH1.Text);
        }
        if (cbH2.Checked == true)
        {
            listHobbies.Add(cbH2.Text);
        }
        if (cbH3.Checked == true)
        {
            listHobbies.Add(cbH3.Text);
        }
        if (cbH4.Checked == true)
        {
            listHobbies.Add(cbH4.Text);
        }
        //通过 e.NewValues["Hobbies"]赋值
        e.NewValues["Hobbies"] = string.Join(",", listHobbies.ToArray());
    }
    protected void ASPxGridView1_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e)
    {
        //在RowUpdating时,将当前时间赋值给“创建时间列”ModifyTime赋值
        e.NewValues["ModifyTime"] = DateTime.Now;

        GridViewDataColumn columnHobbies = ASPxGridView1.Columns["Hobbies"] as GridViewDataColumn;//取出GridView的Column
        //通过ASPxGridView1.FindEditRowCellTemplateControl找出自定义的CheckBox
        ASPxCheckBox cbH1 = (ASPxGridView1.FindEditRowCellTemplateControl(columnHobbies, "ASPxCheckBox_H1") as ASPxCheckBox);
        ASPxCheckBox cbH2 = (ASPxGridView1.FindEditRowCellTemplateControl(columnHobbies, "ASPxCheckBox_H2") as ASPxCheckBox);
        ASPxCheckBox cbH3 = (ASPxGridView1.FindEditRowCellTemplateControl(columnHobbies, "ASPxCheckBox_H3") as ASPxCheckBox);
        ASPxCheckBox cbH4 = (ASPxGridView1.FindEditRowCellTemplateControl(columnHobbies, "ASPxCheckBox_H4") as ASPxCheckBox);

        ArrayList listHobbies = new ArrayList();
        if (cbH1.Checked == true)
        {
            listHobbies.Add(cbH1.Text);
        }
        if (cbH2.Checked == true)
        {
            listHobbies.Add(cbH2.Text);
        }
        if (cbH3.Checked == true)
        {
            listHobbies.Add(cbH3.Text);
        }
        if (cbH4.Checked == true)
        {
            listHobbies.Add(cbH4.Text);
        }
        //通过 e.NewValues["Hobbies"]赋值
        e.NewValues["Hobbies"] = string.Join(",", listHobbies.ToArray());
    }
}

 源码下载:http://pan.baidu.com/s/1hqziMNE

你可能感兴趣的:(DevExpress)