Gridview SqlDataSource ; Error with edit from dropdownlist - c#

I have a gridview populated with an sqldatasource. One of the columns of the gridview is a templatefield which contains a label as ItemTemplate, but in the EditItemTemplate I have a dropdownlist, instead of a textbox. I wanted to be able to edit a value from a certain column by selecting from a list of possible values.
So I created a second sqldatasource in order to extract the values from the database. I bounded the 2 sqldatasources. Visually it's ok. When I click on edit, the dropdownlist appears with the values that I want inside of it. When I select one of the values and click update, I get the error "
Input string was not in a correct format." I think I know why this is happening. Probably the values from the dropdownlist are type string and what I need is integer because that is the type for this column. I have tried setting the UpdateParameter as type Int32 but no luck. Is there any way to do this ?
This is the code I have used, but I have changed the column names with "Column_1", "Column_2", etc. In this example, "Column_6" is the templatefield with the dropdownlist in the edit.
<asp:GridView ID="DataUploadGridView" runat="server" AutoGenerateColumns="False" DataSourceID="First_DB" DataKeyNames="Column_3" >
<RowStyle HorizontalAlign="Center" />
<Columns>
<asp:BoundField DataField="Column_1" HeaderText="Column 1"/>
<asp:BoundField DataField="Column_2" HeaderText="Column 2"/>
<asp:BoundField DataField="Column_3" HeaderText="Column 3"/>
<asp:BoundField DataField="Column_4" HeaderText="Column 4"/>
<asp:BoundField DataField="Column_5" HeaderText="Column 5"/>
<asp:TemplateField HeaderText="Column 6">
<EditItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="Second_DB" DataTextField="Column_6_Description" DataValueField="Column_6_ID"/>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("Column_6_ID") %>'/>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="true" HeaderText="Edit" />
<asp:CommandField ShowDeleteButton="true" HeaderText="Delete" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="First_DB" runat="server" ConnectionString="<%$ ConnectionStrings:MyConnectionString %>" OnSelecting="First_DB_Selecting" OnSelected="First_DB_Selected" OnInserted="First_DB_Inserted" OnInserting="First_DB_Inserting" OnDeleting="First_DB_Deleting" OnUpdating="First_DB_Updating"
SelectCommand ="SELECT * FROM [tblFirst_DB]
UpdateCommand ="UPDATE [tblFirst_DB]
SET [Column_1] = #Column_1,
[Column_2] = #Column_2,
[Column_3] = #Column_3,
[Column_4] = #Column_4,
[Column_5] = #Column_5,
[Column_6] = #Column_6
WHERE [Column_3] = #Column_3"
DeleteCommand ="DELETE FROM [tblFirst_DB] WHERE [Column_3] = #Column_3"
<UpdateParameters>
<asp:Parameter Name="Column_1" Type="String" />
<asp:Parameter Name="Column_2" Type="String" />
<asp:Parameter Name="Column_3" Type="String" />
<asp:Parameter Name="Column_4" Type="String" />
<asp:Parameter Name="Column_5" Type="Int32" />
<asp:Parameter Name="Column_6" Type="Int32" />
</UpdateParameters>
<DeleteParameters>
<asp:Parameter Name="Column_3" Type="String" />
</DeleteParameters>
</asp:SqlDataSource>
<asp:SqlDataSource ID="Second_DB" runat="server" ConnectionString="<%$ ConnectionStrings:MyConnectionString %>" SelectCommand="SELECT [Column_6_ID], [Column_6_Description] FROM [tblSecond_DB]"></asp:SqlDataSource>
Hopefully you are still here. So just to recap the problem. I'm getting an "
Input string was not in a correct format. " error because I need the Column_6 parameter to be integer and the values are coming from a dropdownlist which is probably making each value a string.
What can I do so that the value for Column_6 stays int upon updating it ?
The only thing that comes to mind right now is to pass the parameter from the code behind somehow. When I select the dropdownlist value, I should trigger an OnSelectedIndexChanged event. I'm thinking here is where I should cast the Selected_ID to an integer and somehow feed it into the first sqldatasource. But the value would go into a label so that will turn it into a string again. So no use...I'm really stuck on this. Any help is welcome.
Thank you !
Update: I've noticed that if I remove all the UpdateParameters, except the one from Column_6, I'm not getting the error anymore. However the value is not going in the gridview. It's an empty cell. I looked in the DB and it's null.
I think it's null because in the UpdateParameters I now have:
<UpdateParameters>
<asp:Parameter Name="Column_6" Type="Int32" />
</UpdateParameters>
It's not getting the value from anywhere. It should get it from the Second_DB sqldatasource. I tried changing it to:
<UpdateParameters>
<asp:ControlParameter Name="Column_6" ControlID="Second_DB" Type="Int32" />
</UpdateParameters>
But it's not really working out like I expected. I feel like I'm getting closer but no idea why it's behaving like this.

