Solved

Fill DropDownList dynamically in editable DataGrid

Posted on 2004-09-22
9
12,239 Views
Last Modified: 2007-12-19
I am working with .NET ASP QuickStart tutorials. To see the sample I am talking about, please open this page:

http://samples.gotdotnet.com/quickstart/aspplus/doc/webdataaccess.aspx

Click link "DataGrid8.aspx [View Source]" and click link "CS\datagrid8.aspx". This sample shows how to use editable DataGrid. One of DataGrid columns is State which is edited as DropDownList. Appropriate code fragments from the file http://samples.gotdotnet.com/quickstart/util/srcview.aspx?path=/quickstart/aspplus/samples/webforms/data/datagrid8.src&file=CS\datagrid8.aspx&font=3

public Hashtable StateIndex;

...
         StateIndex = new Hashtable();
         StateIndex["CA"] = 0;
         StateIndex["IN"] = 1;
         StateIndex["KS"] = 2;
         StateIndex["MD"] = 3;
         StateIndex["MI"] = 4;
         StateIndex["OR"] = 5;
         StateIndex["TN"] = 6;
         StateIndex["UT"] = 7;
...
    public int GetStateIndex(String stateName)
    {
        if (StateIndex[stateName] != null)
            return (int)StateIndex[stateName];
        else
            return 0;
    }

...
        <asp:TemplateColumn HeaderText="state" SortExpression="state">
          <ItemTemplate>
            <asp:Label runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "state") %>'/>
          </ItemTemplate>
          <EditItemTemplate>
            <asp:DropDownList runat="server" SelectedIndex='<%# GetStateIndex(DataBinder.Eval(Container.DataItem, "state").ToString()) %>' id="edit_State">
                  <asp:ListItem>CA</asp:ListItem>
                  <asp:ListItem>IN</asp:ListItem>
                  <asp:ListItem>KS</asp:ListItem>
                  <asp:ListItem>MD</asp:ListItem>
                  <asp:ListItem>MI</asp:ListItem>
                  <asp:ListItem>OR</asp:ListItem>
                  <asp:ListItem>TN</asp:ListItem>
                  <asp:ListItem>UT</asp:ListItem>
            </asp:DropDownList>
          </EditItemTemplate>
        </asp:TemplateColumn>
 
Both DropDownList and HashTable used to set initial selection are filled using hard-coded values. I want to change this sample and to fill DropDowmList dynamically from database. List of states may be read from database using the following SQL command:

select distinct State from Authors

In Page_Load I can read values from database table and keep them in HashTable or ArrayList. How can I populate dynamically DropDownList with these values? I tried to fill them using code inside asp:DropDownList tag, but compiler gives error:
Code blocks are not supported in this context
0
Comment
Question by:AlexFM
  • 4
  • 4
9 Comments
 
LVL 15

Assisted Solution

by:praneetha
praneetha earned 250 total points
Comment Utility
do it in the itemDataBound event of a datagrid


if(e.Item.ItemType==ListItemType.EditItem && e.Item.ItemType != ListItemType.Header && e.Item.ItemType != ListItemType.Footer)
                  {
                        System.Web.UI.HtmlControls.HtmlSelect dList=(HtmlSelect)e.Item.FindControl("ddlColor");
dList.DataSource=ArrayList;
dlist.databind();                        
}

hope that works
0
 
LVL 3

Accepted Solution

by:
sajay earned 250 total points
Comment Utility
You should cast the control to a drop down list and not an HTML select .. or what ever control you have use in the item template with the correct id

///event handler for the datagrid item databound
private void MyDataGrid_ItemDataBound(object sender,DataGridItemEventArgs e)
{

          if(e.Item.ItemType==ListItemType.EditItem && e.Item.ItemType != ListItemType.Header && e.Item.ItemType != ListItemType.Footer)
                         {
                              DropDownList dList=(DropDownList)e.Item.FindControl("edit_State");
                              dList.DataSource=ArrayList;
                              dlist.databind();                    
                              //you can set any property like selected item etc here.. or add new items here.

                         }

}
0
 
LVL 48

Author Comment

