Solved

GridView DropDownList DataBind EditItemTemplate Problem - has a SelectedValue which is invalid because it does not exist in the list of items. Parameter name: value

Posted on 2011-03-02
21
2,228 Views
Last Modified: 2012-05-11
I'm having a problem with my dropdownlist.  The problem is that when the edit button is clicked from my gridview and the value isn't in the dropdownlist (then)

I get the following:
System.ArgumentOutOfRangeException: 'DropDownListManufactureYear' has a SelectedValue which is invalid because it does not exist in the list of items.

I want to catch this in a try block but am having problems figuring out which directives to use.  I need to use the FindControl function because the dropdown is only visible after the edit button is clicked.  

I'm not sure how to accomplish this and need some advice.  Please see the below code to get an idea about what I need to accomplish.  The statement in the catch has a red line under 'SelectedValue'.  

Thanks!
protected void GridviewBuses_RowEditing(object sender, GridViewEditEventArgs e)
        {
            try
            {
                FindControl("DropDownListPurchaseYear").DataBind();
            }
            catch (ArgumentOutOfRangeException)
            {
                FindControl("DropDownListPurchaseYear").SelectedValue = "";

            }
        }

Open in new window

0
Comment
Question by:etan08
  • 11
  • 7
  • 3
21 Comments
 
LVL 8

Expert Comment

by:sriggumma
Comment Utility
Is the DropDownList a control in each row of the GridviewBuses? or is it outside the GridviewBuses?
0
 

Author Comment

by:etan08
Comment Utility
It is inside the gridview and is only populates when the edit button is clicked.
0
 

Author Comment

by:etan08
Comment Utility
Here's the EditItemTemplate used:
<EditItemTemplate>
    <asp:DropDownList ID="DropDownListManufactureYear" runat="server" DataTextField="Year" DataValueField="Year"
        SelectedValue='<%# Bind("ManufactureYear") %>' DataSourceID="ObjectDataSourceSelectYear" CssClass="gvDropDownBoxStyle"
        AppendDataBoundItems="true">
    </asp:DropDownList>
    <asp:RequiredFieldValidator ID="RequiredFieldValidatorManufactureYear" runat="server" ErrorMessage=""
        ControlToValidate="DropDownListManufactureYear" ValidationGroup="EditBus"></asp:RequiredFieldValidator>
</EditItemTemplate>

Open in new window

0
 
LVL 8

Expert Comment

by:sriggumma
Comment Utility

Code like below should work for you.
 
protected void GridviewBuses_RowEditing(object sender, GridViewEditEventArgs e)
{
	GridviewBuses.EditIndex = e.NewEditIndex;
	(DropDownList)e.Item.FindControl("DropDownListPurchaseYear").DataBind();
}

Open in new window


Hope this helps.
0
 
LVL 8

Expert Comment

by:sriggumma
Comment Utility
Are there DropDownListManufactureYear and DropDownListPurchaseYear seperate?
Where's DropDownListPurchaseYear located?
0
 

Author Comment

by:etan08
Comment Utility
Yes they are separate but need the same functionality described.  Just need to have some kind of try catch block so they don't error out if the item is not displayed in the dropdown.  good catch...

I'm getting an error a red line under the Item in the code you've provided.  

Here's the error message:
'System.Web.UI.WebControls.GridViewEditEventArgs' does not contain a definition for 'Item' and no extension method 'Item' accepting a first argument of type 'System.Web.UI.WebControls.GridViewEditEventArgs' could be found (are you missing a using directive or an assembly reference?)

I had to modify your code slightly not sure if it is correct:

        protected void GridviewBuses_RowEditing(object sender, GridViewEditEventArgs e)
        {
            GridviewBuses.EditIndex = e.NewEditIndex;
            DropDownList DropDownListPurchaseYear = (DropDownList) e.Item.FindControl("DropDownListPurchaseYear").DataBind();
        }
0
 
LVL 8

Expert Comment

by:sriggumma
Comment Utility
I understand that DropDownListManufactureYear exists in each row of GridView.

But where's DropDownListPurchaseYear  located?
Answer to this may help to identify why the control is not accesible.
0
 

Author Comment

