Solved

DataGrid DropDownList with Boolean Values

Posted on 2004-09-12
12
2,059 Views
Last Modified: 2008-02-01
I have a DataGrid and need to add a DropDownList that displays Active and Inactive with the appropriate boolean values of True and False.

I was able to add the following using TemplateColumns

<asp:DropDownList runat="server" id="ddlActive" AutoPostBack="False" DataTextField='' DataValueField=''>
   <asp:ListItem Value="True">Active</asp:ListItem>
   <asp:ListItem Value="False">Inactive</asp:ListItem>
</asp:DropDownList>

Now how to I bind the dropdownlist above when I go to the edit mode of the datagrid the database field is "Active" which is an Access Table Boolean using True and False.

Thanks!

Also looking for good articles on build once use again Datagrid solutions. I found one on SitePoint and 4GuysFromRolla but those leave a few details out.
0
Comment
Question by:brian2k1
  • 4
  • 4
  • 3
12 Comments
 
LVL 10

Accepted Solution

by:
jnhorst earned 300 total points
ID: 12041428
Use the OnItemDataBound event like this:

private void grdName_ItemDataBound(object senser, e DataGridItemEventArgs)
{
     if (e.Item.ItemType != ListItemType.Header && e.Item.ItemType != ListItemType.Footer)
     {
          // get dropdown list from column.  x=the column index.
          DropDownList ddl = (DropDownList)e.Item.Cells[x].FindControl("ddlActive");

          // check its value.
          if (Convert.ToBoolean(ddl.SelectedItem.Value))
          {
               // the active option was selected.  here is where you would do whatever you need to do for this item.
               // you can resolve controls in other TemplateColumns by referring to the column index like the resolution
               // of the dropdown list above.  Just make sure to give all controls an id="..." attribute so FindControl() will find it.
          }
     }
}

John
0
 
LVL 10

Expert Comment

by:jnhorst
ID: 12041431
Also, for great ASP.NET controls across the board, including a great data grid, see:

http://www.infragistics.com

John
0
 
LVL 1

Author Comment

by:brian2k1
ID: 12041557
jnhorst - I've tried the Infragistics controls and they are very complex to implement and EXPENSIVE! I'm waiting for ASP.NET v2.0 which will be easier to use than current datagrid. Do you work for Infragistics or something?

I don't think you answer is what I'm looking for, but then again I don't use C# at the moment and I may be not understanding your solution.

I'm looking for something in VB.NET to select the proper listitem when it switches to Edit mode.

I appreciate the help though.
0
 
LVL 8

Assisted Solution

by:boulder_bum
boulder_bum earned 200 total points
ID: 12041769
OnItemDataBound is definately the way to go, there were just a few bits of information missing. I'm assuming you're using the EditItemTemplate for the DropDownList. Here's what the code might look like in VB (untested, but it will give you the idea)

Private Sub DataGrid1_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles DataGrid1.ItemDataBound
        'if edit mode
        If e.Item.ItemType = ListItemType.EditItem Then
            'this will be the indes of the column you want to extract the value from (the "active" column)
            Dim columnIndex As Integer = 2

            'get boolean value from data source
            Dim active As Boolean = (CType(e.Item.DataItem, DataRowView)).Row.ItemArray(columnIndex)

            'set cell and control indices. let's call them "x" and "y"

            'now we can communicate with the edit control
            'let's find the appropriate value and "select" it
            Dim ddl As DropDownList = _
                CType(e.Item.Cells(x).Controls(y), DropDownList).Items.FindByValue(active.ToString()).Selected = True
        End If
End Sub

Then, in the EditCommand for the grid, you'd re-bind the grid after setting the EditItemIndex. Note that you will need to reset the index to -1 and rebind to end edit mode:

Private Sub DataGrid1_EditCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) Handles DataGrid1.EditCommand
        DataGrid1.EditItemIndex = e.Item.ItemIndex
        BindYourGrid()
End Sub
0
 
LVL 1

Author Comment

by:brian2k1
ID: 12041873
I wish I could figure out either of your solutions but they don't make me understand what is going on. I just want to select the appropriate listitem when I go into EditMode. I tried your VB solution and it gave me an error on the last line which, because of my lack of understanding, I could not resolve.

