Solved

Fill DropDownList dynamically in editable DataGrid

Posted on 2004-09-22
9
12,259 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
[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
  • 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
Setting up LaraDock for Laravel

Learn how to set up LaraDock in a Laravel project - LaraDock gives us an easy way to run a Laravel application using Docker in a single command.

 
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

Quiz: What Do These Organizations Have In Common?

Hint: Their teams ended up taking quizzes, too.

Question has a verified solution.

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

This article describes relatively difficult and non-obvious issues that are likely to arise when creating COM class in Visual Studio and deploying it by professional MSI-authoring tools. It is assumed that the reader is already familiar with the cla…
Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
There are cases when e.g. an IT administrator wants to have full access and view into selected mailboxes on Exchange server, directly from his own email account in Outlook or Outlook Web Access. This proves useful when for example administrator want…
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…

623 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