using Telerik.Web.UI;
using System.Data;
using System.Data.OleDb;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Telerik.GridExamplesCS.Programming.FilteringTemplateColumns
{
    public class MyCustomFilteringColumn : GridTemplateColumn
    {

        public static string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + System.Web.HttpContext.Current.Server.MapPath("~/App_Data/Nwind.mdb");
        public DataTable GetDataTable(string query)
        {
            OleDbConnection connection1 = new OleDbConnection(connectionString);
            OleDbDataAdapter adapter1 = new OleDbDataAdapter();
            adapter1.SelectCommand = new OleDbCommand(query, connection1);
            DataTable table1 = new DataTable();
            connection1.Open();
            try
            {
                adapter1.Fill(table1);
            }
            finally
            {
                connection1.Close();
            }
            return table1;
        }

        protected override void SetupFilterControls(TableCell cell)
        {
            RadComboBox rcBox = new RadComboBox();
            rcBox.ID = "DropDownList1";
            rcBox.Width = Unit.Percentage(100);
            rcBox.AutoPostBack = true;
            rcBox.Skin = "Web20";
            rcBox.DataTextField = this.DataField;
            rcBox.DataValueField = this.DataField;
            rcBox.SelectedIndexChanged += rcBox_SelectedIndexChanged;
            DataTable table = GetDataTable(string.Format("SELECT DISTINCT {0} FROM {1}", this.DataField, "Customers"));
            DataRow row = table.NewRow();
            row[this.DataField] = "";
            table.Rows.InsertAt(row, 0);
            rcBox.DataSource = table;
            cell.Controls.Add(rcBox);
        }

        protected override void SetCurrentFilterValueToControl(TableCell cell)
        {
            if (!(this.CurrentFilterValue == ""))
            {
                ((RadComboBox)cell.Controls[0]).Items.FindItemByText(this.CurrentFilterValue).Selected = true;
            }
        }

        protected override string GetCurrentFilterValueFromControl(TableCell cell)
        {
            string currentValue = ((RadComboBox)cell.Controls[0]).SelectedItem.Value;
            this.CurrentFilterFunction = (currentValue != "")? GridKnownFunction.EqualTo : GridKnownFunction.NoFilter;
            return currentValue;
        }

        private void rcBox_SelectedIndexChanged(object sender, Telerik.Web.UI.RadComboBoxSelectedIndexChangedEventArgs e)
        {
            ((GridFilteringItem)(((RadComboBox)sender).Parent.Parent)).FireCommandEvent("Filter", new Pair());
        }
    }
}