среда, 16 ноября 2011 г.

Add item to combobox with bounded datasource

I ususally need to add item with text like "None" or "Choose ..." to combobox with bounded datasource. So, here is the script, that helps to do this.
We have combobox which reads data from testTable, using ID field as ValueField and Data as TextField.


 Creating our testTable
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[testTable](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [Data] [nvarchar](250) NULL,
    [Status] [nvarchar](50) NULL,
    [Code] [nvarchar](50) NULL,
 CONSTRAINT [PK_testTable] PRIMARY KEY CLUSTERED
(
    [ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

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

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

<!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>
    <form id="form1" runat="server">
    <div>
        <dx:ASPxComboBox ID="ASPxComboBox1" runat="server" ClientIDMode="AutoID"
            DataSourceID="SqlDataSource1" ValueType="System.String" TextField="Data" ValueField="ID">
        </dx:ASPxComboBox>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server"
            ConnectionString="<%$ ConnectionStrings:testConnectionString %>"
            SelectCommand="SELECT [Data], [ID] FROM [testTable]"></asp:SqlDataSource>
    </div>
    </form>
</body>
</html>

AddItemToCombobox.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DevExpress.Web.ASPxEditors;

public partial class AddItemToCombobox : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            ASPxComboBox1.Items.Insert(0, new ListEditItem("All", "0"));
            ASPxComboBox1.DataBound += new EventHandler(addItem_DataBound);
        }
    }

    private void addItem_DataBound(object sender, EventArgs e)
    {
        ListEditItem noneItem = new ListEditItem("All", "0");
        (sender as ASPxComboBox).Items.Insert(0, noneItem);
        (sender as ASPxComboBox).SelectedIndex = 0;
    }
}

Комментариев нет:

Отправить комментарий