Problem filling a DropDownList in a FormView programmatically

Last post 04-21-2009 12:12 PM by Mark_E. 9 replies.

Sort Posts:

  • Problem filling a DropDownList in a FormView programmatically

    04-20-2009, 8:04 AM
    • Member
      13 point Member
    • Mark_E
    • Member since 04-20-2009, 7:38 AM
    • Posts 23

    Hi, this is my first post on this forum and I'm new to ASP.NET devolpment. So, my question may be pretty daft.

    I'm trying to fill a DropDownList which I have on a FormView in the EditTemplate view.
    The first time I fill it, it works ok. If I move to the next FormView page it fails to fill the DropDownList even though my FillDropDownList method is called and executes succesfully (or appears to).


    Here is the code:

    // Code Start ---------------------------------------------------------------------
                
    // In the FormView Load event I attempt to fill the DropDownList

        protected void fvAccFilter1_Load(object sender, EventArgs e)
        {
            //if (!IsPostBack)
            //{
                FillDropDownList(GetDropDownList(fvAccFilter1, "ddlAccCat"), "Incident", "IncidentID", "NAME", "NAME", true);
           
            //}
        }
       
    // This method retrieves the DropDownList I want to fill from a FormView

        protected DropDownList GetDropDownList(FormView formView, String name)
        {
            DropDownList ddList = null;

            try
            {
                ddList = (DropDownList)formView.FindControl(name);
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
           
            return ddList;
        }

    // This method fills the DropDownList with data from a database and optionally adds
    // a blank entry before the data from the database. (The main reason for doing this)

        protected void FillDropDownList(DropDownList ddList, String tableName, String dataField,
                                        String listField, String orderByField, bool addBlank)
        {
            if (ddList != null)
            {
                SqlConnection connection = null;

                try
                {
                    String connStr = dsAccFilter1.ConnectionString;

                    connection = new SqlConnection(connStr);

                    DataTable dtable = new DataTable();

                    String SQL = "SELECT " + dataField + ", " + listField +
                                " FROM " + tableName +
                                " ORDER BY " + orderByField;

                    SqlDataAdapter adapter = new SqlDataAdapter(SQL, connection);

                    connection.Open();

                    adapter.Fill(dtable);

                    ddList.ClearSelection();
                    ddList.Items.Clear();

                    if (addBlank)
                    {
                        ListItem item = new ListItem("", "0");

                        ddList.Items.Add(item);
                    }

                    int count = dtable.Rows.Count;

                    for (int i = 0; i < count; i++)
                    {
                        ListItem item = new ListItem(dtable.Rows[i][1].ToString(), dtable.Rows[i][0].ToString());

                        ddList.Items.Add(item);
                    }
                }
                catch (Exception ex)
                {
                    Response.Write(ex.Message);
                }
                finally
                {
                    connection.Close();
                }
            }
            else
                Response.Write("ERROR: ddList == null");
        }

    // Code End -----------------------------------------------------------------------

    Any help would be very welcome,
    Thanks,
    Mark

     

  • Re: Problem filling a DropDownList in a FormView programmatically

    04-20-2009, 2:20 PM
    • Member
      13 point Member
    • Mark_E
    • Member since 04-20-2009, 7:38 AM
    • Posts 23

    Hi again, I've simplified the code as much as I can here. But I don't really think it's a problem with the code, maybe a problem with the way I think the FormView works.

    Anyway, the problem is that the following code successfully fills a DropDownList on a FormView the first time it is called but not subsequent calls via the 'next page' formview link. (I hope that makes sense, please say so if it doesn't)


    // Code Start ---------------------------------------------------------------------
                
    // In the FormView Load event I attempt to fill the DropDownList

        protected void fvAccFilter1_Load(object sender, EventArgs e)
        {
            //if (!IsPostBack)
            //{                                       
           
                DropDownList ddl = GetDropDownList(fvAccFilter1, "ddlAccCat");
               
                FillDropDownList(ddl);
           
            //}
        }
       
    // This method retrieves the DropDownList I want to fill from a FormView

        protected DropDownList GetDropDownList(FormView formView, String name)
        {
            DropDownList ddList = null;

            try
            {
                ddList = (DropDownList)formView.FindControl(name);
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
           
            return ddList;
        }

    // This method fills the DropDownList.

        protected void FillDropDownList(DropDownList ddList)
        {
            if (ddList != null)
            {
                ddList.Items.Clear();

                for (int i = 0; i < 4; i++)
                {
                    ListItem item = new ListItem("Item" + i.ToString(), i.ToString());

                    ddList.Items.Add(item);
                }
            }
            else
                Response.Write("ERROR: ddList == null - ");
        }
                      
    // Code End -----------------------------------------------------------------------

    Thanks (getting pretty desperate!),
    Mark

  • Re: Problem filling a DropDownList in a FormView programmatically

    04-20-2009, 2:27 PM
    • Member
      66 point Member
    • jrossh21
    • Member since 03-04-2008, 7:06 PM
    • Posts 110
    Can we see your aspx page? If "AutoPostBack" isn't set, set it to true to see if that helps any.
  • Re: Problem filling a DropDownList in a FormView programmatically

    04-20-2009, 3:07 PM
    • Member
      13 point Member
    • Mark_E
    • Member since 04-20-2009, 7:38 AM
    • Posts 23

    Hi, is this the bit you mean? The asp code for the DropDwonList?

    <td>
        <asp:DropDownList ID="ddlAccCat" runat="server" Width="124px"
        AutoPostBack="True">
        </asp:DropDownList>
    </td>                                                          

    If not, which bit do you mean because it's pretty large?

    Anyway, the AutoPostBack wasn't set to true when you asked but I've now set it to true but it hasn't helped. Any other ideas? Looking at the code, do you think I should be able to do what I'm trying to do? (I'm really, really new to asp.net and web programming in general)

    Thanks,
    Mark

  • Re: Problem filling a DropDownList in a FormView programmatically

    04-20-2009, 3:18 PM
    • Member
      66 point Member
    • jrossh21
    • Member since 03-04-2008, 7:06 PM
    • Posts 110

    Yes, that was the bit of code I was talking about.

    Why aren't you using asp.net's built in feature for populating the dropdownlist? Like this:

    <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" DataSourceID="SqlDataSource1" DataTextField="YEAR" DataValueField="YEAR">
        </asp:DropDownList>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:MyConnection.DbConnection %>"
            SelectCommand="SELECT YEAR FROM REPORT_TABLE ORDER BY YEAR DESC">
        </asp:SqlDataSource>

    You can do this in a gui by going into design mode and clicking on the dropdownlist and a little black arrow in the upper right corner of the dropdownlist will appear - click on it.

  • Re: Problem filling a DropDownList in a FormView programmatically

    04-20-2009, 3:34 PM
    • Member
      13 point Member
    • Mark_E
    • Member since 04-20-2009, 7:38 AM
    • Posts 23

    Hi, thanks for replying again,

    Yes, I do understand that I can do it that way but I need to have an empty ("") list item at the beginning of the list. The DB table I've got to work with doesn't have a 'blank' record and I can't just put one in because it's a live database and I can't muck about with the data like that, unfortunately.

    If you look at my first post in this thread, at the FillDropDownList method you'll see that I add an empty item and the fill the rest of the DDL from a database table.

    For a test I used a DropDownList directly on the page (not in a FormView) and that works perfectly when the page refreshes. I just don't understand why it's not working when it's in a FormView, seems very odd to me.

    Also, why do DropDownLists always load the first item in to the text part automatically? That alaos seems very odd to me. If I could stop that from happening it would be helpfull.

    Thanks,

    Mark

     

  • Re: Problem filling a DropDownList in a FormView programmatically

    04-21-2009, 9:50 AM
    • Member
      66 point Member
    • jrossh21
    • Member since 03-04-2008, 7:06 PM
    • Posts 110

    You can add an extra item in the DDL by that same gui:

    • click on the little black arrow in deisgn mode
    • click on edit items
    • click add
    • fill in the properties for your item
    That might solve your problem about the first item in the text part automatically.
  • Re: Problem filling a DropDownList in a FormView programmatically

    04-21-2009, 10:37 AM
    • Member
      13 point Member
    • Mark_E
    • Member since 04-20-2009, 7:38 AM
    • Posts 23

    Hi again,

    Thanks for not giving up on me, very much appreciated. Maybe I've over egged the new to VS etc. Although I am, I've been programming since about 1990! using borland (duck and cover!) tools and have recently been forced to move to VS by the company I work for. That's not to say I'm not enjoying the experience. The way things work in VS is very often quite different.

    I've already tried your latest suggestion. I added an empty item in the way you describe and then tried to fill the rest from the DB. I have to do that because even though I'm not allowed to alter the contents of the tables the contents can change. So I can't hardwire the list. It gets worse, doesn't it! Anyway, I think the stuff from the DB over wrote anything I added via 'edit items'. At least I think that was the reason, it was one of my first stabs at a solution and I can't quite remember why it didn't work.

    I have discovered a way round this. I've created a user control and put a dropdownlist on it and essential moved the code in my first post to it and tied it all up. And hey presto it's filling the dropdown whenever I move from one page of the formview to another. I've just got to get the rest of the functionality to work now!

    Once again, thanks a lot for your help,

    Mark

     

  • Re: Problem filling a DropDownList in a FormView programmatically

    04-21-2009, 10:55 AM
    Answer
    • Member
      66 point Member
    • jrossh21
    • Member since 03-04-2008, 7:06 PM
    • Posts 110

    I'm sorry my suggestions didn't help you.

    Here's another suggestion that may help you or someone else in the future. Here's a way you can add an item to a DLL: 

    protected void DropDownList1_DataBound(object sender, EventArgs e)
    {
      DropDownList1.Items.Add(new ListItem("ALL", "%"));
    }
    And then add the event to your aspx page like this: 
    <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" DataSourceID="SqlDataSource1" DataTextField="YEAR" DataValueField="YEAR" OnDataBound="DropDownList1_DataBound">
     
  • Re: Problem filling a DropDownList in a FormView programmatically

    04-21-2009, 12:12 PM
    • Member
      13 point Member
    • Mark_E
    • Member since 04-20-2009, 7:38 AM
    • Posts 23

    Well Mr jrossh21, I could kiss you - Ok, I won't!

    That's the answer I wanted all along.

    Even though I tested my user control idea with the test code in my second post I hadn't finished implementing the full solution using the code in post one.

    It turns out that my function GetDropDownList (which I still needed to use) was not returning the correct dropdown when you changed page. So, the formview doesn't work like I thought it did. I don't know why but it just didn't dawn on me that I could use events on controls embedded in a formview.

    Anyway, your last suggestion has done the trick. So my code looks like this now:

        protected void ddlAccCat_DataBound(object sender, EventArgs e)
        {
            FillDropDownList((DropDownList)sender, "Incident", "IncidentID", "NAME", "NAME", true);
        }

    Sender is the dropdown I wanted all along! YIPPEE!, I'm gonna take the rest of the day off and I think you deserve to too.

    Thanks very, very much.
    Mark

Page 1 of 1 (10 items)