使用 ASP.Net Web 窗體的示例說明

ASPX 頁面上的 GridView 定義

如下所示,第一列網格被定義為一個核取方塊列,有條件地清除,如下面的進一步示例所示(標題核取方塊僅用於選擇/取消選擇當前頁面上的所有行,但同樣可以擴充套件到所有行在網格上):

<dx:ASPxGridView ID="ASPxGridView1" runat="server" AutoGenerateColumns="True" ClientInstanceName="ASPxGridView1" KeyFieldName="CustomerID" Width="100%" 
        OnHtmlRowCreated="ASPxGridView1_HtmlRowCreated" OnCustomJSProperties="ASPxGridView1_CustomJSProperties">
    <SettingsPager PageSize="30" />
    <Settings VerticalScrollBarMode="Visible" VerticalScrollableHeight="350" />
    <Paddings Padding="0px" />
    <Border BorderWidth="0px" />
    <BorderBottom BorderWidth="1px" />
    <Columns>
        <dx:GridViewDataTextColumn Caption="#" VisibleIndex="0">
            <DataItemTemplate>
                <dx:ASPxCheckBox ID="cbCheck" runat="server" AutoPostBack="false" CssClass="chkSelDgProdRow" OnLoad="ASPxGridView1_cbCheck_Load" />
            </DataItemTemplate>
            <HeaderTemplate>
                <dx:ASPxCheckBox ID="cbPageSelectAll" runat="server" ToolTip="Select/Unselect all rows on the page" ClientInstanceName="cbPageSelectAll"
                    ClientSideEvents-CheckedChanged="function(s, e) { checkUncheckSelectableRowsOnPage(s.GetChecked()); }" OnLoad="ASPxGridView1_cbPageSelectAll_Load" />
            </HeaderTemplate>
        </dx:GridViewDataTextColumn>
        <dx:GridViewDataTextColumn FieldName="ContactName" VisibleIndex="2">
        </dx:GridViewDataTextColumn>
        <dx:GridViewDataTextColumn FieldName="CompanyName" VisibleIndex="1">
        </dx:GridViewDataTextColumn>
        <dx:GridViewDataTextColumn FieldName="ContactTitle" VisibleIndex="3">
        </dx:GridViewDataTextColumn>
        <dx:GridViewDataTextColumn FieldName="City" VisibleIndex="5">
        </dx:GridViewDataTextColumn>
        <dx:GridViewDataTextColumn FieldName="Country" VisibleIndex="6">
        </dx:GridViewDataTextColumn>
        <dx:GridViewDataTextColumn FieldName="Phone" VisibleIndex="9">
        </dx:GridViewDataTextColumn>
    </Columns>
    <ClientSideEvents BeginCallback="OnGridCallBackBegin" />
</dx:ASPxGridView>

SQL 表結構

資料從 SQL 表’Customers’載入,其結構如下(請注意該表是 NorthWind 資料庫的標準結構,具有多餘的’IsRegistered’列以演示’條件’選擇功能):

CREATE TABLE [dbo].[Customers] (
    [CustomerID]   NCHAR (5)     NOT NULL,
    [CompanyName]  NVARCHAR (40) NOT NULL,
    [ContactName]  NVARCHAR (30) NULL,
    [ContactTitle] NVARCHAR (30) NULL,
    [Address]      NVARCHAR (60) NULL,
    [City]         NVARCHAR (15) NULL,
    [Region]       NVARCHAR (15) NULL,
    [PostalCode]   NVARCHAR (10) NULL,
    [Country]      NVARCHAR (15) NULL,
    [Phone]        NVARCHAR (24) NULL,
    [Fax]          NVARCHAR (24) NULL,
    [IsRegistered] BIT           NULL
);

頁面載入事件(.CS 頁面)