Related

Editable GridView

I'm trying to allow for editing of the items in a GridView (the DataSource is a database connection). Every example I find has complicated examples implemented within. I'd like to know what the simplest change(s) I need to do are in order to allow for editing of items in the GridView.
In other words, how can I modify the following to allow for editing?
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSourceWS">
<Columns>
<asp:CommandField ShowSelectButton="True" />
<asp:BoundField DataField="id" HeaderText="id" InsertVisible="False" ReadOnly="True" SortExpression="id" />
<asp:BoundField DataField="NAME" HeaderText="NAME" SortExpression="NAME" />
<asp:BoundField DataField="ACCESS_TO" HeaderText="ACCESS_TO" SortExpression="ACCESS_TO" />
</Columns>
</asp:GridView>
Obviously I'd need to add code as well, but I'm just not sure how to start with this.
EDIT: I thought I'd specified, but I didn't - it's an SQLDataSource.
There are several thing you need to do to enable editing
Assuming that your data source is an SQLDataSource
1) Add a command field to your girdview columns
<asp:CommandField ButtonType="Button" EditText="Edit" ShowEditButton="true"/>
2) Add an update command to your data source
<asp:SqlDataSource ID="SqlDataSourceWS" runat="server"
ConnectionString="<%$ Connection String %>"
SelectCommand=" SELECT COMMAND HERE "
UpdateCommand=" UPDATE COMMAND HERE ">
<UpdateParameters>
<asp:Parameter Name="" />
<asp:Parameter Name="" />
</UpdateParameters>
</asp:SqlDataSource>
For more information on the command field and how to use it you can look at the Microsoft Developer Network Documentation
EDIT
Here is a very simple example of a SQLDatasource that shows how you may update an item
<asp:SqlDataSource ID="sqlMeetings" runat="server"
ConnectionString="<%$ connection %>"
SelectCommand="SELECT [meetingid]
,[groupname]
,[meetingtime]
,[meetingdate]
FROM [DCMS].[dbo].[tbl_meetings] "
UpdateCommand="UPDATE tbl_meetings
SET meetingdate = #meetingdate, meetingtime = #meetingtime
WHERE meetingid = #meetingid">
<UpdateParameters>
<asp:Parameter Name="meetingdate" />
<asp:Parameter Name="meetingtime" />
</UpdateParameters>
</asp:SqlDataSource>
From the example above you can see that I am selecting 3 fields from the data base but only allowing for two to be updated (meetingdate and meetingtime).
To edit the records, the GridView must enter EditMode. The grid changes modes according to the commands it receives, in this case "edit". See the remarks on the gridview page, 'Data Operations' section, for more info.
There are basically three ways to fire the command and enter edit mode on the grid:
Use the AutoGenerateEditButton property on the grid
Use a CommandField with ShowEditButton like the other answer stated
Use a custom TemplateField with a LinkButton inside like this:
<Columns>
...
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat="server" Text="Edit" CommandName="Edit" />
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton runat="server" Text="Update" CommandName="Update" />
<asp:LinkButton runat="server" Text="Cancel" CommandName="Cancel" />
</EditItemTemplate>
</asp:TemplateField>
...
</Columns>
After that, it will depend on which DataSource control you are using. With an EntityDataSource, for instance, all you need to do is set EnableUpdate="true"

Update Command doesn't work on a specific page

