Eval()、XPath() 和 Bind() 这类数据绑定方法只能在数据绑定控件的上下文中使用。 (FromView)

在formview里面放3个联动到dropdownlist到时候会出现这样到错误信息。
查找了中文博客,没有任何到解释,终于在找国外资料到时候找到了这个问题到完全解决方案,非常到不错。

Demo for 2-way databinding cascading lists within a FormView

You might have wanted to use inside a databound templated server control (e.g. the FormView or the GridView) several cascading dropdownlists. The listitems in each dropdownlist would change based on the selection of the previous dropdownlist, e.g. the city selections would change based on the province and the latter would change based on the country selection. Sounds easy? Well, you added to your webform a datasource object linked for each dropdownlist where the SelectParameters collection contains a ControlParameter pointing to the previous list.

But you encounter any of those 2 error messages:

  1. Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control
  2. 'DropDownList1' has a SelectedValue which is invalid because it does not exist in the list of items.

"What is the problem?", you ask. Well, it is not a bug by Microsoft's judgement (look at this Bug Report)

When you have a dropdownlist that is dependent on another within a FormView server control, it becomes populated on SelectedIndexChanged event of the first dropdown list. However, in this case the template was not rebound to the data, only the dropdown list. The FormView was reconstructed from the saved ViewState. This causes the error message: "Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control".

The solution is to remove the 2-way databinding from the cascading dropdownlists and replace it with customized code during processing the ItemUpdating event.

Let me expand a bit on the last sentence because people who visited the site asked for such an explanation. What are the problems again?

  1. The problem of populating the dependant lists: When one list changes the second list needs to be re-bound to the data based on the previous list selection. To do that using the BIND statement, the container must be databound. But upon postback from the first list the container is not databound rather it is reconstructed from the viewstate
  2. The problem of saving the values of the dependent lists after the user makes a selection: When updating the results without the BIND statement on the SelectedValue property of the cascading lists, you need to handle the ItemUpdating event to update the values manually to the data store.

Click on the Edit link (of the FormView display above) to activate the EditItemTemplate of the FormView. Change the country selection to watch the province/State and city selections change accordingly. Then you can view the same concepts applied to the GridView by clicking on the tab for the GridView above. The source code is available in 4 versions based on the type of datasource and the programming language that you use.

Notice that every button click on this demo posts the entire page back to the server and causes the entire screen to flash back. This distracts from the viewing experience and it has a cost on band width where the entire navigational controls are being posted back and refreshed. Compare this to the same sample but while using MS ASP.NET AJAX.

