?
Solved

Populate DataGrid with results based on DropDownList selection

Posted on 2005-03-30
7
Medium Priority
?
830 Views
Last Modified: 2010-04-16
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
Comment
Question by:simonm_jp
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
7 Comments
 

Author Comment

by:simonm_jp
ID: 13668678
Sorry, DropDownList appears in HTML as follows:

<asp:dropdownlist id="SelectStatus" runat="server" AutoPostBack="True" OnSelectedIndexChanged="SelectStatus_SelectedIndexChanged"></asp:dropdownlist>
0
 
LVL 13

Expert Comment

by:dungla
ID: 13668728
Move BindGrid in method Page_Load to line below PopulateStatus();  in if not post back.
0
 

Author Comment

by:simonm_jp
ID: 13668775
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.

 

Author Comment

by:simonm_jp
ID: 13668792
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
 
LVL 13

Accepted Solution

by:
dungla earned 2000 total points
ID: 13669347
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
 

Author Comment

by:simonm_jp
ID: 13678151
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
 
LVL 13

Expert Comment

by:dungla
ID: 13704150
As far as i know, it is impossible
0

Featured Post

On Demand Webinar: Networking for the Cloud Era

Ready to improve network connectivity? Watch this webinar to learn how SD-WANs and a one-click instant connect tool can boost provisions, deployment, and management of your cloud connection.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Article by: Ivo
C# And Nullable Types Since 2.0 C# has Nullable(T) Generic Structure. The idea behind is to allow value type objects to have null values just like reference types have. This concerns scenarios where not all data sources have values (like a databa…
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
In this video you will find out how to export Office 365 mailboxes using the built in eDiscovery tool. Bear in mind that although this method might be useful in some cases, using PST files as Office 365 backup is troublesome in a long run (more on t…
In this video, Percona Solutions Engineer Barrett Chambers discusses some of the basic syntax differences between MySQL and MongoDB. To learn more check out our webinar on MongoDB administration for MySQL DBA: https://www.percona.com/resources/we…
Suggested Courses

764 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question