I have been having issues with the update command on a page I have. I have 4 gridviews and 4 detailsviews and none of them will update with the update command. I can insert and delete but update doesn't work. The update button doesn't cause a post back, it just sits there.
I created a new page and added a detailsview and connected it to the same database and same table, and in that page the update command worked perfectly. I even copied and pasted the command queries to the detailsviews on the other page, but no success.
I'm thinking is an issue with the buttons, but why the default update link button doesn't work?
I am using ASP.NET, C# and SQL Server 2008.
I did notice that the update button on the detailsview that works shows: javascript:__doPostBack('DetailsView1$ctl02','') on the status bar.
But the update button for the one that doesn't work shows this: WebForm_PostBackOptions("ctl00$ContentPlaceHolder1$DetailsView2$ctl02", "", true, "", "", false, true))
Here's the code for the detailsview that works
<asp:DetailsView ID="DetailsView1" runat="server" AutoGenerateRows="False"
DataKeyNames="WorkshopName,WorkshopBeginingDate,WorkshopLocation"
DataSourceID="SqlDataSource1" Height="50px" Width="125px">
<Fields>
<asp:BoundField DataField="WorkshopName" HeaderText="WorkshopName"
ReadOnly="True" SortExpression="WorkshopName" />
<asp:BoundField DataField="WorkshopBeginingDate"
HeaderText="WorkshopBeginingDate" ReadOnly="True"
SortExpression="WorkshopBeginingDate" />
<asp:BoundField DataField="WorkshopEndingDate" HeaderText="WorkshopEndingDate"
SortExpression="WorkshopEndingDate" />
<asp:BoundField DataField="WorkshopLocation" HeaderText="WorkshopLocation"
ReadOnly="True" SortExpression="WorkshopLocation" />
<asp:CommandField ShowEditButton="True" />
</Fields>
</asp:DetailsView>
This is the code for one that doesn't work
<asp:DetailsView ID="DetailsView2" runat="server" AutoGenerateRows="False"
DataKeyNames="WorkshopName,WorkshopBeginingDate,WorkshopLocation"
DataSourceID="SqlDataSource20" Height="50px" Width="125px">
<Fields>
<asp:BoundField DataField="WorkshopName" HeaderText="WorkshopName"
ReadOnly="True" SortExpression="WorkshopName" />
<asp:BoundField DataField="WorkshopBeginingDate"
HeaderText="WorkshopBeginingDate" ReadOnly="True"
SortExpression="WorkshopBeginingDate" />
<asp:BoundField DataField="WorkshopEndingDate" HeaderText="WorkshopEndingDate"
SortExpression="WorkshopEndingDate" />
<asp:BoundField DataField="WorkshopLocation" HeaderText="WorkshopLocation"
ReadOnly="True" SortExpression="WorkshopLocation" />
<asp:CommandField ShowEditButton="True" />
</Fields>
</asp:DetailsView>
**This is the SQL Data source code for the one that doesn't work, it is also the same on the one that works, except for the Datasource ID.**
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConflictDetection="CompareAllValues"
ConnectionString="<%$ ConnectionStrings:WildLife_EducationConnectionString %>"
DeleteCommand="DELETE FROM [tblWorkshop] WHERE [WorkshopName] = #original_WorkshopName AND [WorkshopBeginingDate] = #original_WorkshopBeginingDate AND [WorkshopLocation] = #original_WorkshopLocation AND (([WorkshopEndingDate] = #original_WorkshopEndingDate) OR ([WorkshopEndingDate] IS NULL AND #original_WorkshopEndingDate IS NULL))"
InsertCommand="INSERT INTO [tblWorkshop] ([WorkshopName], [WorkshopBeginingDate], [WorkshopEndingDate], [WorkshopLocation]) VALUES (#WorkshopName, #WorkshopBeginingDate, #WorkshopEndingDate, #WorkshopLocation)"
OldValuesParameterFormatString="original_{0}"
SelectCommand="SELECT [WorkshopName], [WorkshopBeginingDate], [WorkshopEndingDate], [WorkshopLocation] FROM [tblWorkshop]"
UpdateCommand="UPDATE [tblWorkshop] SET [WorkshopEndingDate] = #WorkshopEndingDate WHERE [WorkshopName] = #original_WorkshopName AND [WorkshopBeginingDate] = #original_WorkshopBeginingDate AND [WorkshopLocation] = #original_WorkshopLocation AND (([WorkshopEndingDate] = #original_WorkshopEndingDate) OR ([WorkshopEndingDate] IS NULL AND #original_WorkshopEndingDate IS NULL))">
<DeleteParameters>
<asp:Parameter Name="original_WorkshopName" Type="String" />
<asp:Parameter DbType="Date" Name="original_WorkshopBeginingDate" />
<asp:Parameter Name="original_WorkshopLocation" Type="String" />
<asp:Parameter DbType="Date" Name="original_WorkshopEndingDate" />
</DeleteParameters>
<InsertParameters>
<asp:Parameter Name="WorkshopName" Type="String" />
<asp:Parameter DbType="Date" Name="WorkshopBeginingDate" />
<asp:Parameter DbType="Date" Name="WorkshopEndingDate" />
<asp:Parameter Name="WorkshopLocation" Type="String" />
</InsertParameters>
<UpdateParameters>
<asp:Parameter DbType="Date" Name="WorkshopEndingDate" />
<asp:Parameter Name="original_WorkshopName" Type="String" />
<asp:Parameter DbType="Date" Name="original_WorkshopBeginingDate" />
<asp:Parameter Name="original_WorkshopLocation" Type="String" />
<asp:Parameter DbType="Date" Name="original_WorkshopEndingDate" />
</UpdateParameters>
</asp:SqlDataSource>
After weeks of researching I decided to remove all the ajax from my page, and update started working beautifully. Apparently the some code was conflicting with the update command on the page.
I had researched the issue for weeks, readded the datasource many times but no success. My last resource was to remove all of the ajax from the page and magically everything worked.