完整代码:

  1<%@ Import Namespace="System.Data" %>
  2
  3<%@ Page Language="C#" AutoEventWireup="false" MasterPageFile="~/WEBSWAPP.master" %>
  4
  5<script language="C#" runat="server">
  6    
  7    //As the FormView becomes databound, the DataBound events of the dropdownlists
  8    //will trigger.  At this stage the page has not been rendered yet and we can 
  9    //manipulate the displayed values on the dropdownlists
 10    protected void ddlProvince_DataBound(object sender, EventArgs e)
 11    {
 12        DropDownList ddl = (DropDownList)sender;
 13        //add an empty item on top of the list
 14        AddEmptyItem(ddl);
 15        FormView frmV = (FormView)ddl.NamingContainer;
 16        if (frmV.DataItem != null)
 17        {
 18            //Let's pull the province value from the databound item.  The data
 19            //in my application is supplied by BLL as a dataview.  Therefore each
 20            //item bound to the FormView is of type DataRowView.  So let's cast 
 21            //that DataItem to the appropriate type to be able to use it
 22            string strProvinceID = ((DataRowView)frmV.DataItem)["ProvinceID"].ToString ();
 23
 24            ddl.ClearSelection();
 25            //be careful of the possibility that the value saved on the
 26            //database does not exist in the valid selections that are displayed
 27            //on the list
 28            ListItem li = ddl.Items.FindByValue(strProvinceID );
 29            if (li != null) li.Selected = true;
 30        }

 31        //since the city selection is dependent on the province, we
 32        //have to databind the city list after we changed the selection for the province
 33        ddl = (DropDownList)frmV.FindControl("ddlCity");
 34        if (ddl != null) ddl.DataBind();
 35
 36    }

 37
 38    void FormView1_PageIndexChanging(object sender, FormViewPageEventArgs e)
 39    {
 40        ClientScriptManager cs = Page.ClientScript;
 41        Type cstype = this.GetType();
 42        if (FormView1.CurrentMode == FormViewMode.Edit)
 43        {
 44            // Check to see if the startup script is already registered.
 45            if (!cs.IsStartupScriptRegistered(cstype, "AlertMessage"))
 46            {
 47                String cstext = "alert('You cannot navigate to another page while in Edit mode. Please complete the Edit operation first.');";
 48                cs.RegisterStartupScript(cstype, "AlertMessage", cstext, true);
 49            }

 50            lblStatus.Text = "Your last operation (navigating to another page) has failed because you are in Edit mode.";
 51            e.Cancel = true;
 52        }

 53    }

 54
 55    protected void ddlCity_DataBound(object sender, EventArgs e)
 56    {
 57        DropDownList ddl = (DropDownList)sender;
 58        FormView frmV = (FormView)ddl.NamingContainer;
 59        if (frmV.DataItem != null)
 60        {
 61            string  strCityID = ((DataRowView)frmV.DataItem)["CityID"].ToString ();
 62            ddl.ClearSelection();
 63            ListItem lm = ddl.Items.FindByValue(strCityID );
 64            if (lm != null) lm.Selected = true;
 65        }

 66        //add an empty item on top of the list
 67        AddEmptyItem(ddl);
 68    }

 69    //==============================================================================================
 70    //The concept is basically to intercept the databinding within the ItemUpdating event 
 71    //by passing into the FormViewUpdateEventArgs the new values that we need to update.  
 72    //This interception gives us the opportunity to set the selections for the cascading dropdownlist
 73    //without relying on the Bind method to effect the 2-way databinding
 74    //==============================================================================================
 75    protected void FormView1_ItemUpdating(object sender, FormViewUpdateEventArgs e)
 76    {
 77        //in my datatable I only need the CityID which I relate to another Table containing
 78        //a list of all cities where the CityID is a primary key that allows me to determine
 79        //the province and country (in case there were 2 cities with the
 80        //the same name in 2 different countries then there are 2 records with 2 different PK_ID)
 81        if (Page.IsValid)
 82        {
 83            string strCityID = ((DropDownList)((FormView)sender).FindControl("ddlCity")).SelectedValue ;
 84            e.NewValues["CityID"= Convert.ToInt32 (strCityID);
 85            e.Cancel = false;
 86        }

 87        else e.Cancel = true;
 88    }

 89
 90
 91    void FormView1_ItemCommand(object sender, FormViewCommandEventArgs e)
 92    {
 93        if (e.CommandName == "Cancel") FormView1.ChangeMode(FormViewMode.ReadOnly);
 94    }

 95
 96    protected void FormView1_ItemInserting(object sender, FormViewInsertEventArgs e)
 97    {
 98        //in my datatable I only need the CityID which I relate to another Table containing
 99        //a list of all cities where the CityID is a primary key that allows me to determine
100        //the province and country (in case there were 2 cities with the
101        //the same name in 2 different countries then there are 2 records with 2 different PK_ID)
102        if (Page.IsValid)
103        {
104            //we will apply the same logic as above while inserting a new record
105            string strCityID = ((DropDownList)((FormView)sender).FindControl("ddlCity")).SelectedValue;
106            e.Values ["CityID"= Convert.ToInt32(strCityID);
107            e.Cancel = false;
108        }

109        else e.Cancel = true;
110    }

111
112    void odsAddresses_Inserted(object sender, ObjectDataSourceStatusEventArgs e)
113    {
114        //set the current page to the newly inserted record after inserting
115        //by using the returnValue (which in my Business Logic Layer is returning
116        //the position of the newly inserted record which is the page number on the FormView)
117        FormView1.PageIndex = Convert.ToInt16(e.ReturnValue.ToString());
118    }

119
120    void AddEmptyItem(DropDownList ddl)
121    {
122        ListItem li = new ListItem("Make a Selection""");
123        ddl.Items.Insert(0, li);
124
125    }

126
127
128</script>
129
130<asp:Content ID="Content2" runat="server" ContentPlaceHolderID="ContentPlaceHolder1">
131
132    <table>
133        <tr>
134            <td>
135                <h3>
136                    Demo for 2-way databinding cascading lists within a FormView</h3>
137                <asp:FormView ID="FormView1" runat="server" DataSourceID="odsAddresses" AllowPaging="True"
138                    OnItemUpdating="FormView1_ItemUpdating" OnItemInserting="FormView1_ItemInserting" DataKeyNames="PK_ID"
139                    OnItemCommand="FormView1_ItemCommand" OnPageIndexChanging="FormView1_PageIndexChanging" >
140                    <EditItemTemplate>
141                        <%---------------------EditItemTemplate Object datasources definitions----------------------------------- 
142                        Notice that the object datasources are specific to this template and are declared withint its boundaries
143                        --------------------------------------------------------------------------------------------------------%>
144                        <asp:ObjectDataSource ID="odsCountries" runat="server" SelectMethod="CountryList"
145                            TypeName="WEBSWAPP_BLL.Demos"></asp:ObjectDataSource>
146                        <asp:ObjectDataSource ID="odsProvinces" runat="server" SelectMethod="ProvincesList"
147                            TypeName="WEBSWAPP_BLL.Demos">
148                            <SelectParameters>
149                                <asp:ControlParameter ControlID="ddlCountry" Name="CountryID" PropertyName="SelectedValue"
150                                    Type="String" />
151                            </SelectParameters>
152                        </asp:ObjectDataSource>
153                        <asp:ObjectDataSource ID="odsCities" runat="server" SelectMethod="CitiesList" TypeName="WEBSWAPP_BLL.Demos">
154                            <SelectParameters>
155                                <asp:ControlParameter ControlID="ddlProvince" Name="ProvinceID" PropertyName="SelectedValue"
156                                    Type="String" />
157                            </SelectParameters>
158                        </asp:ObjectDataSource>
159                        <%-------------- end of the object datasource difinitions for the EditItemTempalte  ----------%>
160                        <%-------------  Begin of markup for the EditItemTemplate  -----------------------------------%>
161                        <%-- create a panel to be able to mark the Update hyperlink as the default button so that if
162                        the user presses the Enter key while editing the Update button will clicked --%>
163                        <asp:Panel ID="PanelForEditTemplate" runat="server" DefaultButton="UpdateButton">
164                            <table class="CascadingDemo1">
165                                <caption>
166                                    FormView in Edit mode</caption>
167                                <thead>
168                                    <tr>
169                                        <th>
170                                            ID
171                                        </th>
172                                        <th>
173                                            <asp:Label ID="lblID" runat="server" Text='<%# Eval("PK_ID") %>'></asp:Label>
174                                        </th>
175                                        <th class="Origin">
176                                            Original Values</th>
177                                    </tr>
178                                </thead>
179                                <tr>
180                                    <td class="label2">
181                                        Company
182                                    </td>
183                                    <td colspan="2">
184                                        <asp:TextBox MaxLength="50" Width="300" ID="txtCompany" runat="server" Text='<%# Bind("Company") %>'></asp:TextBox>
185                                        <%-- Let's add a requiredfieldvalidator to ensure that edited values are not empty
186                                    but notice to set the CausesValidation=false on the Cancel CommandButton --%>
187                                        <asp:RequiredFieldValidator ID="valCompany" runat="Server" ControlToValidate="txtCompany"
188                                            ForeColor="white" ErrorMessage="Cannot leave the company name empty" Text="*"
189                                            SetFocusOnError="true" Display="Dynamic"></asp:RequiredFieldValidator>
190                                    </td>
191                                </tr>
192                                <tr>
193                                    <td class="label2">
194                                        Street Address
195                                    </td>
196                                    <td colspan="2">
197                                        <asp:TextBox ID="txtStreet" MaxLength="50" Width="300" runat="server" Text='<%# Bind("Street") %>'></asp:TextBox>
198                                        <asp:RequiredFieldValidator ID="valStreet" runat="Server" ControlToValidate="txtStreet"
199                                            ForeColor="white" ErrorMessage="Cannot leave the street address empty" Text="*"
200                                            SetFocusOnError="true" Display="Dynamic"></asp:RequiredFieldValidator>
201                                    </td>
202                                </tr>
203                                <tr>
204                                    <td class="label2">
205                                        Country
206                                    </td>
207                                    <td>
208                                        <asp:DropDownList ID="ddlCountry" runat="server" DataSourceID="odsCountries" AutoPostBack="True"
209                                            SelectedValue='<%# Eval("CountryID") %>'  DataTextField="Description" DataValueField="PK_ID">
210                                        </asp:DropDownList>
211                                    </td>
212                                    <td class="Origin">
213                                        <asp:Label ID="lblCountry" runat="server" Text='<%# Eval("Country") %>'></asp:Label>
214                                    </td>
215                                </tr>
216                                <tr>
217                                    <td class="label2">
218                                        Province/State
219                                    </td>
220                                    <td>
221                                        <asp:DropDownList ID="ddlProvince" runat="server" DataSourceID="odsProvinces" AutoPostBack="true"
222                                            OnDataBound="ddlProvince_DataBound"  DataTextField="Description" DataValueField="PK_ID">
223                                        </asp:DropDownList>
224                                        <asp:RequiredFieldValidator ForeColor="white" ID="valddlProvince" runat="server"
225                                            ErrorMessage="Cannot leave the province selection blank" Text="*" Display="Dynamic"
226                                            ControlToValidate="ddlProvince"></asp:RequiredFieldValidator>
227                                    </td>
228                                    <td class="Origin">
229                                        <asp:Label ID="lblProvince" runat="server" Text='<%# Eval("Province") %>'></asp:Label>
230                                    </td>
231                                </tr>
232                                <tr>
233                                    <td class="label2">
234                                        City
235                                    </td>
236                                    <td>
237                                        <asp:DropDownList ID="ddlCity" runat="server" DataSourceID="odsCities" OnDataBound="ddlCity_DataBound"
238                                         DataTextField="Description" DataValueField="PK_ID">
239                                        </asp:DropDownList>
240                                        <asp:RequiredFieldValidator ForeColor="white" ID="valddlCity" runat="server" ErrorMessage="Cannot leave the city selection blank"
241                                            Text="*" Display="Dynamic" ControlToValidate="ddlCity" ></asp:RequiredFieldValidator>
242                                    </td>
243                                    <td class="Origin">
244                                        <asp:Label ID="lblCity" runat="server" Text='<%# Eval("City") %>'></asp:Label>
245                                    </td>
246                                </tr>
247                            </table>
248                            <asp:LinkButton ID="UpdateButton" runat="server" CommandName="Update" Text="Update"></asp:LinkButton>
249                            <asp:LinkButton ID="btnCancel" CausesValidation="false" runat="server" CommandName="Cancel"
250                                Text="Cancel"></asp:LinkButton>
251                        </asp:Panel>
252                        <%---------------------- end of markup for the EditItemTemplate ---------------------------%>
253                    </EditItemTemplate>
254                    <ItemTemplate>
255                        <table class="CascadingDemo1">
256                            <caption >
257                                FormView in ReadOnly mode</caption>
258                            <tr>
259                                <td>
260                                    Company
261                                </td>
262                                <td>
263                                    <asp:Label ID="lblCompany" runat="server" Text='<%# Eval("Company") %>'></asp:Label>
264                                </td>
265                            </tr>
266                            <tr>
267                                <td>
268                                    Street Address
269                                </td>
270                                <td>
271                                    <asp:Label ID="lblStreet" runat="server" Text='<%# Eval("Street") %>'></asp:Label>
272                                </td>
273                            </tr>
274                            <tr>
275                                <td>
276                                    Country
277                                </td>
278                                <td>
279                                    <asp:Label ID="lblCountry" runat="server" Text='<%# Eval("Country") %>'></asp:Label>
280                                </td>
281                            </tr>
282                            <tr>
283                                <td>
284                                    Province/State
285                                </td>
286                                <td>
287                                    <asp:Label ID="lblProvince" runat="server" Text='<%# Eval("Province") %>'></asp:Label>
288                                </td>
289                            </tr>
290                            <tr>
291                                <td>
292                                    City
293                                </td>
294                                <td>
295                                    <asp:Label ID="lblCity" runat="server" Text='<%# Eval("City") %>'></asp:Label>
296                                </td>
297                            </tr>
298                        </table>
299                        <asp:LinkButton ToolTip="Click here to Edit the record" Text="Edit" runat="server"
300                            ID="Edit" CommandName="Edit"></asp:LinkButton>
301                        <asp:LinkButton ToolTip="Click here to insert a new Record" Text="Insert" runat="server"
302                            ID="Insert" CommandName="New"></asp:LinkButton>
303                    </ItemTemplate>
304                    <InsertItemTemplate>
305                        <%-----------------------------------------------------------------------------------------------------
306                        Object Datasources defintions for the InsertItemTemplate
307                        Notice that these definitions are specific to this tempalte and are only visible within its defintition
308                       --------------------------------------------------------------------------------------------------------%>
309                        <asp:ObjectDataSource ID="odsCountries" runat="server" SelectMethod="CountryList"
310                            TypeName="WEBSWAPP_BLL.Demos"></asp:ObjectDataSource>
311                        <asp:ObjectDataSource ID="odsProvinces" runat="server" SelectMethod="ProvincesList"
312                            TypeName="WEBSWAPP_BLL.Demos">
313                            <SelectParameters>
314                                <asp:ControlParameter ControlID="ddlCountry" Name="CountryID" PropertyName="SelectedValue"
315                                    Type="String" />
316                            </SelectParameters>
317                        </asp:ObjectDataSource>
318                        <asp:ObjectDataSource ID="odsCities" runat="server" SelectMethod="CitiesList" TypeName="WEBSWAPP_BLL.Demos">
319                            <SelectParameters>
320                                <asp:ControlParameter ControlID="ddlProvince" Name="ProvinceID" PropertyName="SelectedValue"
321                                    Type="String" />
322                            </SelectParameters>
323                        </asp:ObjectDataSource>
324                        <asp:Panel ID="PanelForInsertTemplate" runat="server" DefaultButton="btnInsert">
325                            <table class="CascadingDemo1">
326                                <caption >
327                                    FormView in Insert mode</caption>
328                                <tr>
329                                    <td class="label2">
330                                        Company
331                                    </td>
332                                    <td>
333                                        <asp:TextBox MaxLength="50" Width="300" ID="txtCompany" runat="server" Text='<%# Bind("Company") %>'></asp:TextBox>
334                                        <%-- Let's add requiredfieldvalidators to ensure that newly inserted records receive values 
335                                    but notice to set the CausesValidation=false on the Cancel CommandButton --%>
336                                        <asp:RequiredFieldValidator ID="valCompany" runat="Server" ControlToValidate="txtCompany"
337                                            ForeColor="white" ErrorMessage="Cannot leave the company selection empty" Text="*"
338                                            SetFocusOnError="true" Display="Dynamic"></asp:RequiredFieldValidator>
339                                    </td>
340                                </tr>
341                                <tr>
342                                    <td class="label2">
343                                        Street Address
344                                    </td>
345                                    <td>
346                                        <asp:TextBox ID="txtStreet" MaxLength="50" Width="300" runat="server" Text='<%# Bind("Street") %>'></asp:TextBox>
347                                        <asp:RequiredFieldValidator ID="valStreet" runat="Server" ControlToValidate="txtStreet"
348                                            ForeColor="white" ErrorMessage="Cannot leave the street selection empty" Text="*"
349                                            SetFocusOnError="true" Display="Dynamic"></asp:RequiredFieldValidator>
350                                    </td>
351                                </tr>
352                                <tr>
353                                    <td class="label2">
354                                        Country
355                                    </td>
356                                    <td>
357                                        <%-- when we insert a new record there is no country value to be bound upon
358                                displaying the empty record.  Therefore let's add a default listitem with a null
359                                value so that we can validate it using a RequiredFieldValidator to ensure that
360                                the user will enter a value in it.  I will use here the AppendDataBoundItems
361                                property of the dropdownlist so that any databound items to be created will not
362                                replace the default listitem that I just created. --%>
363                                        <asp:DropDownList ID="ddlCountry" runat="server" DataSourceID="odsCountries" AutoPostBack="True"
364                                            SelectedValue='<%# Eval("CountryID") %>'  DataTextField="Description" DataValueField="PK_ID" AppendDataBoundItems="true">
365                                            <asp:ListItem Value="">Select a Country</asp:ListItem>
366                                        </asp:DropDownList>
367                                        <asp:RequiredFieldValidator ForeColor="white" ID="valddlCountry" runat="server" ErrorMessage="Cannot leave the country blank"
368                                            Text="*" Display="Dynamic" ControlToValidate="ddlCountry"></asp:RequiredFieldValidator>
369                                    </td>
370                                </tr>
371                                <tr>
372                                    <td class="label2">
373                                        Province/State
374                                    </td>
375                                    <td>
376                                        <asp:DropDownList ID="ddlProvince" runat="server" DataSourceID="odsProvinces" AutoPostBack="true"
377                                             DataTextField="Description" DataValueField="PK_ID" OnDataBound="ddlProvince_DataBound">
378                                            <asp:ListItem Value="">Select a Province</asp:ListItem>
379                                        </asp:DropDownList>
380                                        <asp:RequiredFieldValidator ForeColor="white" ID="valddlProvince" runat="server"
381                                            ErrorMessage="Cannot leave the province selection blank" Text="*" Display="Dynamic"
382                                            ControlToValidate="ddlProvince"></asp:RequiredFieldValidator>
383                                    </td>
384                                </tr>
385                                <tr>
386                                    <td class="label2">
387                                        City
388                                    </td>
389                                    <td>
390                                        <asp:DropDownList ID="ddlCity" runat="server" DataSourceID="odsCities" OnDataBound="ddlCity_DataBound"
391                                         DataTextField="Description" DataValueField="PK_ID">
392                                            <asp:ListItem Value="">Select a City</asp:ListItem>
393                                        </asp:DropDownList>
394                                        <asp:RequiredFieldValidator ForeColor="white" ID="valddlCity" runat="server" ErrorMessage="Cannot leave the city selection blank"
395                                            Text="*" Display="Dynamic" ControlToValidate="ddlCity"></asp:RequiredFieldValidator>
396                                    </td>
397                                </tr>
398                            </table>
399                            <asp:LinkButton ID="btnInsert" runat="server" CommandName="Insert" Text="Insert"></asp:LinkButton>
400                            <asp:LinkButton ID="btnCancel" runat="server" CausesValidation="false" CommandName="Cancel"
401                                Text="Cancel"></asp:LinkButton>
402                        </asp:Panel>
403                    </InsertItemTemplate>
404                </asp:FormView>
405                <%-- The object Datasource definition for the FormView is declared outside of the FormView
406                --------------------------------------------------------------------------------------------------%>
407                <asp:ObjectDataSource ID="odsAddresses" runat="server" SelectMethod="Contacts" TypeName="WEBSWAPP_BLL.Demos"
408                    UpdateMethod="UpdateContact" InsertMethod="InsertContact" OnInserted="odsAddresses_Inserted" 
409                   >
410                    <UpdateParameters>
411                        <asp:Parameter Name="PK_ID" Type="Int32" />
412                        <asp:Parameter Name="Company" Type="String" />
413                        <asp:Parameter Name="Street" Type="String" />
414                        <asp:Parameter Name="CityID" Type="Int32" />
415                    </UpdateParameters>
416                    <InsertParameters>
417                        <asp:Parameter Name="Company" Type="String" />
418                        <asp:Parameter Name="Street" Type="String" />
419                        <asp:Parameter Name="CityID" Type="Int32" />
420                    </InsertParameters>
421                </asp:ObjectDataSource>
422                <%-- let's add a summary validation control to display a pop up message --%>
423                <asp:ValidationSummary ID="valSumm" runat="server" ShowMessageBox="true" ShowSummary="false" />
424                <%-- Let's add a label to display any status--%>
425                <asp:Label ID="lblStatus" runat="server" EnableViewState="false" CssClass="ErrMessage"></asp:Label>
426            </td>
427        </tr>
428   
429    </table>
430</asp:Content>
431
posted @ 2007-10-31 15:44  Fernando  阅读(7285)  评论(1编辑  收藏  举报