by:etan08
Comment Utility
It is just another column in the gridview.
<asp:GridView ID="GridviewBuses" runat="server" AutoGenerateColumns="False" CellPadding="4"
                    ForeColor="#333333" GridLines="None" Width="700px" DataKeyNames="BusID" DataSourceID="ObjectDataSourceBusesByDistrict"
                    Style="margin-right: 0px; margin-top: 0px;" AllowPaging="True" AllowSorting="True"
                    OnRowUpdated="GridviewBuses_RowUpdated" 
                    OnRowDeleting="GridviewBuses_RowDeleting" 
                    OnRowEditing="GridviewBuses_RowEditing">
                    <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
                    <Columns>
                        <asp:BoundField DataField="BusID" HeaderText="Ref No" SortExpression="BusID" ReadOnly="true">
                            <HeaderStyle Font-Size="11px" Wrap="false"></HeaderStyle>
                            <ItemStyle Font-Size="11px"></ItemStyle>
                        </asp:BoundField>
                        <asp:TemplateField HeaderText="Bus No" SortExpression="BusNo">
                            <ItemTemplate>
                                <asp:Label ID="LabelBusNo" runat="server" Text='<%# Bind("BusNo") %>' SkinID="GridViewLabel"></asp:Label>
                            </ItemTemplate>
                            <EditItemTemplate>
                                <asp:TextBox ID="TextBoxBusNo" runat="server" Text='<%# Bind("BusNo") %>' Width="60px"
                                    CssClass="gvTextBoxStyle" MaxLength="9" onkeyup="this.value=this.value.toUpperCase();"></asp:TextBox>
                                <asp:RequiredFieldValidator ID="RequiredFieldValidatorBusNo" runat="server" ErrorMessage=""
                                    ControlToValidate="TextBoxBusNo" ValidationGroup="EditBus"></asp:RequiredFieldValidator>
                            </EditItemTemplate>
                            <ItemStyle Wrap="false" />
                            <HeaderStyle Font-Size="11px" Wrap="false" />
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Chas" SortExpression="ChassisID" HeaderStyle-Font-Size="11px">
                            <ItemTemplate>
                                <asp:Label ID="Label5" runat="server" Text='<%# Bind("ChassisCode") %>' SkinID="GridViewLabel"></asp:Label>
                            </ItemTemplate>
                            <EditItemTemplate>
                                <asp:DropDownList ID="DropDownListChassis" runat="server" DataTextField="ChassisCode"
                                    DataValueField="ChassisID" DataSourceID="ObjectDataSourceChassis" SelectedValue='<%# Bind("ChassisID") %>'
                                    CssClass="gvDropDownBoxStyle" AppendDataBoundItems="true">
                                    <asp:ListItem></asp:ListItem>
                                </asp:DropDownList>
                                <asp:RequiredFieldValidator ID="RequiredFieldValidatorChassis" runat="server" ErrorMessage=""
                                    ControlToValidate="DropDownListChassis" ValidationGroup="EditBus"></asp:RequiredFieldValidator>
                            </EditItemTemplate>
                            <HeaderStyle Font-Size="11px" />
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="VIN No" SortExpression="VIN">
                            <ItemTemplate>
                                <asp:Label ID="Label12" runat="server" Text='<%# Bind("VIN") %>'></asp:Label>
                            </ItemTemplate>
                            <EditItemTemplate>
                                <asp:TextBox ID="TextBoxVIN" runat="server" Text='<%# Bind("VIN") %>' Width="180px"
                                    CssClass="gvTextBoxStyle" MaxLength="22" onkeyup="this.value=this.value.toUpperCase();"></asp:TextBox>
                                <asp:RequiredFieldValidator ID="RequiredFieldValidatorVIN" runat="server" ErrorMessage=""
                                    ControlToValidate="TextBoxVIN" ValidationGroup="EditBus"></asp:RequiredFieldValidator>
                            </EditItemTemplate>
                            <ItemStyle Wrap="false" />
                            <HeaderStyle Font-Size="11px" />
                            <ItemStyle Font-Size="11px" />
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="POY" SortExpression="PurchaseYear">
                            <ItemTemplate>
                                <asp:Label ID="Label9" runat="server" Text='<%# Bind("PurchaseYear") %>'></asp:Label>
                            </ItemTemplate>
                            <EditItemTemplate>
                                <asp:DropDownList ID="DropDownListPurchaseYear" runat="server" DataTextField="Year" DataValueField="Year"
                                    SelectedValue='<%# Bind("PurchaseYear") %>' DataSourceID="ObjectDataSourceSelectYear" CssClass="gvDropDownBoxStyle"
                                    AppendDataBoundItems="true">
                                </asp:DropDownList>
                                <asp:RequiredFieldValidator ID="RequiredFieldValidatorPurchaseYear" runat="server" ErrorMessage=""
                                    ControlToValidate="DropDownListPurchaseYear" ValidationGroup="EditBus"></asp:RequiredFieldValidator>
                            </EditItemTemplate>
                            <HeaderStyle Font-Size="11px" />
                            <ItemStyle Font-Size="11px" />
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="MOY" SortExpression="ManufactureYear">
                            <ItemTemplate>
                                <asp:Label ID="Label10" runat="server" Text='<%# Bind("ManufactureYear") %>'></asp:Label>
                            </ItemTemplate>
                            <EditItemTemplate>
                                <asp:DropDownList ID="DropDownListManufactureYear" runat="server" DataTextField="Year" DataValueField="Year"
                                    SelectedValue='<%# Bind("ManufactureYear") %>' DataSourceID="ObjectDataSourceSelectYear" CssClass="gvDropDownBoxStyle"
                                    AppendDataBoundItems="true">
                                </asp:DropDownList>
                                <asp:RequiredFieldValidator ID="RequiredFieldValidatorManufactureYear" runat="server" ErrorMessage=""
                                    ControlToValidate="DropDownListManufactureYear" ValidationGroup="EditBus"></asp:RequiredFieldValidator>
                            </EditItemTemplate>
                            <HeaderStyle Font-Size="11px" />
                            <ItemStyle Font-Size="11px" />
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Body" SortExpression="BodyID">
                            <ItemTemplate>
                                <asp:Label ID="Label4" runat="server" Text='<%# Bind("BodyCode") %>' SkinID="GridViewLabel"></asp:Label>
                            </ItemTemplate>
                            <EditItemTemplate>
                                <asp:DropDownList ID="DropDownListBody" runat="server" DataTextField="BodyCode" DataValueField="BodyID"
                                    SelectedValue='<%# Bind("BodyID") %>' DataSourceID="ObjectDataSourceBody" CssClass="gvDropDownBoxStyle"
                                    AppendDataBoundItems="true">
                                    <asp:ListItem></asp:ListItem>
                                </asp:DropDownList>
                                <asp:RequiredFieldValidator ID="RequiredFieldValidatorBody" runat="server" ErrorMessage=""
                                    ControlToValidate="DropDownListBody" ValidationGroup="EditBus"></asp:RequiredFieldValidator>
                            </EditItemTemplate>
                            <HeaderStyle Font-Size="11px"></HeaderStyle>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Style" SortExpression="EngineID">
                            <ItemTemplate>
                                <asp:Label ID="Label2" runat="server" Text='<%# Bind("EngineCode") %>' SkinID="GridViewLabel"></asp:Label>
                            </ItemTemplate>
                            <EditItemTemplate>
                                <asp:DropDownList ID="DropDownListEnginStyle" runat="server" DataTextField="EngineCode"
                                    DataValueField="EngineID" DataSourceID="ObjectDataSourceEnginStyle" SelectedValue='<%# Bind("EngineID") %>'
                                    CssClass="gvDropDownBoxStyle" AppendDataBoundItems="true">
                                    <asp:ListItem></asp:ListItem>
                                </asp:DropDownList>
                                <asp:RequiredFieldValidator ID="RequiredFieldValidatorEnginStyle" runat="server"
                                    ErrorMessage="" ControlToValidate="DropDownListEnginStyle" ValidationGroup="EditBus"></asp:RequiredFieldValidator>
                            </EditItemTemplate>
                            <HeaderStyle Font-Size="11px"></HeaderStyle>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Fuel" SortExpression="FuelID">
                            <ItemTemplate>
                                <asp:Label ID="Label6" runat="server" Text='<%# Bind("FuelCode") %>' SkinID="GridViewLabel"></asp:Label>
                            </ItemTemplate>
                            <EditItemTemplate>
                                <asp:DropDownList ID="DropDownListFuel" runat="server" DataTextField="FuelCode" DataValueField="FuelID"
                                    DataSourceID="ObjectDataSourceFuel" SelectedValue='<%# Bind("FuelID") %>' CssClass="gvDropDownBoxStyle"
                                    AppendDataBoundItems="true">
                                    <asp:ListItem></asp:ListItem>
                                </asp:DropDownList>
                                <asp:RequiredFieldValidator ID="RequiredFieldValidatorFuel" runat="server" ErrorMessage=""
                                    ControlToValidate="DropDownListFuel" ValidationGroup="EditBus"></asp:RequiredFieldValidator>
                            </EditItemTemplate>
                            <HeaderStyle Font-Size="11px"></HeaderStyle>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Eqip" SortExpression="EquipmentID">
                            <ItemTemplate>
                                <asp:Label ID="Label3" runat="server" Text='<%# Bind("EquipmentCode") %>' SkinID="GridViewLabel"></asp:Label>
                            </ItemTemplate>
                            <EditItemTemplate>
                                <asp:DropDownList ID="DropDownListEquipment" runat="server" DataTextField="EquipmentCode"
                                    DataValueField="EquipmentID" DataSourceID="ObjectDataSourceEquipment" SelectedValue='<%# Bind("EquipmentID") %>'
                                    CssClass="gvDropDownBoxStyle" AppendDataBoundItems="true">
                                    <asp:ListItem></asp:ListItem>
                                </asp:DropDownList>
                            </EditItemTemplate>
                            <HeaderStyle Font-Size="11px"></HeaderStyle>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Cap" SortExpression="Capacity">
                            <ItemTemplate>
                                <asp:Label ID="Label1" runat="server" Text='<%# Bind("Capacity") %>' SkinID="GridViewLabel"></asp:Label>
                            </ItemTemplate>
                            <EditItemTemplate>
                                <asp:TextBox ID="TextBoxCapacity" runat="server" Text='<%# Bind("Capacity") %>' Width="40px"
                                    Font-Size="11px"></asp:TextBox>
                                <asp:RequiredFieldValidator ID="RequiredFieldValidatorCapacity" runat="server" ErrorMessage=""
                                    ControlToValidate="TextBoxCapacity" ValidationGroup="EditBus"></asp:RequiredFieldValidator>
                            </EditItemTemplate>
                            <HeaderStyle Font-Size="11px"></HeaderStyle>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Cost" SortExpression="Cost">
                            <ItemTemplate>
                                <asp:Label ID="Label11" runat="server" Text='<%# Bind("Cost") %>'></asp:Label>
                            </ItemTemplate>
                            <EditItemTemplate>
                                <asp:TextBox ID="TextBoxCost" runat="server" Text='<%# Bind("Cost") %>' Width="40px"
                                    Font-Size="11px"></asp:TextBox>
                                <asp:RequiredFieldValidator ID="RequiredFieldValidatorCost" runat="server" ErrorMessage=""
                                    ControlToValidate="TextBoxCost" ValidationGroup="EditBus"></asp:RequiredFieldValidator>
                            </EditItemTemplate>
                            <HeaderStyle Font-Size="11px" />
                            <ItemStyle Font-Size="11px" HorizontalAlign="Right" />
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Stat" SortExpression="StatusID">
                            <ItemTemplate>
                                <asp:Label ID="Label7" runat="server" Text='<%# Bind("StatusCode") %>' SkinID="GridViewLabel"></asp:Label>
                            </ItemTemplate>
                            <EditItemTemplate>
                                <asp:DropDownList ID="DropDownListStatus" runat="server" DataTextField="StatusCode"
                                    DataValueField="StatusID" DataSourceID="ObjectDataSourceStatus" SelectedValue='<%# Bind("StatusID") %>'
                                    CssClass="gvDropDownBoxStyle" AppendDataBoundItems="true">
                                    <asp:ListItem></asp:ListItem>
                                </asp:DropDownList>
                                <asp:RequiredFieldValidator ID="RequiredFieldValidatorStatus" runat="server" ErrorMessage=""
                                    ControlToValidate="DropDownListStatus" ValidationGroup="EditBus"></asp:RequiredFieldValidator>
                            </EditItemTemplate>
                            <HeaderStyle Font-Size="11px"></HeaderStyle>
                        </asp:TemplateField>
                        <asp:TemplateField SortExpression="AmortizationCode" HeaderText="AT">
                            <ItemTemplate>
                                <asp:Label ID="Label8" runat="server" Text='<%# Bind("AmortizationCode") %>'></asp:Label>
                            </ItemTemplate>
                            <EditItemTemplate>
                                <asp:DropDownList ID="DropDownListAmortization" runat="server" DataTextField="AmortizationCode"
                                    DataValueField="AmortizationID" DataSourceID="ObjectDataSourceAmortization" SelectedValue='<%# Bind("AmortizationID") %>'
                                    CssClass="gvDropDownBoxStyle" AppendDataBoundItems="true">
                                    <asp:ListItem></asp:ListItem>
                                </asp:DropDownList>
                                <asp:RequiredFieldValidator ID="RequiredFieldValidatorAmortization" runat="server" ErrorMessage=""
                                    ControlToValidate="DropDownListAmortization" ValidationGroup="EditBus"></asp:RequiredFieldValidator>
                            </EditItemTemplate>
                            <HeaderStyle Font-Size="11px" />
                            <ItemStyle Font-Size="11px"></ItemStyle>
                        </asp:TemplateField>
                        <asp:TemplateField ItemStyle-Wrap="false" SortExpression="BusID">
                            <ItemTemplate>
                                <asp:LinkButton ID="LinkButtonEdit" runat="server" CommandName="Edit" Text="Edit"
                                    Font-Size="11px">
                                </asp:LinkButton>
                                <asp:LinkButton ID="LinkButtonDelete" runat="server" CommandName="Delete" Text="Del"
                                    Font-Size="11px" OnClientClick='<%# Eval("BusID", "return confirm(&#39;Are you sure you want to delete {0}?&#39;)") %>'>
                                </asp:LinkButton>
                                <asp:LinkButton ID="LinkButtonTransfer" runat="server" PostBackUrl='<%#"~/AdminMenu.aspx?Action=T&BusID="+Eval("BusID") %>'
                                    Text="Transfer" Font-Size="11px">
                                </asp:LinkButton>
                            </ItemTemplate>
                            <EditItemTemplate>
                                <asp:LinkButton ID="LinkButtonUpdate" runat="server" CommandName="Update" Text="Update"
                                    ValidationGroup="EditBus" Font-Size="11px" >
                                </asp:LinkButton>
                                <asp:LinkButton ID="LinkButtonCancel" runat="server" CommandName="Cancel" Text="Cancel"
                                    Font-Size="11px">
                                </asp:LinkButton>
                            </EditItemTemplate>
                            <ItemStyle Wrap="False" />
                        </asp:TemplateField>
                    </Columns>
                    <EditRowStyle BackColor="#999999" />
                    <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                    <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                    <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
                    <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
                    <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
                    <SortedAscendingCellStyle BackColor="#E9E7E2" />
                    <SortedAscendingHeaderStyle BackColor="#506C8C" />
                    <SortedDescendingCellStyle BackColor="#FFFDF8" />
                    <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
                </asp:GridView>

