Solved

Fill DropDownList dynamically in editable DataGrid

Posted on 2004-09-22
9
12,251 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
How Do You Stack Up Against Your Peers?

With today’s modern enterprise so dependent on digital infrastructures, the impact of major incidents has increased dramatically. Grab the report now to gain insight into how your organization ranks against your peers and learn best-in-class strategies to resolve incidents.

 
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

Resolve Critical IT Incidents Fast

If your data, services or processes become compromised, your organization can suffer damage in just minutes and how fast you communicate during a major IT incident is everything. Learn how to immediately identify incidents & best practices to resolve them quickly and effectively.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
How do you do a one to many list in .NET CORE? 2 37
.NET 2008 VB and C# 6 39
DataTables + iCheck + pagination Issue 2 47
VB.NET 2008 Winforms Signing 13 33
In my previous article (http://www.experts-exchange.com/Programming/Languages/.NET/.NET_Framework_3.x/A_4362-Serialization-in-NET-1.html) we saw the basics of serialization and how types/objects can be serialized to Binary format. In this blog we wi…
Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
Microsoft Active Directory, the widely used IT infrastructure, is known for its high risk of credential theft. The best way to test your Active Directory’s vulnerabilities to pass-the-ticket, pass-the-hash, privilege escalation, and malware attacks …
I've attached the XLSM Excel spreadsheet I used in the video and also text files containing the macros used below. https://filedb.experts-exchange.com/incoming/2017/03_w12/1151775/Permutations.txt https://filedb.experts-exchange.com/incoming/201…

821 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