add default value to dropdownlist in gridview

Posts   
 
    
like2175
User
Posts: 83
Joined: 27-Mar-2006
# Posted on: 05-Jul-2006 09:32:51   

I am binding my ddl in an asp.net gridview (VS 2005)


<ItemTemplate>
            <asp:DropDownList ID="ddlCertificateTypeID" Selectedvalue='<%# Eval("CertificateTypeID")%>' runat="server" DataSource='<%# CertificateTypes() %>'
              DataTextField="CertificateType" DataValueField="CertificateTypeID" Enabled="false" >
            </asp:DropDownList>


.
.
.

 Public ReadOnly Property CertificateTypes() As CertificateTypeCollection
    ' 
    ' All Certificate Types 
    '
    Get
      Dim certColl As CertificateTypeCollection
      certColl = CertificateTypeEntity.GetCertificateTypeCollection

      Return certColl

    End Get

  End Property

I now want to add a "[No value selected yet]" to the top of the dropdownlist that corresponds to null in the backend database.

I have done this before, when I am dealing with just one dropdown on a form.



Const COMBO_NULL As String = "[No value selected yet]"

...

ddlStatus1.DataSource = PsStatusEntity.GetStatusCollection
ddlStatus1.DataValueField = PsStatusFieldIndex.StatusId.ToString
ddlStatus1.DataTextField = PsStatusFieldIndex.StatusDescr.ToString
ddlStatus1.DataBind()
ddlStatus1.Items.Insert(0, COMBO_NULL)

Can anyone help me do this "for the multiple entries in the datagrid?

Otis avatar
Otis
LLBLGen Pro Team
Posts: 39590
Joined: 17-Aug-2003
# Posted on: 05-Jul-2006 11:55:02   

From my bare head I'd say add an option tag to the HTML.

Frans Bouma | Lead developer LLBLGen Pro
Jez
User
Posts: 198
Joined: 01-May-2006
# Posted on: 05-Jul-2006 12:58:10   

You could bind to the RowDataBound event for the gridview and programatically manipulate the dropdownlist for that particular row.

You should be able to do something like:


protected void myGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)    
    {
        //Gets first control in the first cell.
        DropDownList myDropDown = (DropDownList)e.Row.Cells[0].Controls[0]; 
        myDropDown.Items.Insert(0, "[No items selected"]);
    }
}

It should be straightforward to convert the above to VB. I haven't actually tested this so it may need some tweaks simple_smile

like2175
User
Posts: 83
Joined: 27-Mar-2006
# Posted on: 21-Nov-2007 09:45:15   

Better solution:

You can add items to your ddl by creating a <asp:ListItem> entry as follows:

 <asp:DropDownList ID="cboRepGroup" runat="server" AutoPostBack="True" DataSource='<%#ReportGroups%>'
      DataTextField="GroupName" DataValueField="AppReportGroupID" AppendDataBoundItems="true">
      <asp:ListItem Text="--Select--" Value=""></asp:ListItem>
    </asp:DropDownList>

Make sure you

AppendDataBoundItems="true"

Simple! wink