Open in new window

0
 

Author Comment

by:etan08
Comment Utility
Ok, I've came up with this but it isn't working because the DropDownLists are not pupulated when the event triggers therefore it doesn't enter the try block and set the selectedvalue to "".  

Please review my code and tell me what I can do to get it into the try block if possible.

I've tried various other methods but none are working.  The rendering of the dropdown doesen't happen because it errors out.  Therefore i need an alternate method rather than trying to find if the dropdownlist is present.  I need something like if there is an ArgumentOutOfRangeException when trying to populate a dropdown because of the selected value is not in the table that the stored procedure makes then enter the try block.  

I'm not sure how to do that however.

Any ideas?
protected void GridviewBuses_RowEditing(object sender, GridViewEditEventArgs e)
        {
            GridviewBuses.EditIndex = e.NewEditIndex;
            GridViewRow editingRow = GridviewBuses.Rows[e.NewEditIndex];
            DropDownList DropDownListPurchaseYear = (editingRow.FindControl("DropDownListPurchaseYear") as DropDownList);

            if (DropDownListPurchaseYear != null)
            {
                try
                {
                    DropDownListPurchaseYear.DataBind();
                }
                catch (ArgumentOutOfRangeException)
                {
                    DropDownListPurchaseYear.SelectedValue = "";
                }
            }

            DropDownList DropDownListManufactureYear = (editingRow.FindControl("DropDownListManufactureYear") as DropDownList);
            if (DropDownListManufactureYear != null)
            {
                try
                {
                    DropDownListManufactureYear.DataBind();
                }
                catch (ArgumentOutOfRangeException)
                {
                    DropDownListManufactureYear.SelectedValue = "";
                }
            }
        }