ASP Dropdown list not changing the value

First off, I'm still getting my web dev legs under me. I've combed through piles of SO posts, blogs, newsgroups and articles and I cannot seem to fix my problem. It's very similar to at least 10 different posts I've looked at.
I have an ASP gridview, which acts as a display and a select column. When you click select it throws the data into a detailsview. I have one field that needs to be a drop down box, but whenever I change the value and click update the value that is sent to the command is the original value.
Page Markup:
<asp:TemplateField HeaderText="Planner Name">
<ItemTemplate>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="cboCurrentPlanner" runat="server" DataSourceID="plannerDataSource"
DataTextField="planner_name" DataValueField="planner_id" SelectedValue='<%# Eval("planner_id") %>' AutoPostBack="true" ></asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" />
</Fields>
<FooterStyle BackColor="#CCCC99" ForeColor="Black" />
<HeaderStyle BackColor="#333333" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="White" ForeColor="Black" HorizontalAlign="Right" />
</asp:DetailsView>
sqlDataSource:
SelectCommand="SELECT vendor_key, vendor, planner_name, street, city, state_country, planner_id, country FROM V_MAP_MarkerInfo WHERE (vendor_key = #vendor_key)"
UpdateCommand="MAP_usp_webUpdatePlanToVendor"
UpdateCommandType="StoredProcedure" onupdating="mapDetailSource_Updating" >
<SelectParameters>
<asp:ControlParameter ControlID="GridView1" Name="vendor_key"
PropertyName="SelectedValue" Type="Int32" />
</SelectParameters>
<UpdateParameters>
<asp:Parameter Name="vendor_key" Type="String" />
<asp:Parameter Name="planner_id" Type="Int32" />
<asp:Parameter Name = "vendor" Type="String" />
</UpdateParameters>
</asp:SqlDataSource>
<asp:SqlDataSource ID="plannerDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:vendor_mapConnectionString %>"
SelectCommand="SELECT [planner_id], [planner_name] FROM [MAP_planners]"
OldValuesParameterFormatString="original_{0}">
</asp:SqlDataSource>
I won't post the stored procedure code, I know that is working. The original value is the only value that makes it to the parameter.
I've tried all sorts of combinations of <%# Bind/Eval() %> postbacks but I can't find the right combination.
When I click select, I want the current planner to be selected in the dropdown list. When I select a new planner and click update I would like the planner to update. I'm not sure why this is so difficult or what I have royally screwed up to make it difficult but I am at my wits end. If at all possible, I would like an explanation of what is going on and not just the magical line of code that makes it work.
Flabbergasted is an understatement.
EDITS: ViewStateEnbabled="true" added to dropdownlist, the selectedIndexChanged event is firing.
EDIT AGAIN: Changed the planner_id to <asp:ControlParameter> added monitors to DetailsView1_OnDataBind and MapDataSource1_updating and the value is all over the place. but I can't see where it's being reset.
Do you have EnableViewState="false" set on the #Control or #Page settings? If viewstate is not enabled the control will always have the default value as the selected value. This can be set at the aspx level or the ascx level.
http://msdn.microsoft.com/en-us/library/ms972976.aspx
So I am a complete idiot, the DetailsView DataKeyNames property was not set correctly. I had accidentally added "planner_id" as a key from the wizard.
The code was fine all along. Thank you to everyone for trying, but I am a lost cause!