._L 頁面上的 Page_Load() 事件和相應的相關程式碼。請注意,DevExpress 的 Custom JS 屬性需要具有字首’cp’。

    private const string _selectableRowsKey = "cp_SelectableRows";
    private const string _selectedRowsCountKey = "cp_SelectedRowsCount";

    protected void Page_Load(object sender, EventArgs e)
    {
        PopulateGrid();
    }

    private void PopulateGrid()
    {
        using (SqlConnection conn = new SqlConnection())
        {
            conn.ConnectionString = ConfigurationManager.ConnectionStrings["NWindConnectionString"].ConnectionString;
            conn.Open();

            using (SqlCommand cmd = new SqlCommand("SELECT * FROM [Customers]", conn))
            {
                DataTable dt = new DataTable();
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(dt);

                ASPxGridView1.DataSource = dt;
                ASPxGridView1.DataBind();
            }

            conn.Close();
        }
    }

HtmlRowCreated 事件(.CS 頁面)

在資料繫結時在 GridView 上建立的每一行都會呼叫此事件。這用於有條件地檢查 IsRegistered 是否設定為 true,清除第一列上的核取方塊。此外,它也用於為網格設定 Custom JS 屬性,該屬性將具有允許在 UI 上選擇/取消選擇的#left 行列表。

    protected void ASPxGridView1_HtmlRowCreated(object sender, ASPxGridViewTableRowEventArgs e)
    {
        if (e.RowType == GridViewRowType.Data)
        {
            if (e.GetValue("IsRegistered") != null)
            {
                if (e.GetValue("IsRegistered") != DBNull.Value && (bool)e.GetValue("IsRegistered"))
                    e.Row.Cells[0].Controls.Clear();
                else
                {
                    string selectableRows = string.Empty;
                    if (ASPxGridView1.JSProperties.ContainsKey(_selectableRowsKey))
                        selectableRows = (string)ASPxGridView1.JSProperties[_selectableRowsKey];
                    selectableRows += "#" + e.VisibleIndex.ToString();
                    ASPxGridView1.JSProperties[_selectableRowsKey] = selectableRows;
                }
            }
        }
    }

網格核取方塊載入事件(.CS 頁面)

在 UI 上載入時,會為每個核取方塊呼叫此事件。這用於設定它的狀態以及附加 JavaScript 程式碼以選擇/取消選中核取方塊的行。

    protected void ASPxGridView1_cbCheck_Load(object sender, EventArgs e)
    {
        ASPxCheckBox cb = (ASPxCheckBox)sender;

        GridViewDataItemTemplateContainer container = (GridViewDataItemTemplateContainer)cb.NamingContainer;
        cb.ClientInstanceName = string.Format("cbCheck{0}", container.VisibleIndex);
        cb.Checked = ASPxGridView1.Selection.IsRowSelected(container.VisibleIndex);

        cb.ClientSideEvents.CheckedChanged = string.Format("function (s, e) {{ ASPxGridView1.SelectRowOnPage({0}, s.GetChecked()); updateSelectedKeys(s.GetChecked()); }}", container.VisibleIndex);
    }

選擇載入事件(.CS 頁面)上的所有頁面核取方塊

此事件用於在導航頁面時根據其選擇狀態選擇/取消選中全選頁面核取方塊。

    protected void ASPxGridView1_cbPageSelectAll_Load(object sender, EventArgs e)
    {
        ASPxCheckBox cb = (ASPxCheckBox)sender;
        ASPxGridView grid = (cb.NamingContainer as GridViewHeaderTemplateContainer).Grid;

        bool cbChecked = true;
        int start = grid.VisibleStartIndex;
        int end = grid.VisibleStartIndex + grid.SettingsPager.PageSize;
        end = (end > grid.VisibleRowCount ? grid.VisibleRowCount : end);

        for (int i = start; i < end; i++)
        {
            DataRowView dr = (DataRowView)(grid.GetRow(i));
            if (!grid.Selection.IsRowSelected(i))
            {
                if (dr["IsRegistered"] == DBNull.Value || !(bool)dr["IsRegistered"])
                {
                    cbChecked = false;
                    break;
                }
            }
        }
        cb.Checked = cbChecked;
    }