Open in new window

0
 
LVL 12

Expert Comment

by:CmdoProg2
Comment Utility
Is your value from the datasource an empty string, a null value, or an actual value not in the dropdownlist?
0
How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

 

Author Comment

by:etan08
Comment Utility
The datasource calls a stored procedure that performs the math because we only want specific years.  The solution uses a data access layer and business layer to complete the call to the database.

What I'm trying to fix is:
If the data in the table doesn't fall into the date range within the stored procedure, and edit is clicked, then the .net site gives me a ArgumentOutOfRangeException.  It is possible for the data to contain something other than what is populated in the dropdownlist but we don't want the user to be able to select anything but years from 2002 to the current year.

I hope this clears up what you've asked.
CREATE procedure [dbo].[spGetYears] as

CREATE TABLE #temp(
	[YearID] [int] IDENTITY(1,1) NOT NULL,
	[Year] [char](4))

declare @yr int
select @yr = 2002
while @yr <= (select year(getdate()))
begin
    insert into #temp select @yr
    select @yr = @yr + 1
end


	SELECT	YearID, 
			Year
	FROM	#temp
	order by Year desc

GO

Open in new window

0
 

Author Comment

by:etan08
Comment Utility
Upping the point value.
0
 
LVL 12

Expert Comment

by:CmdoProg2
Comment Utility
The difficulty is the control binding to the value.  I have a similar problem with having a null value from the database and use a custom control built from the dropdownlist.  The custom control snippet below is in VB and does not check for missing value.  The two methods are identical, but shows you can override the selectvalue or create a new method.

  It will be awhile before I can translate it into C# and test it for missing value during a binding to throw an event.
Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Drawing
Imports System.Text
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls

