using Telerik.Web.UI;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;


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

        public DataTable GetDataTable(string queryString)
        {
            string ConnString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            SqlConnection MySqlConnection = new SqlConnection(ConnString);
            SqlDataAdapter MySqlDataAdapter = new SqlDataAdapter();
            MySqlDataAdapter.SelectCommand = new SqlCommand(queryString, MySqlConnection);

            DataTable myDataTable = new DataTable();
            MySqlConnection.Open();
            try
            {
                MySqlDataAdapter.Fill(myDataTable);
            }
            finally
            {
                MySqlConnection.Close();
            }

            return myDataTable;
        }

        protected override void SetupFilterControls(TableCell cell)
        {
            RadComboBox rcBox = new RadComboBox();
            rcBox.ID = "DropDownList1";
            //rcBox.Width = Unit.Percentage(100);
            rcBox.AutoPostBack = true;
            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());
        }
    }
}