Error:
Value of type 'Boolean' cannot be converted to 'System.Web.UI.WebControls.DropDownList'.

I thought this would be a simple solution it sure seems more complicated than I expected for .NET code.

In case I've not made my question clear I can already get the selected value when I go to update the database. Now I just need to set the proper listitem when the edit button is pressed and the datagrid switches to the edit template.

Thanks for all the help maybe I'll figure it out with a few more tips.
0
Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

 
LVL 1

Author Comment

by:brian2k1
ID: 12041930
One Working Solution I found, answer point given to person(s) who can simplify this even more.

Function GetActiveIndex(ByVal Active As String) As Integer
        If Active = "True" Then
            Return 0
        Else
            Return 1
        End If
End Function

<asp:DropDownList runat="server" id="Active" AutoPostBack="False"
SelectedIndex='<%# GetActiveIndex(Container.DataItem("Active"))%>'>
      <asp:ListItem Value="True">Active</asp:ListItem>
      <asp:ListItem Value="False">Inactive</asp:ListItem>
</asp:DropDownList>

This works great and is very simple to implement. However I'm curious if the function call is neccessary at all. I'm slowly switching from AsP to .NET and it is these simple things that slow me down.
0
 
LVL 8

Expert Comment

by:boulder_bum
ID: 12042004
Selecting the appropriate ListItem after the "Edit" button is pressed is pretty easy (you have an Edit/Update/Cancel column added in your grid, right?).

Private Sub DataGrid1_EditCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) Handles DataGrid1.EditCommand
        DataGrid1.EditItemIndex = e.Item.ItemIndex
        BindYourGrid()
End Sub

I'm still a little unclear on what you eventually want to do after you've set the appropriate item to edit mode, but the above code block will be a good start.
0
 
LVL 10

Expert Comment

by:jnhorst
ID: 12044341
You've got a datalist that shows records from a table in Access and one of the fields has Active or Inactive.  You show that Active/Inactive in a dropdpwn. When you click the edit link in the list item, you want to do something in particular.  That something is not clear.  Help us understand what you want to do when the edit link is clicked in the item.

John
0
 
LVL 8

Expert Comment

by:boulder_bum
ID: 12049175
Meaning no disrespect, we've given him the information appropriate for the question (several different ways), he just doesn't know enough about what he's doing to understand the answer.

I'd be willing to help further but if points must be refunded it's cool.
0
 
LVL 1

Author Comment

by:brian2k1
ID: 12050087
boulder_bum:

you did not answer the question. I answered the question and eventhough I have unlimited points to give away. I'm not giving them to non-answers. Administrator it is very simple. Read my original question. Then read the solution I found on my own. The truth of this particular q&a on EE will be clear. I'm not stingy with points or positive feedback for those who take the time to ready and understand a question before giving out of scope answers. Both answers provided here were out of scope of my question as illustrated by my own solution.
0
 
LVL 8

Expert Comment

by:boulder_bum
ID: 12051224
"you did not answer the question."

Brian.

Please note that I am just trying to help, but I will point out that you just did declaritively what jnhorst and I demonstrated with the ItemDataBound event, which is to use the DataItem for the particular row to retrieve relevant data and set the selection of the DropDownList.

Container.DataItem("Active")
        is similar to
(CType(e.Item.DataItem, DataRowView)).Row.ItemArray(columnIndex)

While a fine solution really, some (like Microsoft) would shy away from the approach you used because the alternative tends to be a cleaner separation of logic and UI which allows for things like easier debugging. For example, what would you do if you wanted to examine some other field in the row you are binding to? With the markup-based declarative approach you'd be hosed, but the alternative gives you references to everything that's happening during the bind.

That said, I guess there's more than one way to skin a cat, and at least you got it working.

'All the best.



0

Featured Post

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

Suggested Solutions

I recently went through the process of creating a Calendar Control of events with the basis of using a database to keep track of the dates that are selectable, one requirement was to have the selected date pop-up in a simple lightbox.  At first this…
Introduction This article shows how to use the open source plupload control to upload multiple images. The images are resized on the client side before uploading and the upload is done in chunks. Background I had to provide a way for user…
It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…

706 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

12 Experts available now in Live!

Get 1:1 Help Now