Problem with cascading drop down in asp.net [duplicate] - c#

I am having problem in EditItemTemplate of FormView.
When I use such code in InsertItemTemplate everything works:
<asp:DropDownList ID="Lic_PosiadaczLicencjiIDDropDownList" runat="server"
SelectedValue='<%# Bind("Lic_PosiadaczLicencjiID") %>' />
<asp:CascadingDropDown ID="CascadingDropDown1" runat="server"
TargetControlID="Lic_PosiadaczLicencjiIDDropDownList" Category="Knt_Kod"
ServicePath="~/ManagerLicencjiService.asmx" ServiceMethod="GetKontrahenci">
</asp:CascadingDropDown>
But when I use exactly the same code in EditItemTemplate I am getting an error that SelectedValue is wrong cause it doesn't exists on the list of elements.
I think that the problem is that DropDownList is checked for the values before it is populated by the service. When I run debugger the error occured before breakpoint in the service method.
How to solve this problem?

<rant>I've found the CCD very clunky and full of poorly-documented workarounds</rant> but here is how you do something as simple as selecting a value when filling the ddl. Note that the selected value is not set on the DDL and that it is being passed to the web service where the selecting is done.
<asp:ScriptManager ID="sm1" runat="server"></asp:ScriptManager>
<asp:FormView ID="fv1" runat="server" DataSourceID="yourDataSource">
<EditItemTemplate>
<asp:DropDownList ID="Lic_PosiadaczLicencjiIDDropDownList" runat="server" />
<asp:CascadingDropDown ID="CascadingDropDown1" runat="server"
TargetControlID="Lic_PosiadaczLicencjiIDDropDownList" Category="Knt_Kod"
ServicePath="~/ManagerLicencjiService.asmx" ServiceMethod="GetKontrahenci"
UseContextKey="true" ContextKey='<%# Bind("Lic_PosiadaczLicencjiID") %>'>
</asp:CascadingDropDown>
</EditItemTemplate>
</asp:FormView>
<asp:sqldatasource id="yourDataSource"
selectcommand="select Lic_PosiadaczLicencjiID FROM yourdatabase"
UpdateCommand="Update yourdatabase set Lic_PosiadaczLicencjiID = #newvalue WHERE Lic_PosiadaczLicencjiID = #Lic_PosiadaczLicencjiID"
connectionstring="<%$ ConnectionStrings:yourConnectionString %>"
runat="server"
onupdating="yourDataSource_Updating">
<UpdateParameters>
<asp:Parameter Name="newvalue" DbType="String" />
</UpdateParameters>
</asp:sqldatasource>
code behind:
protected void yourDataSource_Updating(object sender, SqlDataSourceCommandEventArgs e)
{
e.Command.Parameters["#newvalue"].Value = ((DropDownList)fv1.FindControl("Lic_PosiadaczLicencjiIDDropDownList")).SelectedValue;
}
and in your web service where you are getting your data from you need to add the context key to the signature exactly as shown as it is case sensitive. You then check your returned values for the selected value and set selected = true. If you want selected value instead of selected text then check for x.value instead of x.name.
[WebMethod]
public CascadingDropDownNameValue[] GetKontrahenci(string knownCategoryValues, string category, string contextKey)
{
CascadingDropDownNameValue[] results = getdata();
CascadingDropDownNameValue selectedVal = (from x in results where x.name == contextKey select x).FirstOrDefault();
if (selectedVal != null)
selectedVal.isDefaultValue = true;
return results;
}
Hope this helps!

Related

RadDropDownList OnSelectedIndexChanged event not firing in server