<AspNetHostingPermission(SecurityAction.Demand, Level:=AspNetHostingPermissionLevel.Minimal)> _
<AspNetHostingPermission(SecurityAction.InheritanceDemand, Level:=AspNetHostingPermissionLevel.Minimal)> _
<Designer(GetType(ListControlDesigner))> _
<ToolboxData("<{0}:ddlNullable runat=server></{0}:ddlNullable>")> _
<ToolboxBitmap(GetType(ddlNullable), "ddlNull.bmp")> _
Public Class ddlNullable
  Inherits DropDownList

#Region "  Properties . . "
  ''' <summary>
  ''' Allow binding to a nullable field
  ''' </summary>
  ''' <value></value>
  ''' <returns></returns>
  ''' <remarks></remarks>
  <Bindable(True), Category("Data"), Localizable(True), DefaultValue(GetType(Object), Nothing)> _
     Public Property NullableValue() As Object
    Get
      If MyBase.SelectedIndex = -1 Then
        Return Nothing
      Else
        Return MyBase.SelectedValue
      End If
    End Get
    Set(ByVal value As Object)
      If value Is Nothing Then
        MyBase.SelectedIndex = -1
      ElseIf TypeOf (value) Is DBNull Then
        MyBase.SelectedIndex = -1
      Else
        MyBase.SelectedValue = value
      End If
    End Set
  End Property

  Public Overloads Property SelectedValue() As Object
    Get
      If MyBase.SelectedIndex = -1 Then
        Return Nothing
      Else
        Return MyBase.SelectedValue
      End If
    End Get
    Set(ByVal value As Object)
      If value Is Nothing Then
        MyBase.SelectedIndex = -1
      ElseIf TypeOf (value) Is DBNull Then
        MyBase.SelectedIndex = -1
      Else 'If MyBase.Items.Count > 0 Then
        MyBase.SelectedValue = value
      End If
    End Set
  End Property
