Простую страницу поиска.


using System;
using System.Web.UI.WebControls;

namespace RideShare.Web
{
    public partial class UserOrganization : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!IsPostBack)
                {
                    // Fill drop down in search area.
                    FillOrganizationDropDown();

                    // Populate riders grid with all records in Riders table.
                    PopulateRidersGrid((int)SearchArguments.Zeor, null, (int)SearchArguments.Zeor, (int)SearchArguments.GenderDefaultValue);
                }
            }
            catch (Exception ex)
            {
                Exceptions.CatchException(false, ex);
            }
        }

        // Populate drop down list with organizations in each row bound.
        // Select Organization in drop down if rider has one.
        protected void grdRiders_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    DropDownList ddlRiderOrganization = e.Row.FindControl("ddlRiderOrganization") as DropDownList;

                    if (ddlRiderOrganization != null)
                    {
                        PopulateGridOrgDropDown(ddlRiderOrganization);

                        // This is needed to select the organization of rider in ddl in grid
                        Label lblOrganizationId = e.Row.FindControl("lblOrganizationId") as Label;

                        if (lblOrganizationId != null)
                        {
                            if (!(string.IsNullOrEmpty(lblOrganizationId.Text.Trim())))
                            {
                                ddlRiderOrganization.SelectedValue = lblOrganizationId.Text;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Exceptions.CatchException(false, ex);
            }
        }

        // Update organization when user click on update button.
        protected void grdRiders_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                if (e.CommandName == "UpdateOrganization")
                {
                    int rowIndex = -1;
                    rowIndex = int.Parse(e.CommandArgument.ToString());

                    if (rowIndex >= 0)
                    {
                        GridViewRow row = grdRiders.Rows[rowIndex];

                        // Get organization id from ddl
                        int seletedOrganizationId = GetSelecetdOrgId(row);

                        // Organization is selected in drop down.
                        if (seletedOrganizationId > 0)
                        {
                            int riderId = GetRiderId(row);

                            if (riderId > 0)
                            {
                                bool isUpdate = RidersService.UpdateRiderOrganization(riderId, seletedOrganizationId);

                                ShowMessage(isUpdate);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Exceptions.CatchException(false, ex);
            }
        }

        // Filter grid on given criteria.
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            try
            {
                FilterGrid();
            }
            catch (Exception ex)
            {
                Exceptions.CatchException(false, ex);
            }
        }

        // Put all controls on default position and populate grid.
        protected void btnClear_Click(object sender, EventArgs e)
        {
            try
            {
                txtName.Text = "";
                txtAge.Text = "";
                ddlGender.SelectedValue = "-1";

                ddlOrganization.SelectedIndex = 0;
                FilterGrid();
            }
            catch (Exception ex)
            {
                Exceptions.CatchException(false, ex);
            }
        }

        // Filter Riders grid on changing organizaton.
        protected void ddlOrganization_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                FilterGrid();
            }
            catch (Exception ex)
            {
                Exceptions.CatchException(false, ex);
            }
        }

        // Fitler grid on search criteria specified.
        private void FilterGrid()
        {
            int organizationId = 0;
            int.TryParse(ddlOrganization.SelectedValue.ToString(), out organizationId);

            string name = "";
            if (!(string.IsNullOrEmpty(txtName.Text.Trim())))
            {
                name = txtName.Text.Trim();
            }

            int age = 0;
            if (!(string.IsNullOrEmpty(txtAge.Text.Trim())))
            {
                int.TryParse(txtAge.Text.Trim(), out age);
            }

            int gender = int.Parse(ddlGender.SelectedValue.ToString());

            PopulateRidersGrid(organizationId, name, age, gender);
        }

        // Fill grid with riders.
        private void PopulateRidersGrid(int organizationId, string firstName, int age, int gender)
        {
            grdRiders.DataSource = RidersService.GetRidersOnOrganizationId(organizationId, firstName, age, gender);
            grdRiders.DataBind();
        }

        // Fill Organizations drop down. This drop down is in search area.
        private void FillOrganizationDropDown()
        {
            // Append is to retain an item i.e. 'All' having '0' value.
            ddlOrganization.AppendDataBoundItems = true;

            ddlOrganization.DataTextField = "OrganizationName";
            ddlOrganization.DataValueField = "OrganizationId";

            ddlOrganization.DataSource = RidersService.GetAllOrganization();
            ddlOrganization.DataBind();
        }

        // Populate organization drop down in gridview.
        private void PopulateGridOrgDropDown(DropDownList ddlRiderOrganization)
        {
            ddlRiderOrganization.DataTextField = "OrganizationName";
            ddlRiderOrganization.DataValueField = "OrganizationId";

            ddlRiderOrganization.DataSource = RidersService.GetAllOrganization();
            ddlRiderOrganization.DataBind();
        }

        // Get organization id from drown down in grid.
        private int GetSelecetdOrgId(GridViewRow row)
        {
            int selectedOrganizationId = -1;

            // Capture organization drop down list of current row.
            DropDownList ddlRiderOrganization = row.FindControl("ddlRiderOrganization") as DropDownList;

            if (ddlRiderOrganization != null)
            {
                selectedOrganizationId = int.Parse(ddlRiderOrganization.SelectedValue.ToString());
            }

            return selectedOrganizationId;
        }

        // Get rider id from specified grid row.
        private int GetRiderId(GridViewRow row)
        {
            int riderId = 0;

            Label lblRiderId = row.FindControl("lblRiderId") as Label;

            if (lblRiderId != null)
            {
                if (!(string.IsNullOrEmpty(lblRiderId.Text)))
                {
                    riderId = int.Parse(lblRiderId.Text);
                }
            }

            return riderId;
        }

        private void ShowMessage(bool isUpdated)
        {
            if (isUpdated)
            {
                ltrlMessage.Text = "Organization Updated Successfully!";
            }
            else
            {
                ltrlMessage.Text = "Organization Not Updated. Please contact support team!";
            }
        }

        private enum SearchArguments : int
        {
            GenderDefaultValue = -1,
            Zeor = 0
        }
    }
}


508
2
задан 23 июня 2011 в 04:06 Источник Поделиться
Комментарии
1 ответ

Я бы рекомендовал вам зарегистрировать ваши методы в качестве обработчиков событий. У вас есть несколько обработчиков, которые просто называют более описательный метод, который загромождает код немного. В В():

// Register event handlers
btn_Search.Click += new EventHandler(this.FilterGrid);
btn_Clear.Click += new EventHandler(this.ClearGrid);

И так далее для каждого события. (ClearGrid является гипотетико - не один вы уже реализовали.) Это должно конденсироваться источник совсем немного. Вы можете потерять некоторые из вариантов визуальной студии навигации; ИМО это стоит для более чистого кода.

Да, и вы неправильно написали GetSelecetdOrgId :)

2
ответ дан 24 июня 2011 в 01:06 Источник Поделиться