I have a web application that uses a few dropdown lists that are nested. (Selection of DDL1 will be a parameter for DDL2 etc).
My problem is when I run my application with Visual Studio this DDL1 works as expected firing the SelectedIndexChanged event populating DDL2.
When I publish the same code to the server and access the web application DDL1's SelectedIndexChanged event doesn't fire.
What could be the problem to this?
Here is my Code,
<telerik:RadDropDownList ID="RadDropDownList_Warehouse" runat="server" DataSourceID="SqlDataSource_Warehouse" CausesValidation="false" DataTextField="WarehouseName" DataValueField="WarehouseId" DefaultMessage="Select..." Font-Size="12px" Skin="Metro"
Width="260px" ValidationGroup="save" AutoPostBack="true" OnSelectedIndexChanged="RadDropDownList_Warehouse_SelectedIndexChanged" ViewStateMode="Enabled" EnableViewState="true">
</telerik:RadDropDownList>
<asp:SqlDataSource ID="SqlDataSource_Warehouse" runat="server" ConnectionString="<%$ ConnectionStrings:STNRequisitionConnectionString %>" SelectCommand="SELECT DISTINCT wd.WarehouseId, wd.WarehouseName, vrmpm.IsDeleted FROM WarehouseDetails AS wd INNER JOIN V_RequestMakerPermissionMatrix AS vrmpm ON wd.WarehouseId = vrmpm.WarehouseId WHERE (vrmpm.UserName = #username) AND (vrmpm.IsDeleted = 0)">
<SelectParameters>
<asp:ControlParameter ControlID="HiddenField1" Name="username" PropertyName="Value" />
</SelectParameters>
</asp:SqlDataSource>
<asp:RequiredFieldValidator ID="RequiredFieldValidator_Warehouse" runat="server" ControlToValidate="RadDropDownList_Warehouse" ErrorMessage="Can not be empty!" Font-Bold="False" Font-Size="12px" ForeColor="Red" ValidationGroup="save"></asp:RequiredFieldValidator>
protected void RadDropDownList_Warehouse_SelectedIndexChanged(object sender, DropDownListEventArgs e)
{
string message = STNLogger.CreateMessage("Warehouse Selected Index Changed Method Fired");
STNLogger.LogFileWrite(message);
string factory = RadDropDownList_Warehouse.SelectedText.Trim();
List<string> buList = new List<string>();
buList = mr.GetBUsForPlants(factory);
RadDropDownList_BusinessUnit.DataSource = buList;
RadDropDownList_BusinessUnit.DataBind();
}
I used this LogFileWrite() to see if this method was executed at all in the server but no. This event is not fired in the server, whereas in Visual Studio it is. Please help!!
Thanks in advance.

Retrieving Current Value from Telerik RadGrid EditFormItem