DropDownList in DetailsView-Issue - ddl has a value which is invalid because it doesn't exist

well I've stumbled upon similar cases of this problem, and also followed the solution approaches. But my case is quite strange, as I have 2 different DetailsView-controls (with different data), one works, the other doesn't.
So here's the problem in detail. I get the following error message:
DropDownList2 has a SelectedValue which is invalid because it does not exist in the list of items.
Parameter name: value
I am aware of this thread, and maybe I'm stupid and not seeing something. But maybe you do. I have 2 Detailsviews, which bind their data based on a dataset for one user. Both DVs have DropdownList-Controls inside their EditItemTemplates, which bind the possible values for this very column. I use SelectedValue='<%# Bind("mycolumn") %>' for my DropDownList-template exactly the same way in the 2 DVs.
As said, I am aware of code-behind workarounds, but I want to avoid those, to keep my code clean and consistent. I can't really document why I use a workaround on one DetailsView, and why I don't on the other.
Here is the code of my 2 DetailsViews:
<asp:DetailsView ID="dv_theme_ava" runat="server" Height="50px" Width="125px" AutoGenerateRows="False"
DataSourceID="SqlDataSource1" DefaultMode="Edit" AutoGenerateEditButton="True" DataKeyNames="Pat_ID">
<Fields>
<asp:TemplateField HeaderText="Theme">
<EditItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="SqlDataSource2"
DataTextField="theme" DataValueField="theme"
SelectedValue='<%# Bind("theme") %>'>
</asp:DropDownList>
<asp:Label ID="lolbel2" runat="server" Text='<%# Bind("theme") %>'></asp:Label>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:interacct_SQL_convConnectionString %>"
SelectCommand="SELECT [theme] FROM [gui_themes]"></asp:SqlDataSource>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Avatar">
<EditItemTemplate>
<asp:DropDownList ID="DropDownList2" runat="server" DataSourceID="SqlDataSource3"
DataTextField="avatar" DataValueField="avatar">
</asp:DropDownList>
<asp:Label ID="lolbel" runat="server" Text='<%# Bind("avatar") %>'></asp:Label>
<asp:SqlDataSource ID="SqlDataSource3" runat="server" ConnectionString="<%$ ConnectionStrings:interacct_SQL_convConnectionString %>"
SelectCommand="SELECT [avatar] FROM [gui_avatars]"></asp:SqlDataSource>
</EditItemTemplate>
</asp:TemplateField>
</Fields>
</asp:DetailsView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:interacct_SQL_convConnectionString %>"
SelectCommand="SELECT * FROM [pat_gui_config] WHERE ([Pat_ID] = #Pat_ID)" DeleteCommand="DELETE FROM [pat_gui_config] WHERE [Pat_ID] = #Pat_ID"
InsertCommand="INSERT INTO [pat_gui_config] ([Pat_ID], [theme], [avatar]) VALUES (#Pat_ID, #theme, #avatar)"
UpdateCommand="UPDATE [pat_gui_config] SET [theme] = #theme, [avatar] = #avatar WHERE [Pat_ID] = #Pat_ID">
<DeleteParameters>
<asp:Parameter Name="Pat_ID" Type="Int32" />
</DeleteParameters>
<InsertParameters>
<asp:Parameter Name="Pat_ID" Type="Int32" />
<asp:Parameter Name="theme" Type="String" />
<asp:Parameter Name="avatar" Type="String" />
</InsertParameters>
<SelectParameters>
<asp:SessionParameter Name="Pat_ID" SessionField="sel_pat_id" Type="Int32" />
</SelectParameters>
<UpdateParameters>
<asp:Parameter Name="theme" Type="String" />
<asp:Parameter Name="avatar" Type="String" />
<asp:Parameter Name="Pat_ID" Type="Int32" />
</UpdateParameters>
</asp:SqlDataSource>
<asp:DetailsView ID="dv_treat_edit" runat="server" AutoGenerateEditButton="True"
AutoGenerateRows="False" DataKeyNames="Tr_ID" DataSourceID="sql_newcat" DefaultMode="Edit"
Height="50px" Width="90%" AllowPaging="True" CssClass="dv_details" Style="margin: 0 auto;">
<Fields>
<asp:BoundField DataField="Tr_ID" HeaderText="Tr_ID" InsertVisible="False" ReadOnly="True"
SortExpression="Tr_ID" />
<asp:BoundField DataField="description" HeaderText="Description" SortExpression="description" />
<asp:BoundField DataField="syn_ger" HeaderText="Display Name (German)" SortExpression="syn_ger" />
<asp:TemplateField HeaderText="Type">
<EditItemTemplate>
<asp:DropDownList ID="ddl_type0" runat="server" DataSourceID="sql_ddl_type0" DataTextField="type"
DataValueField="type" SelectedValue='<%# Bind("type") %>'>
</asp:DropDownList>
<asp:SqlDataSource ID="sql_ddl_type0" runat="server" ConnectionString="<%$ ConnectionStrings:interacct_SQL_convConnectionString %>"
SelectCommand="SELECT [type] FROM [entry_type]"></asp:SqlDataSource>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Exclusive for Patient_ID">
<EditItemTemplate>
<asp:DropDownList ID="ddl_excl_pat0" runat="server" DataSourceID="sql_ddl_exclpat0"
DataTextField="Pat_ID" DataValueField="Pat_ID" SelectedValue='<%# Bind("custom_cat_for_Pat") %>'
AppendDataBoundItems="true">
<asp:ListItem Text="" Value=""></asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ID="sql_ddl_exclpat0" runat="server" ConnectionString="<%$ ConnectionStrings:interacct_SQL_convConnectionString %>"
SelectCommand="SELECT [Pat_ID] FROM [patients]"></asp:SqlDataSource>
</EditItemTemplate>
</asp:TemplateField>
</Fields>
<CommandRowStyle CssClass="dv_footer" />
<RowStyle CssClass="dv_tr" />
<PagerSettings Mode="NumericFirstLast" Position="Top" Visible="False" />
</asp:DetailsView>
<asp:SqlDataSource ID="sql_newcat" runat="server" ConnectionString="<%$ ConnectionStrings:interacct_SQL_convConnectionString %>"
SelectCommand="SELECT * FROM [treat_cat]" DeleteCommand="DELETE FROM [treat_cat] WHERE [Tr_ID] = #Tr_ID"
InsertCommand="INSERT INTO [treat_cat] ([description], [syn_ger], [type], [custom_cat_for_Pat]) VALUES (#description, #syn_ger, #type, #custom_cat_for_Pat)"
UpdateCommand="UPDATE [treat_cat] SET [description] = #description, [syn_ger] = #syn_ger, [type] = #type, [custom_cat_for_Pat] = #custom_cat_for_Pat WHERE [Tr_ID] = #Tr_ID">
<DeleteParameters>
<asp:Parameter Name="Tr_ID" Type="Int32" />
</DeleteParameters>
<InsertParameters>
<asp:Parameter Name="description" Type="String" />
<asp:Parameter Name="syn_ger" Type="String" />
<asp:Parameter Name="type" Type="String" />
<asp:Parameter Name="custom_cat_for_Pat" Type="Int32" />
</InsertParameters>
<UpdateParameters>
<asp:Parameter Name="description" Type="String" />
<asp:Parameter Name="syn_ger" Type="String" />
<asp:Parameter Name="type" Type="String" />
<asp:Parameter Name="custom_cat_for_Pat" Type="Int32" />
<asp:Parameter Name="Tr_ID" Type="Int32" />
</UpdateParameters>
</asp:SqlDataSource>
Note: the data model is quite simple. For comparison I used the 2 fields "theme" and "type". Both tables only have 1 column in my database, holding string entries.
Now, the "type"-DDL gets it's items perfectly fine, and has the SelectedValue bound to the value brought to the DetailsView by the datasource. When I bind the "theme"-DDL with SelectedValue, I get the error. Interesting: in the same EditItemTemplate I have set up a Label (ID "lolbel2" :p) to check the databinding. It works (of course, when I remove the SelectedValue from the DDL). So without the SelectedValue in the DDL my output is like
[DROPDOWNLIST] with items "space", "magic"
[LABEL] with text "magic" (since this is the value of my test-user).
Am I missing something? Am I completely nuts?
So, sorry for re-asking this question for like the 10th-time, but I want to UNDERSTAND what my code does.
Thanks in advance!
Konrad
Ooooohkay. Found the problem, that's what you get when you are stubborn as a goat. :)
When debugging a workaround with a HiddenField I noticed that the value, which gets bound the same way as the Label-Control, has some trailing whitespace. In particular: instead of "dog" I got "dog ". While this isn't shown in the asp:Label, I guess this was the reason why the value wasn't found in the DropDownList.
Where did the whitespace come from? In my SQL table I created the columns for "theme" and avatar as "nchar", and not "nvarchar". Apparently when using "nchar" as DataType the not-used chars of the tupels are filled with whitespace, or let's say the fields have fixed width (always x chars).
Changing the datatype to "nvarchar" helped me to get rid of the whitespace, and now the databinding of the DDLs works just fine.
I am documenting this, as maybe someone else will stumble over this aswell - and since there are 50 solutions and workarounds, maybe just taking a look at the database sometimes does the trick.