#End Region

  Public Function IsValueInList(ByVal value As String) As Boolean
    Return (Me.Items.FindByValue(value) Is Nothing = False)
  End Function


End Class
Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Drawing
Imports System.Text
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls

<AspNetHostingPermission(SecurityAction.Demand, Level:=AspNetHostingPermissionLevel.Minimal)> _
<AspNetHostingPermission(SecurityAction.InheritanceDemand, Level:=AspNetHostingPermissionLevel.Minimal)> _
<Designer(GetType(ListControlDesigner))> _
<ToolboxData("<{0}:ddlNullable runat=server></{0}:ddlNullable>")> _
<ToolboxBitmap(GetType(ddlNullable), "ddlNull.bmp")> _
Public Class ddlNullable
  Inherits DropDownList

#Region "  Properties . . "
  ''' <summary>
  ''' Allow binding to a nullable field
  ''' </summary>
  ''' <value></value>
  ''' <returns></returns>
  ''' <remarks></remarks>
  <Bindable(True), Category("Data"), Localizable(True), DefaultValue(GetType(Object), Nothing)> _
     Public Property NullableValue() As Object
    Get
      If MyBase.SelectedIndex = -1 Then
        Return Nothing
      Else
        Return MyBase.SelectedValue
      End If
    End Get
    Set(ByVal value As Object)
      If value Is Nothing Then
        MyBase.SelectedIndex = -1
      ElseIf TypeOf (value) Is DBNull Then
        MyBase.SelectedIndex = -1
      Else
        MyBase.SelectedValue = value
      End If
    End Set
  End Property

  Public Overloads Property SelectedValue() As Object
    Get
      If MyBase.SelectedIndex = -1 Then
        Return Nothing
      Else
        Return MyBase.SelectedValue
      End If
    End Get
    Set(ByVal value As Object)
      If value Is Nothing Then
        MyBase.SelectedIndex = -1
      ElseIf TypeOf (value) Is DBNull Then
        MyBase.SelectedIndex = -1
      Else 
        MyBase.SelectedValue = value
      End If
    End Set
  End Property