I have an ASP form created using Telerik's RadGrid control, already binding values from the database and displaying them, with the ability to add and delete entries from the table. I need to add editing functionality, but I've finally run into a block, and I can't find a way past it.
The ASP page contains both the RadGrid and the SqlDataSource I need to use:
<asp:SqlDataSource ID="ContactsSqlDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:DBConnectionString %>"
SelectCommand="etc..."
UpdateCommand="UPDATE Contacts
SET Salutation=#Salutation,
FirstName=#FirstName,
etc...
WHERE ClientContactID=#ClientContactID" CancelSelectOnNullParameter="False"
onupdating="ContactsSqlDataSource_Updating">
<UpdateParameters>
<asp:Parameter Name="Salutation" Type="String" />
<asp:Parameter Name="FirstName" Type="String" />
etc...
<asp:Parameter Name="ClientContactID" Type="String" />
</UpdateParameters>
<SelectParameters>
<asp:QueryStringParameter Name="GroupID" QueryStringField="ID" />
</SelectParameters>
</asp:SqlDataSource>
etc...
<telerik:RadGrid ID="ContactsRadGrid" runat="server"
AutoGenerateColumns="False" AutoGenerateDeleteColumn="True" CellSpacing="0"
DataSourceID="ContactsSqlDataSource" GridLines="None"
Skin="Windows7" onitemcommand="ContactsRadGrid_ItemCommand"
onitemdatabound="ContactsRadGrid_ItemDataBound"
AllowAutomaticUpdates="True">
<MasterTableView DataSourceID="ContactsSqlDataSource"
DataKeyNames="etc...">
<Columns>
etc...
</Columns>
<EditFormSettings EditFormType="Template">
<FormTemplate>
<asp:HiddenField ID="ClientIDHiddenField" runat="server"
Value='<%# Bind("ClientContactID") %>' />
etc...
<asp:TextBox ID="SalutationTextBox" runat="server" Text='<%# Bind("Salutation") %>' TabIndex="1" />
etc...
<asp:TextBox ID="FirstNameTextBox" runat="server" Text='<%# Bind("FirstName") %>' TabIndex="2" />
</FormTemplate>
</EditFormSettings>
</MasterTableView>
</telerik:RadGrid>
In my code behind, I have:
protected void ContactsRadGrid_ItemCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
{
RadGrid grid = sender as RadGrid;
GridDataItem dataItem = e.Item as GridDataItem;
GridEditFormItem editItem = e.Item as GridEditFormItem;
if (e.CommandName == "Delete")
{
etc...
}
else if (e.CommandName == "Update")
{
ContactsSqlDataSource.Update();
}
}
protected void ContactsSqlDataSource_Updating(object sender, SqlDataSourceCommandEventArgs e)
{
GridEditFormItem editItem = (ContactsRadGrid.EditItems[0] as GridDataItem).EditFormItem;
string salutation = Convert.ToString(editItem.GetDataKeyValue("Salutation"));
string firstName = Convert.ToString(editItem.GetDataKeyValue("FirstName"));
etc...
string clientContactID = Convert.ToString(editItem.GetDataKeyValue("ClientContactID"));
e.Command.Parameters["#Salutation"].Value = salutation;
e.Command.Parameters["#FirstName"].Value = firstName;
etc...
e.Command.Parameters["#ClientContactID"].Value = clientContactID;
e.Command.Connection.Open();
e.Command.ExecuteNonQuery();
e.Command.Connection.Close();
}
This is where I finally got to in order to stop getting errors on the SQL execution, however there's one major problem: the values being pushed onto the parameters are the old values, the ones that were already in the database, not the values I've entered in the EditFormItem. If I hardcode something onto a parameter (eg, append ".com" onto email), the alteration is correctly reflected in both the database and the table after the "Save" button in the edit form is clicked. Without the manual edit, no changes occur, because the database is simply being updated with the values that were already present.
How can I get the current values in the edit form?
(I'm not opposed to getting this done in some way other than the DataSource_Updating event, that's just the solution I came up with which was closest to correct. I do need to stick with the RadGrid, though.)
I managed to find a resolution to this issue. In the first part of ContactsSqlDataSource_Updating, I now have:
string salutation = (editItem.FindControl("SalutationTextBox") as TextBox).Text;
string firstName = (editItem.FindControl("FirstNameTextBox") as TextBox).Text;
etc...
string clientContactID = (editItem.FindControl("ClientIDHiddenField") as HiddenField).Value;
The database now updates correctly.

DetailsView DropDownLists

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
SelectedValue='<%# DataBinder.Eval (Container.DataItem, "VendorBUID") %>'
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
public override void OnLoad(EventArgs e) {
VendorBUName.DataBinding += dataBindDropDown;
}
private void dataBindDropDown(object sender, EventArgs e) {
VendorBUName.SelectedValue = dataSource.VendorBUID;
}

Catching null values on databinding

I have a dropdownlist that is populated from an SQL select statement. The select statement filters for items where the 'bit' is set to false and the items, although still in the database are hidden.
My problem is; when an item is out of stock or hidden (bit = false) the user may still have items that are now hidden so it throws an error. How and where can I catch this, show the original item or set the value to default?
protected void GradeDropDownList_DataBinding (object sender, EventArgs e)
{
var ddl = (DropDownList)(sender);
var a = ((Label)MyDetailsView.FindControl("GradeLabelEdit")).Text;
a = a.Trim();
if (a != "") { ddl.SelectedValue = a; }
}
The select statement;
<asp:SqlDataSource ID="getGrade" runat="server" ConnectionString="<%$ ConnectionStrings:CasesTimeConnection %>"
SelectCommand="SELECT [gradeID], [gradeText] FROM [user_grades] WHERE ([visibleState] = #visibleState)">
<SelectParameters>
<asp:Parameter DefaultValue="True" Name="visibleState" Type="Boolean" />
</SelectParameters>
</asp:SqlDataSource>
In page;
<EditItemTemplate>
<asp:DropDownList ID="GradeDropDownList" runat="server" DataSourceID="getGrade" DataTextField="gradeText" DataValueField="gradeID" OnDataBinding="GradeDropDownList_DataBinding" OnSelectedIndexChanged="GradeDropDownList_SelectedIndexChanged">
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="gradeLabel" runat="server" Text='<%# Bind("gradeText") %>'></asp:Label>
</ItemTemplate>
Retrieve LastModifiedDate while retrieving the records and while trying to update the record check the existing lastModifiedDate value with the one you retrieved. If they are different then throw an alert message / display new quantity.
Thanks
Shashi