Formview EditItemTemplate in asp.net c#

I have a product table that am updating. the fields updated are category_id, prod_name, prod_desc, prize, status. I am using a formview to do that updating. however i am having problems with the category_id. the category_id is a databound dropdownlist using a sqldatasource to fetch id and name from category table in the database. When a product has no category_id value, a null value is entered by default by sql.
The problem comes when i go to edititemtemplate mode in formview, the dropdownlist cannot show a null value from db so it throws an exception of:
'category_idDropdown' has a SelectedValue which is invalid because it
does not exist in the list of items. Parameter name: value
this is my code in the updateprod.aspx page:
<asp:DropDownList ID="category_idDropdown" runat="server"
AppendDataBoundItems="True"
AutoPostBack="True"
DataSourceID="catnames"
DataTextField="category_name"
DataValueField="category_id" ViewStateMode="Enabled"
SelectedValue='<%# Bind("category_id") %>' >
<asp:ListItem Text="-- Choose Category--" Value="0" Selected="True">
</asp:ListItem>
</asp:DropDownList>
this is my sqldatasource code the dropdownlist is databound to:
<asp:SqlDataSource ID="catnames" runat="server"
ConnectionString="<%$ ConnectionStrings:cloud_Kewl.Properties.Settings.conString %>"
SelectCommand="SELECT [category_id], [category_name] FROM [category]">
</asp:SqlDataSource>
& finally this is the sqldatasource used to update the product details:
<asp:SqlDataSource ID="productUpdate" runat="server"
ConnectionString="<%$ ConnectionStrings:cloud_Kewl.Properties.Settings.conString %>"
SelectCommand="SELECT prod_id, category_id, prod_name, prod_desc, prod_price, img_name, img_contenttype, prod_img, status FROM product WHERE (prod_id = #prod_id)"
UpdateCommand="UPDATE product SET category_id = #category_id, prod_name = #prod_name, prod_desc = #prod_desc, prod_price = #prod_price, status = #status WHERE (prod_id = #prod_id)">
<SelectParameters>
<asp:QueryStringParameter Name="prod_id" QueryStringField="prod_id" Type="Int32" />
</SelectParameters>
<UpdateParameters>
<asp:Parameter Name="category_id" Type="Int32" DefaultValue="0" />
<asp:Parameter Name="prod_name" Type="String" />
<asp:Parameter Name="prod_desc" Type="String" />
<asp:Parameter Name="prod_price" Type="Decimal" />
<asp:Parameter Name="status" Type="String" />
<asp:Parameter Name="prod_id" Type="Int32" />
</UpdateParameters>
</asp:SqlDataSource>
i looked up in the questions regarding the formview and edititemtemplate in this site, but none came close to give me any idea on how to approach this problem.
I tried to solve it programatically but not success in cracking this problem. Please help me, i looked for the solution for 3 weeks. no success :(
Try rebinding your datasource prior to the null value being set:
protected void myFormView_OnItemEditing(object sender, ListViewEditEventArgs e)
{
DropDownList category_idDropdown = (DropDownList)(myFormView.FindControl("category_idDropDown"));
category_idDropdown.DataBind();
category_idDropdown.Items.Add(0, new ListItem("Select", null));
}
The problem likely isn't that you're trying to select a value that doesn't exist, but rather that you're trying to bind a DropDownList that already has a null value to a datasource that doesn't contain that value.

Categories