#End Region

  Public Function IsValueInList(ByVal value As String) As Boolean
    Return (Me.Items.FindByValue(value) Is Nothing = False)
  End Function


End Class

Open in new window

0
 
LVL 12

Expert Comment

by:CmdoProg2
Comment Utility
Oops, I hit paste twice.  Please ignore the second class.
0
 

Author Comment

by:etan08
Comment Utility
Well I've come up with a way to populate the correct years when the database has something other than the selected items (see code below)

However there are some problems that I am having with the code that I have here.
1. if the value is not in the dropdownlist then the values are written to the DDLPurchaseYear twice
2. when the update button is clicked the original values are retained and the new value doesn't matter
protected void GridviewBuses_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                if (e.Row.RowIndex == GridviewBuses.EditIndex)
                {
                    HiddenField hfManufactureYear = (HiddenField)e.Row.FindControl("hfManufactureYear");
                    string CurrentManufactureYear = hfManufactureYear.Value;

                    HiddenField hfPurchaseYear = (HiddenField)e.Row.FindControl("hfPurchaseYear");
                    string CurrentPurchaseYear = hfPurchaseYear.Value;

                    DropDownList ddl = (DropDownList)e.Row.FindControl("DropDownListManufactureYear");
                    ddl.DataSourceID = "ObjectDataSourceSelectManufactureYear";

                    DropDownList ddl2 = (DropDownList)e.Row.FindControl("DropDownListPurchaseYear");
                    ddl2.DataSourceID = "ObjectDataSourceSelectPurchaseYear";

                    try
                    {
                        ddl.SelectedValue = CurrentManufactureYear;
                        ddl.DataBind();

                        ddl2.SelectedValue = CurrentPurchaseYear;
                        ddl2.DataBind();
                    }
                    catch (ArgumentOutOfRangeException)
                    {
                        ddl.SelectedValue = "";
                        ddl.DataBind();

                        ddl2.SelectedValue = "";
                        ddl2.DataBind();
                    }
                }
            }
        }


                        <asp:TemplateField HeaderText="POY" SortExpression="PurchaseYear">
                            <ItemTemplate>
                                <asp:Label ID="Label9" runat="server" Text='<%# Bind("PurchaseYear") %>'></asp:Label>
                            </ItemTemplate>
                            <EditItemTemplate>
                            <asp:HiddenField ID="hfPurchaseYear" runat="server" Value='<%# Bind("PurchaseYear") %>' />
                                <asp:DropDownList ID="DropDownListPurchaseYear" runat="server" DataTextField="Year" DataValueField="Year"
                                    CssClass="gvDropDownBoxStyle" AppendDataBoundItems="true">
                                    <asp:ListItem Value=""></asp:ListItem>
                                </asp:DropDownList>
                                <asp:RequiredFieldValidator ID="RequiredFieldValidatorPurchaseYear" runat="server" ErrorMessage=""
                                    ControlToValidate="DropDownListPurchaseYear" ValidationGroup="EditBus"></asp:RequiredFieldValidator>
                            </EditItemTemplate>
                            <HeaderStyle Font-Size="11px" /><ItemStyle Font-Size="11px" />
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="MOY" SortExpression="ManufactureYear">
                            <ItemTemplate>
                                <asp:Label ID="Label10" runat="server" Text='<%# Bind("ManufactureYear") %>'></asp:Label>
                            </ItemTemplate>
                            <EditItemTemplate>
                            <asp:HiddenField ID="hfManufactureYear" runat="server" Value='<%# Bind("ManufactureYear") %>' />
                                <asp:DropDownList ID="DropDownListManufactureYear" runat="server" DataTextField="Year" DataValueField="Year"
                                    CssClass="gvDropDownBoxStyle" AppendDataBoundItems="true">
                                    <asp:ListItem Value=""></asp:ListItem>
                                </asp:DropDownList>
                                <asp:RequiredFieldValidator ID="RequiredFieldValidatorManufactureYear" runat="server" ErrorMessage=""
                                    ControlToValidate="DropDownListManufactureYear" ValidationGroup="EditBus"></asp:RequiredFieldValidator>
                            </EditItemTemplate>

