• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 833
  • Last Modified:

Populate DataGrid with results based on DropDownList selection

Hi Experts,

I have a page which displays a dropdownlist, followed by a DataGrid with results extracted from a database.  Once the dropdownlist is changed, the results in the datagrid should change to reflect the choice, however, despite my attempts the DropDownList seems to Postback, but not change the results in the DataGrid.

Code is detailed below ... anyone's help would be greatly appreciated.  :)

Sample:  

ASCX Control HTML ....
<table><tr><td><asp:placeholder id="ResultsSpan" runat="server"></asp:placeholder>
<ASP:DATAGRID id="ResultsDataGrid" runat="server" AutoGenerateColumns="True" Width="100%" CssClass="moduleBody" ShowFooter="false" OnPageIndexChanged="myDataGrid_PageChanger" PagerStyle-Mode="NumericPages" PageSize="10" AllowPaging="True" EnableViewState="true" AllowSorting="true" SortCommand="SortGrid">
</ASP:DATAGRID></td></tr></table>

C# Code Behind

public class myDataTest : System.Web.UI.UserControl
      {
            protected System.Web.UI.WebControls.PlaceHolder ResultsSpan;
            protected System.Web.UI.WebControls.DataGrid ResultsDataGrid;
            protected System.Web.UI.WebControls.DropDownList SelectStatus;
            private string status = "Not Selected"

            private void Page_Load(object sender, System.EventArgs e)
            {
                  if(Page.IsPostBack == false)
                  {
                          PopulateStatus();      
                  }
                  BindGrid();
            }

            public void SelectStatus_SelectedIndexChanged(object sender, System.EventArgs e)
            {
                  string status = SelectStatus.SelectedItem.Value;
                  BindGrid();
            }

            public void BindGrid(string inStatus)
            {
                  //get a dataset from component
                  myApplication.ContactDB db = myApplication.ContactDB();
                                                DataSet ds = new DataSet();
                  ds = db.GetResults();

                  DataView view = new DataView(ds.Tables[0]);

                  //Sorting criteria
                  view.Sort = SortField;  if (!SortAscending)  { view.Sort += " DESC";  }

                  ResultsDataGrid.DataSource = view;
                  ResultsDataGrid.DataBind();
            }

            // using ViewState for SortField property
            string SortField
            {       get
                  {
                        object o = ViewState["SortField"];
                        if (o == null) { return String.Empty; }
                        return (string)o;
                  } set
                  {
                        if (value == SortField)
                        {      //if ascending change to descending or vice versa.
                              SortAscending = !SortAscending; }
                        ViewState["SortField"] = value;
                  }
            }

            // using ViewState for SortAscending property
            bool SortAscending
            {
                  get
                  {
                        object o = ViewState["SortAscending"];
                        if (o == null) { return true; } return (bool)o;
                  }
                  set { ViewState["SortAscending"] = value; }
            }

            protected void SortGrid(Object src, DataGridSortCommandEventArgs e)
            {
                  ResultsDataGrid.CurrentPageIndex = 0;
                  SortField = e.SortExpression;    
                  BindGrid();
            }

            protected void myDataGrid_PageChanger(Object src, DataGridPageChangedEventArgs e)
            {
                  ResultsDataGrid.CurrentPageIndex = e.NewPageIndex;
                  BindGrid();
            }

            public DataSet PopulateStatus()
            {
                  DataSet ds = new DataSet();
                  
                  myApplication.ContactDB db = new myApplication.ContactDB();
                  
                  SelectStatus.DataSource = db.GetStatusList();
                  SelectStatus.DataTextField = "STATUS";
                  SelectStatus.DataValueField = "STATUS";
                  SelectStatus.DataBind();
                  return ds;
            }

            #region Web Form Designer generated code
            override protected void OnInit(EventArgs e)
            {
                  //
                  // CODEGEN: This call is required by the ASP.NET Web Form Designer.
                  //
                  InitializeComponent();
                  base.OnInit(e);
            }
            
            private void InitializeComponent()
            {
                  this.SelectStatus.SelectedIndexChanged += new System.EventHandler(this.SelectStatus_SelectedIndexChanged);
                  this.Load += new System.EventHandler(this.Page_Load);

            }
            #endregion
      }
}


0
simonm_jp
Asked:
simonm_jp
  • 4
  • 3
1 Solution
 
simonm_jpAuthor Commented:
Sorry, DropDownList appears in HTML as follows:

<asp:dropdownlist id="SelectStatus" runat="server" AutoPostBack="True" OnSelectedIndexChanged="SelectStatus_SelectedIndexChanged"></asp:dropdownlist>
0
 