by:AlexFM
Comment Utility
Thank you very much.
By the way, I cannot set SelectedItem inside of MyDataGrid_ItemDataBound (Why? I don't know). But I found solution of this problem and this is my code:

        public ArrayList States;

        private void Page_Load(object sender, System.EventArgs e)
        {
            myConnection = new SqlConnection("server=(local)\\NetSDK;database=pubs;Integrated Security=SSPI");

            if (!IsPostBack)
                BindGrid();

            States = new ArrayList();
            string mySelectQuery = "select distinct State from Authors";
            SqlCommand myCommand = new SqlCommand(mySelectQuery,myConnection);
            myConnection.Open();
            SqlDataReader myReader;
            myReader = myCommand.ExecuteReader();

            while (myReader.Read())
            {
                States.Add(myReader.GetString(0));
            }

            myReader.Close();
            myConnection.Close();
        }

        private void MyDataGrid_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
        {
            if ( e.Item.ItemType != ListItemType.EditItem )
                return;

            Control c = e.Item.FindControl("edit_State");

            if ( c == null )
                return;

            DropDownList dList=(DropDownList)c;

            dList.DataSource = States;
            dList.DataBind();
        }

        public int GetStateIndex(String stateName)
        {
            System.Collections.IEnumerator myEnumerator = States.GetEnumerator();
            int i = 0;

            while ( myEnumerator.MoveNext() )
            {
                if ( myEnumerator.Current.ToString() == stateName )
                {
                    return i;
                }

                i++;
            }

            return 0;
        }


<asp:DropDownList runat="server" id="edit_State" SelectedIndex='<%# GetStateIndex(DataBinder.Eval(Container.DataItem, "state").ToString()) %>' />
0
 
LVL 48

Author Comment

by:AlexFM
Comment Utility
I want to ask additional question, I am sure you can answer it. After getting the answer I will open "Points for..." question.

Suppose I want to set SelectedIndex directly in MyDataGrid_ItemDataBound. It should look like this:

        private void MyDataGrid_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
        {
            if ( e.Item.ItemType != ListItemType.EditItem )
                return;

            Control c = e.Item.FindControl("edit_State");

            if ( c == null )
                return;

            DropDownList dList=(DropDownList)c;

            dList.DataSource = States;
            dList.DataBind();

            System.Collections.IEnumerator myEnumerator = States.GetEnumerator();
            int i = 0;

            while ( myEnumerator.MoveNext() )
            {
                if ( myEnumerator.Current.ToString() == ??? )     // what should I write here instead of ???
                {
                    dList.SelectedIndex = i;
                    break;
                }

                i++;
            }
        }

How can I get recordset value to set current selection? Recordset contains string like "IN", "CA" etc. In my current solution it is extracted using
DataBinder.Eval(Container.DataItem, "state").ToString()
and passed to GetStateIndex function. How can I access this value directly from MyDataGrid_ItemDataBound function?
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 3

Expert Comment

by:sajay
Comment Utility
now .. as far as i get your code.. its to select a state.. depending on the value selected. right

now if your using v1.1 of the framework .. in asp.net you can do this

///event handler for the datagrid item databound
private void MyDataGrid_ItemDataBound(object sender,DataGridItemEventArgs e)
{

          if(e.Item.ItemType==ListItemType.EditItem && e.Item.ItemType != ListItemType.Header && e.Item.ItemType != ListItemType.Footer)
                         {
                              DropDownList dList=(DropDownList)e.Item.FindControl("edit_State");
                              dList.DataSource=ArrayList;
                              dlist.databind();                    

                              //you can set any property
                               DataRowView drv = e.DataItem;
                               DataRow dr= drv.Row;
                               dlist.SelectedValue = dr["MY_COLUMN_NAME"].ToString()
                         }
}


you can tweak anything you want from the e.DataItem.

this exposese the actual row view object that is bound to the row..
hope this answers your question.
0
 
LVL 3

Expert Comment

by:sajay
Comment Utility
sorry i missed out the casting

DataRowView drv = (DataRowView)e.DataItem

:)
cheers
0
 
LVL 48

Author Comment

by:AlexFM
Comment Utility
System.Web.UI.WebControls.DataGridItemEventArgs' does not contain a definition for 'DataItem

for the line:
DataRowView drv = (DataRowView)e.DataItem;

I am working with VS 2003.
0
 
LVL 3

Expert Comment

by:sajay
Comment Utility
I guess its e.Item.DataItem ..

sorry about that
0
 
LVL 48

Author Comment

by:AlexFM
Comment Utility
0

Featured Post

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

Welcome my friends to the second instalment and follow-up to our Minify and Concatenate Your Scripts and Stylesheets (http://www.experts-exchange.com/Programming/Languages/.NET/ASP.NET/A_4334-Minify-and-Concatenate-Your-Scripts-and-Stylesheets.html)…
More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

743 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

Need Help in Real-Time?

Connect with top rated Experts

8 Experts available now in Live!

Get 1:1 Help Now