Open in new window

0
 
LVL 8

Expert Comment

by:sriggumma
Comment Utility
In GridviewBuses_RowDataBound, Shouldn't it be like below?
 
try
{
	ddl.Items.Clear();
	ddl.DataBind();
	ddl.SelectedValue = CurrentManufactureYear;
	
	ddl2.Items.Clear();
	ddl2.DataBind();
	ddl2.SelectedValue = CurrentPurchaseYear;
}
catch (ArgumentOutOfRangeException)
{
	ddl.DataBind();
	ddl.SelectedValue = "";

	ddl2.DataBind();
	ddl2.SelectedValue = "";
}

Open in new window


Hope this helps.
0
 
LVL 8

Expert Comment

by:sriggumma
Comment Utility
Or to be more safe - check if CurrentManufactureYear or CurrentPurchaseYear exists in ddl.Items Value field before setting the SelectedValue.
0
 

Author Comment

by:etan08
Comment Utility
Actually everything works in the try block but when a ArgumentOutOfRangeException occurs that's when it doesn't update the values.  I'm trying to trigger a change in a selectedindexchanged sub but am not getting the correct syntax to set those values.  Any ideas?
0
 

Accepted Solution

by:
etan08 earned 0 total points
Comment Utility
Correction I guess it doesn't work because it doesn't keep the new values from the dropdown.  I tried what you've suggested without any luck.
0
 
LVL 8

Expert Comment

by:sriggumma
Comment Utility
hmmmmmmm.

I didn't have any other thoughts as of now.
But in case if your issues gets resolved .. try to post it, so that others will benefit.
0
 

Author Closing Comment

by:etan08
Comment Utility
Didn't help and I will not like to post this entry to the kb
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
Ever needed a SQL 2008 Database replicated/mirrored/log shipped on another server but you can't take the downtime inflicted by initial snapshot or disconnect while T-logs are restored or mirror applied? You can use SQL Server Initialize from Backup…
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.
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…

762 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