I am new to ASP.NET and currently having problem with dropdownlists in the DetailsView.
Exception error: System.InvalidOperationException: Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control.
I have this code my code behind to refresh the list for the dropdownlists in DetailsView
protected void ddlVendor_SelectedIndexChanged
(object sender, EventArgs e)
{
DropDownList ddlVendorBB =
(DropDownList)DetailsView1.FindControl("VendorBUName");
if (ddlVendorBB != null)
{
Response.Write("SelectChanged");
ddlVendorBB.DataBind();
}
}
protected void SqlDataSourceProd_Selecting
(object sender, SqlDataSourceSelectingEventArgs e)
{
DropDownList ddlVendor =
(DropDownList)DetailsView1.FindControl("VendorName");
if (ddlVendor != null)
{
e.Command.Parameters["@VendorID"].Value = ddlVendor.SelectedValue;
}
}
These two dropdownlists in the DetailsView
<EditItemTemplate>
<asp:DropDownList id="VendorName"
datasourceid="VendorSqlDataSource"
AutoPostBack="true"
datatextfield="VendorName"
DataValueField="VendorID"
SelectedValue='<%# Bind("VendorID") %>'
runat="server"
OnSelectedIndexChanged="ddlCategory_SelectedIndexChanged" />
<asp:SqlDataSource ID="VendorSqlDataSource"
ConnectionString="<%$Connectionstrings:ConnectionString%>"
SelectCommand="SELECT VendorID, VendorName from MDF_Vendor"
runat="server">
</asp:SqlDataSource>
</EditItemTemplate>
<EditItemTemplate>
<asp:DropDownList id="VendorBUName"
datasourceid="VendorBUSqlDataSource"
datatextfield="VendorBUName"
DataValueField="VendorBUID"
SelectedValue='<%# Bind("VendorBUID") %>'
runat="server"/>
<asp:SqlDataSource ID="VendorBUSqlDataSource"
runat="server"
ConnectionString="<%$Connectionstrings:ConnectionString%>"
selectcommand="SELECT VendorBUID, VendorBUName
from MDF_VendorBU
Where VendorID = @VendorID"
OnSelecting="SqlDataSourceProd_Selecting">
<SelectParameters>
<asp:Parameter Name="VendorID" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
</EditItemTemplate>
Problem is:
If I leave SelectedValue= there, the dropdownlists in Edit mode seletected the correct value in the items listed when I first click Edit, but when I select a new VendorName, it errors “Databining method such as Eval(), Xpath(), and Bind()… “.
Now, if I removed the Selectedvalued for the dropdownlists, it will work for refreshing the VendorBUName when select a new VendorName, but NOT not selected the default VendorID when I click “Edit”. It just list the VendorName list without selected the current VendorID one.
Can someone please let me know what wrong in my codes? Thanks!
As the error states, you cannot use Bind where you are trying to use it. You should be able to use the DataBinder though
Edit: Since binding a value to the SelectedValue with DataBinder didn’t work, you can try to set the value when binding data. Provided dataSource is some instance of a class that has a property called
VendorBUID, something similar to this might work in