p2p.wrox.com Forums

p2p.wrox.com Forums (http://p2p.wrox.com/index.php)
-   ASP.NET 2.0 Basics (http://p2p.wrox.com/forumdisplay.php?f=136)
-   -   Saving DropDownList selection to a database (http://p2p.wrox.com/showthread.php?t=35599)

steve35719 November 30th, 2005 12:41 AM

Saving DropDownList selection to a database
 
What am I missing? I can't figure it out. Granted, I'm a complete newb, but I've been trying for weeks! While in "template mode", removed the default textbox in the DetailsView EditItemTemplate and InsertItemTemplate and replaced with a dropdownlist control. When I place SelectedValue= '<%# Bind("Color") %>' in the DropDownList tag I get an error at runtime:

"'DropDownList2' has a SelectedValue which is invalid because it does not exist in the list of items. Parameter name: value "

If I leave out "SelectedValue='<%# Bind("Color") %>" from the tag, the selection gets lost and doesn't get saved to the database. What's going on and how do I fix it? All I want to do is provide a form and save it to a database. Seems like it should be straightfoward...

Thanks for the much needed help,
Greg

Here's my code:

 <%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

<title>Untitled Page</title>

</head>

<body>

<form id="form1" runat="server">

<div>



<br />

&nbsp;


<asp:DetailsView ID="DetailsView1" runat="server" AllowPaging="True" AutoGenerateRows="False"

DataSourceID="SqlDataSource1" Height="50px" Width="125px">

<Fields>

<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />

<asp:TemplateField HeaderText="Color" SortExpression="Color">

<EditItemTemplate>

<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" SelectedValue='<%# Bind("Color") %>'>

<asp:ListItem>Blue</asp:ListItem>

<asp:ListItem>Green</asp:ListItem>

<asp:ListItem>Red</asp:ListItem>

</asp:DropDownList>

</EditItemTemplate>

<InsertItemTemplate>

<asp:DropDownList ID="DropDownList2" runat="server" AutoPostBack="True" SelectedValue='<%# Bind("Color") %>'>

<asp:ListItem>Blue</asp:ListItem>

<asp:ListItem>Green</asp:ListItem>

<asp:ListItem>Red</asp:ListItem>

</asp:DropDownList>

</InsertItemTemplate>

<ItemTemplate>

<asp:Label ID="Label1" runat="server" Text='<%# Bind("Color") %>'></asp:Label>

</ItemTemplate>

</asp:TemplateField>

<asp:CommandField ShowEditButton="True" ShowInsertButton="True" />

</Fields>

</asp:DetailsView>


<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"

SelectCommand="SELECT * FROM [Color]"

InsertCommand="INSERT INTO Color([Name], [Color]) VALUES (@Name, @Color)"

UpdateCommand="UPDATE Color

SET Name =@Name,

Color =@Color

WHERE [Name]=@Name">

<UpdateParameters><asp:Parameter Name="Name" Type="string" /><asp:Parameter Name="Color" Type="string" /></UpdateParameters>

<InsertParameters><asp:Parameter Name="Name" Type="string" /><asp:Parameter Name="Color" Type="string" /></InsertParameters>


</asp:SqlDataSource>


</div>

</form>

</body>

</html>

What about removing "SelecedValue" from the DropDownList tag and replacing it with an OnSelectedIndexChanged function. Can't figure out how to put together the code behind to make it work. Don't have a clue...

    Protected Sub MyMethod(ByVal sender As Object, ByVal e As System.EventArgs)


        Dim DropDownList1 As New DropDownList
        DropDownList1 = CType(Me.DetailsView1.FindControl("DropDownList1") , DropDownList)




        'Dim DropDownList1 As DropDownList
        'DropDownList1 = CType(Me.DetailsView1.FindControl("DropDownList1") , DropDownList)


        'Dim selectedValue As String = CType(DetailsView1.FindControl("DropDownList1"), DropDownList).SelectedValue
    End Sub


Imar November 30th, 2005 03:20 PM

And is the error message right? Is the item not present in the drop-down? What happens when you display on a label for example?

Imar
---------------------------------------
Imar Spaanjaars
Everyone is unique, except for me.

steve35719 December 1st, 2005 03:52 AM

I'm not sure how to do that. I don't really know how to write VB code in the "code behind" file nor do I know where to learn how to write it. If I remove the "'" from:
'Dim selectedValue As String = CType(DetailsView1.FindControl("DropDownList1"), DropDownList).SelectedValue, and try to update the database, I get an error message that says:

"Object reference not set to an instance of an object."

There's something I'm not including in the code behind that's required to write to the database. I just don't know what it is. Too bad it's so complicated to perform what seems like a straightfoward task.
Sorry for the inexperience but I'm trying. Thanks for the help.


Imar December 1st, 2005 11:19 AM

Exactly the same as you do now for the ItemTemplate. Remove all the stuff from the EditItemTemplate and instead add this:

<asp:Label ID="Label1" runat="server" Text='<%# Bind("Color") %>'></asp:Label>

Does it display the correct color?

Imar
---------------------------------------
Imar Spaanjaars
Everyone is unique, except for me.

steve35719 December 1st, 2005 03:41 PM

If I remove everything from the EditItemTemplate then my dropdownlist is gone. I've included a code-behind event to occur with a selection of the dropdownlist but I still keep getting an error.

Code-behind:
Protected Sub MyMethod(ByVal sender As Object, ByVal e As System.EventArgs)

    Dim DropDownList1 As New System.Web.UI.WebControls.DropDownList
    Dim Label1 As New Label

    DropDownList1 = CType(Me.DetailsView1.FindControl("DropDownList1") , DropDownList)

    Label1 = CType(Me.DetailsView1.FindControl("Label1"), Label)
    Label1.Text = DropDownList1.SelectedItem.Text

    End Sub

Error Message:
"NullRefereceException was unhandled by user code.
Object reference not set to an instance of an object." which was in reference to:
Label1.Text = DropDownList1.SelectedItem.Text


Imar December 1st, 2005 03:49 PM

Quote:

quote:Originally posted by steve35719
If I remove everything from the EditItemTemplate then my dropdownlist is gone.
Yeah, that was the whole idea of my suggestion .... ;)

By adding the label to the ItemTemplate, you can see if the DataItem is still valid and holds a valid selection.

From there, you can diagnose other things. But it's important to find out what goes wrong where in the first place. Since I don't see the whole page, and since I can't run it, I can only guess....

Imar
---------------------------------------
Imar Spaanjaars
Everyone is unique, except for me.

steve35719 December 1st, 2005 04:31 PM

The original code does not work at all. I've had to remove: SelectedValue='<%# Bind("Color") from the tags of the DropDownList because I keep getting an error:
'DropDownList1' has a SelectedValue which is invalid because it does not exist in the list of items.
Parameter name: value

So, I'm trying to do the binding in the code-behind but not having much luck.
I've left the Label in the ItemTemplate still bound to color:
 <asp:Label ID="Label1" runat="server" Text='<%# Bind("Color") %>'></asp:Label>
For some reason, I can't get my selection in DropDownList1 to equal the text of Label1 so that it can be bound to the Color Value of the DetailsView. The DropDownList is a static population; thus, it does not receive its value from another DataSource.

Let me ask you, how would you go about accomplishing this task? I can't tell you how many times I've gone through the web, my Beginning Dynamic Websites, ASP.NET 2.0 Beta, and ASP.NET 2.0 Databases books looking for the answers.

Thank you for your time Imar.


Imar December 1st, 2005 04:48 PM

I don't see why this wouldn't work. This works for me:
Code:

<asp:TemplateField HeaderText="Description" SortExpression="Description">
  <EditItemTemplate>
    <asp:DropDownList ID="DropDownList1" runat="server" SelectedValue='<%# Bind("Description") %>'>
      <asp:ListItem>Posters</asp:ListItem>
      <asp:ListItem>Mugs</asp:ListItem>
      <asp:ListItem>Mugs</asp:ListItem>
      </asp:DropDownList>
    </EditItemTemplate>

    When I set the DefaultMode to edit, it displays the first record in my resultset and preselects the right item. You need *no* code behind to do this.

Could it be that your page is messed up by trying? What happens when you create a new page, add a single DataSource and a DetailsView, change 1 field in the DetailsView to a TemplateField and add a drop down to it? Then set DefaultMode of the DetailsView to Edit.

That should work. If it doesn't can you post the code?

Imar
---------------------------------------
Imar Spaanjaars
Everyone is unique, except for me.

steve35719 December 1st, 2005 05:17 PM

Imar, I've just about had all I can stand... I did exactly as you said and keep getting:
'DropDownList1' has a SelectedValue which is invalid because it does not exist in the list of items.
Parameter name: value
Exception Details: System.ArgumentOutOfRangeException: 'DropDownList1' has a SelectedValue which is invalid because it does not exist in the list of items.
Parameter name: value

Here it is, plain and simple...

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:DetailsView ID="DetailsView1" runat="server" AllowPaging="True" AutoGenerateRows="False"
            DataSourceID="SqlDataSource1" Height="50px" Width="125px" DefaultMode="Edit">
            <Fields>
                <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
                <asp:TemplateField HeaderText="Color" SortExpression="Color">
                    <EditItemTemplate>
                        <asp:DropDownList ID="DropDownList1" runat="server" SelectedValue='<%# Bind("Color") %>'>
                            <asp:ListItem Selected="True">Blue</asp:ListItem>
                            <asp:ListItem>Green</asp:ListItem>
                            <asp:ListItem>Red</asp:ListItem>
                        </asp:DropDownList>
                    </EditItemTemplate>

                </asp:TemplateField>
            </Fields>
        </asp:DetailsView>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
            SelectCommand="SELECT * FROM [Color]"
            UpdateCommand="UPDATE [Color]
                            SET Name=@Name,
                                Color=@Color
                            WHERE [Color]=@Color">
            <UpdateParameters>
                <asp:Parameter Name="Name" Type="String" />
                <asp:Parameter Name="Color" Type="string" />
            </UpdateParameters>

            </asp:SqlDataSource>

    </div>
    </form>
</body>
</html>

Does the error message have something to do with UpdateParameters? I got rid of the InsertItemTemplate and the ItemTemplate for the DetailsView and left only the EditItemTemplate.

I'm sorry to keep bothering you with this.
Greg


Imar December 1st, 2005 05:33 PM

Well, back to my initial question. Is the error message correct? Is there a value of either Blue, Green or Red in the database record you're trying to edit?

That's why I suggested to display the text on the label, so you can see what text it is trying to assign to SelectedValue....

Imar
---------------------------------------
Imar Spaanjaars
Everyone is unique, except for me.


All times are GMT -4. The time now is 05:09 AM.

Powered by vBulletin®
Copyright ©2000 - 2019, Jelsoft Enterprises Ltd.
© 2013 John Wiley & Sons, Inc.