Solved

Fill DropDownList dynamically in editable DataGrid

Posted on 2004-09-22
9
12,245 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
ID: 12124535
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
ID: 12130012
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
ID: 12131420
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
ID: 12131513
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
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 
LVL 3

Expert Comment

by:sajay
ID: 12136900
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
ID: 12136918
sorry i missed out the casting

DataRowView drv = (DataRowView)e.DataItem

:)
cheers
0
 
LVL 48

Author Comment

by:AlexFM
ID: 12140663
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
ID: 12149600
I guess its e.Item.DataItem ..

sorry about that
0
 
LVL 48

Author Comment

by:AlexFM
ID: 12150484
0

Featured Post

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

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

A basic question.. “What is the Garbage Collector?” The usual answer given back: “Garbage collector is a background thread run by the CLR for freeing up the memory space used by the objects which are no longer used by the program.” I wondered …
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…
This Micro Tutorial will give you a basic overview how to record your screen with Microsoft Expression Encoder. This program is still free and open for the public to download. This will be demonstrated using Microsoft Expression Encoder 4.
This Micro Tutorial hows how you can integrate  Mac OSX to a Windows Active Directory Domain. Apple has made it easy to allow users to bind their macs to a windows domain with relative ease. The following video show how to bind OSX Mavericks to …

867 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

15 Experts available now in Live!

Get 1:1 Help Now