Grid CustomJS 屬性設定事件(.CS 頁面)

此事件用於設定 GridView 當前頁面的 Selected Rows Count。這在 JavaScript 中用於自動選擇標題核取方塊。

    protected void ASPxGridView1_CustomJSProperties(object sender, ASPxGridViewClientJSPropertiesEventArgs e)
    {
        ASPxGridView grid = sender as ASPxGridView;
        int start = grid.VisibleStartIndex;
        int end = grid.VisibleStartIndex + grid.SettingsPager.PageSize;
        int selectNumbers = 0;

        end = (end > grid.VisibleRowCount ? grid.VisibleRowCount : end);

        for (int i = start; i < end; i++)
            if (grid.Selection.IsRowSelected(i))
                selectNumbers++;

        e.Properties[_selectedRowsCountKey] = selectNumbers;
    }

用於處理客戶端事件和相關功能的 JavaScript 程式碼

核取方塊選中的更改事件期間呼叫此 JavaScript 函式,如 ASPX 頁面中所定義:

function checkUncheckSelectableRowsOnPage(isChecked) {
    var selectableRowIndexes = ASPxGridView1.cp_SelectableRows;
    var grdStartIndex = ASPxGridView1.visibleStartIndex;
    var grdEndIndex = grdStartIndex + ASPxGridView1.pageRowCount;

    if (selectableRowIndexes != null && selectableRowIndexes != '') {
        var rowIdxes = selectableRowIndexes.split("#");
        var selectedRowsCount = 0;
        if (rowIdxes != null) {
            try {
                for (var i = 0; i < rowIdxes.length; i++) {
                    if (rowIdxes[i] != "") {
                        var rowIndex = parseInt(rowIdxes[i]);
                        if (rowIndex != NaN && rowIndex >= 0 && rowIndex >= grdStartIndex && rowIndex < grdEndIndex) {
                            if (ASPxClientControl.GetControlCollection().GetByName("cbCheck" + rowIdxes[i]) != null) {
                                if (isChecked) {
                                    ASPxGridView1.SelectRowOnPage(rowIdxes[i]);
                                    selectedRowsCount++;
                                }
                                else
                                    ASPxGridView1.UnselectRowOnPage(rowIdxes[i]);
                                ASPxClientControl.GetControlCollection().GetByName("cbCheck" + rowIdxes[i]).SetChecked(isChecked);
                            }
                        }
                    }
                }
                //updateSelectedKeys();   // Can be used if the selected keys needs to be saved separately in a Hidden field
                ASPxGridView1.cp_SelectedRowsCount = selectedRowsCount;
                currentSelectedRowsCount = selectedRowsCount;
            }
            finally {
            }
        }
    }
}

此 JavaScript 程式碼用於根據 GridView 當前頁面上的選定行在標題處選中全部選擇頁面核取方塊。

var currentSelectedRowsCount = 0;
function updateSelectedKeys(isChecked) {
    var selKeys = ASPxGridView1.GetSelectedKeysOnPage();
    if (selKeys != null) {
        var cpIDsList = '';
        try {
            for (var i = 0; i < selKeys.length; i++) {
                cpIDsList += selKeys[i] + ',';
            }
        }
        finally {
        }
        //$("#hdnSelectedCatProdIDs").val(cpIDsList);
        if (isChecked) {
            currentSelectedRowsCount++;
            cbPageSelectAll.SetChecked(selKeys.length == ASPxGridView1.cp_SelectedRowsCount);
        }
        else {
            cbPageSelectAll.SetChecked(selKeys.length == currentSelectedRowsCount);
            currentSelectedRowsCount--;
        }
    }
}

此 JavaScript 客戶端事件處理程式用於設定從 Server 設定的當前選定行。

function OnGridCallBackBegin(s, e) {
    currentSelectedRowsCount = ASPxGridView1.cp_SelectedRowsCount;
}