using System;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Web.UI;

namespace GridView_RowsSample
{
    public partial class _Default : Page
    {
        private static DataTable GetData()
        {
            var dt = new DataTable();
            dt.Columns.Add("Id");
            dt.Columns.Add("Name");
            dt.Columns.Add("Desc");
            dt.Columns.Add("Check", typeof(bool));

            // 50 rows to simulate a heavier grid like 
            for (int i = 1; i <= 50; i++)
            {
                dt.Rows.Add(i, "name-" + i, "desc-" + i, i % 2 == 0);
            }
            return dt;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindGrid(null);

                string initScript = @"
                    Sys.Application.add_load(function () {
                        console.log('Sys.Application.add_load fired (registered on initial load only)');
                        ReadRows();
                    });";
                ClientScript.RegisterStartupScript(
                    GetType(), "readRowsInit", initScript, true);
            }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            // Simulates service call + rebind on partial postback
            string filter = TextBoxFilter.Text.Trim().ToLower();
            BindGrid(string.IsNullOrEmpty(filter) ? null : filter);
        }

        private void BindGrid(string nameFilter)
        {
            var dt = GetData();
            if (nameFilter != null)
            {
                var filtered = dt.AsEnumerable()
                    .Where(r => r["Name"].ToString().ToLower().Contains(nameFilter));
                dt = filtered.Any() ? filtered.CopyToDataTable() : dt.Clone();
            }
            C1GridView1.DataSource = dt;
            C1GridView1.DataBind();
		}

        protected void C1GridView1_RowDataBound(object sender,
            C1.Web.Wijmo.Controls.C1GridView.C1GridViewRowEventArgs e)
        {
            if (e.Row.RowType == C1.Web.Wijmo.Controls.C1GridView.C1GridViewRowType.DataRow)
            {
                var rowData = (DataRowView)e.Row.DataItem;
                var tripJson = "{\"id\":" + rowData["Id"] +
                    ",\"name\":\"" + rowData["Name"] + "\"}";
                e.Row.Attributes["trip"] = tripJson;

                // Simulate heavier server-side rendering like  complex grid
                System.Threading.Thread.Sleep(50);
            }
        }
    }
}