dunglaCommented:
Move BindGrid in method Page_Load to line below PopulateStatus();  in if not post back.
0
 
simonm_jpAuthor Commented:
Hi Dungla,
Thanks for the comment ... I moved the BindGrid as per your suggestion, but there is no change.  The page initially loads ok, and the Datagrid contains results for the default selection ("Not Selected"). But when the DropDownList is changed to one of the other options in the DropDownList, the page flickers, then returns to the default selection, causing the DataGrid to once again display the same results.
Thanks,
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
simonm_jpAuthor Commented:
Note one other correction to BindGrid() as follows:

 public void BindGrid()  // removed the parameter
          {
               //get a dataset from component
               myApplication.ContactDB db = myApplication.ContactDB();
               DataSet ds = new DataSet();
               ds = db.GetResults(status);        // status passed to component to define results.
               //.....
          }
0
 
dunglaCommented:
Did you manage your usercontrol in ASPX page? Here is what I do, already test.

namespace WebApp
{
      using System;
      using System.Data;
      using System.Drawing;
      using System.Web;
      using System.Web.UI.WebControls;
      using System.Web.UI.HtmlControls;
      using System.Data.OleDb;

      /// <summary>
      ///            Summary description for MyControl.
      /// </summary>
      public class MyControl : System.Web.UI.UserControl
      {
            protected System.Web.UI.WebControls.DropDownList ddlPub;
            protected System.Web.UI.WebControls.DataGrid dgrdTitle;

            private const string CONNECTION_STRING = "Provider=SQLOLEDB;Data Source=(local);User ID=sa;Password=sa;Initial Catalog=pubs;";

            private void Page_Load(object sender, System.EventArgs e)
            {
                  if (!IsPostBack)
                  {
                        PopulatePublisher();
                        BindGrid(1);
                  }
            }

            #region Web Form Designer generated code
            override protected void OnInit(EventArgs e)
            {
                  //
                  // CODEGEN: This call is required by the ASP.NET Web Form Designer.
                  //
                  InitializeComponent();
                  base.OnInit(e);
            }
            
            /// <summary>
            ///            Required method for Designer support - do not modify
            ///            the contents of this method with the code editor.
            /// </summary>
            private void InitializeComponent()
            {
                  this.ddlPub.SelectedIndexChanged += new System.EventHandler(this.ddlPub_SelectedIndexChanged);
                  this.Load += new System.EventHandler(this.Page_Load);

            }
            #endregion

            private void PopulatePublisher()
            {
                  OleDbConnection cn = null;
                  try
                  {
                        cn = new OleDbConnection(CONNECTION_STRING);
                        OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT pub_id, pub_name FROM publishers", cn);
                        DataTable tblData = new DataTable("publishers");
                        adapter.Fill(tblData);
                        ddlPub.DataSource = tblData;
                        ddlPub.DataTextField = "pub_name";
                        ddlPub.DataValueField = "pub_id";
                        ddlPub.DataBind();
                  }
                  catch (OleDbException ex)
                  {
                        Response.Write(ex.Message);
                  }
                  finally
                  {
                        if (cn != null)
                        {
                              if (cn.State != ConnectionState.Closed)
                              {
                                    cn.Close();
                              }
                        }
                  }
            }
            private void BindGrid(int pintPubID)
            {
                  OleDbConnection cn = null;
                  try
                  {
                        cn = new OleDbConnection(CONNECTION_STRING);
                        OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM titles WHERE pub_id=" + pintPubID, cn);
                        DataTable tblData = new DataTable("titles");
                        adapter.Fill(tblData);
                        dgrdTitle.DataSource = tblData;
                        dgrdTitle.DataBind();
                  }
                  catch (OleDbException ex)
                  {
                        Response.Write(ex.Message);
                  }
                  finally
                  {
                        if (cn != null)
                        {
                              if (cn.State != ConnectionState.Closed)
                              {
                                    cn.Close();
                              }
                        }
                  }
            }

            private void ddlPub_SelectedIndexChanged(object sender, System.EventArgs e)
            {
                  BindGrid(int.Parse(ddlPub.SelectedValue.ToString()));
            }
      }
}
0
 
simonm_jpAuthor Commented:
Hi Dungla,

Thanks for your input.  :)

After much troubleshooting, I have found the error was caused by another .ascx which was in loaded into the same page.  In the other .ascx it contained a Form, which posted to a different URL, and I have found that once I removed the Form element, everything works fine.  My DataGrid now sorts, pages, and can be filtered using a DropDownList.

Is there a rule with ASP.NET that all forms postback to the same page, or a restriction on the number of Form elements allowed on a Page?

Thanks,
0
 
dunglaCommented:
As far as i know, it is impossible
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

  • 4
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now