Problems with AJAX CascadingDropDown and DropDownList SelectedValue in EditItemTemplate

I am having problem in EditItemTemplate of FormView.
When I use such code in InsertItemTemplate everything works:
<asp:DropDownList ID="Lic_PosiadaczLicencjiIDDropDownList" runat="server"
SelectedValue='<%# Bind("Lic_PosiadaczLicencjiID") %>' />
<asp:CascadingDropDown ID="CascadingDropDown1" runat="server"
TargetControlID="Lic_PosiadaczLicencjiIDDropDownList" Category="Knt_Kod"
ServicePath="~/ManagerLicencjiService.asmx" ServiceMethod="GetKontrahenci">
</asp:CascadingDropDown>
But when I use exactly the same code in EditItemTemplate I am getting an error that SelectedValue is wrong cause it doesn't exists on the list of elements.
I think that the problem is that DropDownList is checked for the values before it is populated by the service. When I run debugger the error occured before breakpoint in the service method.
How to solve this problem?
<rant>I've found the CCD very clunky and full of poorly-documented workarounds</rant> but here is how you do something as simple as selecting a value when filling the ddl. Note that the selected value is not set on the DDL and that it is being passed to the web service where the selecting is done.
<asp:ScriptManager ID="sm1" runat="server"></asp:ScriptManager>
<asp:FormView ID="fv1" runat="server" DataSourceID="yourDataSource">
<EditItemTemplate>
<asp:DropDownList ID="Lic_PosiadaczLicencjiIDDropDownList" runat="server" />
<asp:CascadingDropDown ID="CascadingDropDown1" runat="server"
TargetControlID="Lic_PosiadaczLicencjiIDDropDownList" Category="Knt_Kod"
ServicePath="~/ManagerLicencjiService.asmx" ServiceMethod="GetKontrahenci"
UseContextKey="true" ContextKey='<%# Bind("Lic_PosiadaczLicencjiID") %>'>
</asp:CascadingDropDown>
</EditItemTemplate>
</asp:FormView>
<asp:sqldatasource id="yourDataSource"
selectcommand="select Lic_PosiadaczLicencjiID FROM yourdatabase"
UpdateCommand="Update yourdatabase set Lic_PosiadaczLicencjiID = #newvalue WHERE Lic_PosiadaczLicencjiID = #Lic_PosiadaczLicencjiID"
connectionstring="<%$ ConnectionStrings:yourConnectionString %>"
runat="server"
onupdating="yourDataSource_Updating">
<UpdateParameters>
<asp:Parameter Name="newvalue" DbType="String" />
</UpdateParameters>
</asp:sqldatasource>
code behind:
protected void yourDataSource_Updating(object sender, SqlDataSourceCommandEventArgs e)
{
e.Command.Parameters["#newvalue"].Value = ((DropDownList)fv1.FindControl("Lic_PosiadaczLicencjiIDDropDownList")).SelectedValue;
}
and in your web service where you are getting your data from you need to add the context key to the signature exactly as shown as it is case sensitive. You then check your returned values for the selected value and set selected = true. If you want selected value instead of selected text then check for x.value instead of x.name.
[WebMethod]
public CascadingDropDownNameValue[] GetKontrahenci(string knownCategoryValues, string category, string contextKey)
{
CascadingDropDownNameValue[] results = getdata();
CascadingDropDownNameValue selectedVal = (from x in results where x.name == contextKey select x).FirstOrDefault();
if (selectedVal != null)
selectedVal.isDefaultValue = true;
return results;
}
Hope this helps!

Categories

Resources