Solved

Fill DropDownList dynamically in editable DataGrid

Posted on 2004-09-22
9
12,248 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
Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

 
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
 
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

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Get id from json Data with NewtonSoft 3 49
ASP.NET 5 Templates 2 78
start a process from a service 3 21
VB.Net - MemoryMappedFiles - Confirm receipt 2 18
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)…
In my previous two articles we discussed Binary Serialization (http://www.experts-exchange.com/A_4362.html) and XML Serialization (http://www.experts-exchange.com/A_4425.html). In this article we will try to know more about SOAP (Simple Object Acces…
Two types of users will appreciate AOMEI Backupper Pro: 1 - Those with PCIe drives (and haven't found cloning software that works on them). 2 - Those who want a fast clone of their boot drive (no re-boots needed) and it can clone your drive wh…
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …

786 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