ASP.NET SQLDataSource SelectParameters default value not working - mysql

I wrote a simple ASP.NET form to manage a particular query on my (MySQL) db. Such query is handled by this stored procedure:
CREATE DEFINER=`root`#`localhost` PROCEDURE `noleggio_conducenti`(IN _id_convenzionato INT(10))
BEGIN
IF _id_convenzionato IS NOT NULL THEN
SELECT * FROM
(
SELECT
*
FROM
noleggi AS H
WHERE
id_convenzionato = _id_convenzionato
UNION
SELECT
*
FROM
noleggi AS H
WHERE
id_convenzionato IN (SELECT
id_recipiente
FROM
sosautomotive.transizioni_point
WHERE
id_cedente = _id_convenzionato )
) H
WHERE (H.uscita IS NOT NULL) AND (H.rientro IS NOT NULL);
ELSE
SELECT
*
FROM
noleggi
WHERE (uscita IS NOT NULL) AND (rientro IS NOT NULL);
END IF;
END
As you can see the only parameter can be NULL ... my hope was to use this stored procedure to provide data to the following SQLDataSource object:
<asp:SqlDataSource
ID="_sdsConducenti"
runat="server"
ConnectionString="<%$ ConnectionStrings:sos_db %>"
ProviderName="<%$ ConnectionStrings:sos_db.ProviderName %>"
SelectCommandType="StoredProcedure"
SelectCommand="noleggio_conducenti">
<SelectParameters>
<asp:Parameter Name="_id_convenzionato" Type="Int32" DefaultValue="" ConvertEmptyStringToNull="true" />
</SelectParameters>
</asp:SqlDataSource>
That provides data to a GridView :
<asp:GridView
ID="_gvConducenti"
runat="server"
DataSourceID="_sdsConducenti"
OnSorting="_gvConducenti_Sorting"
OnPageIndexChanging="_gvConducenti_PageIndexChanging"
OnRowDataBound="_gvConducenti_RowDataBound"
AutoGenerateColumns="false"
EmptyDataText="Nessun conducente presente."
BorderStyle="None"
CellSpacing="0"
CellPadding="0"
ShowHeader="true"
ShowFooter="true"
AllowSorting="true"
AllowPaging="true"
PageSize="10"
GridLines="Horizontal"
SelectedIndex="0"
Style="width: 100%;"
HorizontalAlign="Center">
<SelectedRowStyle CssClass="SelRow" />
<HeaderStyle CssClass="GridHeader" />
<AlternatingRowStyle BackColor="#F7F5E9" CssClass="AltRow" />
<PagerStyle HorizontalAlign="Center" />
<PagerSettings
Visible="true"
Mode="NumericFirstLast"
PageButtonCount="3"
Position="Bottom"
NextPageText="Pagina successiva"
PreviousPageText="Pagina precedente"
FirstPageText="Prima pagina"
LastPageText="Ultima pagina" />
<Columns>
<asp:TemplateField Visible="false">
<HeaderTemplate> </HeaderTemplate>
<ItemTemplate>
<%#Eval("idnoleggio")%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Numero" SortExpression="numero">
<ItemTemplate>
<asp:LinkButton
runat="server"
CommandArgument='<%# Eval("idnoleggio")%>'
CommandName="Link"
OnCommand="Link_Command">
<%#Eval("numero_completo")%>
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Conducente" DataField="conducente" />
<asp:BoundField HeaderText="Via" DataField="conducente_via" />
<asp:BoundField HeaderText="N° Civico" DataField="conducente_num_civico" />
<asp:BoundField HeaderText="CAP" DataField="conducente_cap" />
<asp:BoundField HeaderText="Città" DataField="conducente_residente_in" />
<asp:BoundField HeaderText="Prov." DataField="conducente_residente_in_provincia" />
<asp:BoundField HeaderText="Convenzionato" DataField="convenzionato" />
<asp:BoundField HeaderText="Uscita" DataField="uscita" DataFormatString="{0:dd/MM/yyyy HH:mm}" />
<asp:BoundField HeaderText="Rientro" DataField="rientro" DataFormatString="{0:dd/MM/yyyy HH:mm}" />
<asp:BoundField HeaderText="Tipologia noleggio" DataField="modalita_noleggio" />
</Columns>
</asp:GridView>
of course this form has other fields used to filter the query and those are handled by this couple of functions:
private void Ricerca()
{
if (!String.IsNullOrWhiteSpace(_txtConvenzionato.Text.Trim()))
{
int _nIdConvenzionato = CUtilita.RitornaIdConvenzionato(_txtConvenzionato.Text);
if (_nIdConvenzionato != -1)
_sdsConducenti.SelectParameters["_id_convenzionato"].DefaultValue = _nIdConvenzionato.ToString();
else
_sdsConducenti.SelectParameters["_id_convenzionato"].DefaultValue = null;
}
_sdsConducenti.FilterExpression = Filter();
}
private string Filter()
{
StringBuilder _sbFilter = new StringBuilder();
try
{
#region Data fine noleggio
if (!string.IsNullOrWhiteSpace(_txtDallaDataFineNoleggio.Text.Trim()) &&
!string.IsNullOrWhiteSpace(_txtAllaDataFineNoleggio.Text.Trim()))
{
DateTime _dtDallaDataFineNoleggio = DateTime.Parse(_txtDallaDataFineNoleggio.Text.Trim());
DateTime _dtAllaDataFineNoleggio = DateTime.Parse(_txtAllaDataFineNoleggio.Text.Trim());
_sbFilter.AppendFormat("((uscita>='{0:yyyy-MM-dd}') AND (uscita<='{1:yyyy-MM-dd}'))", _dtDallaDataFineNoleggio, _dtAllaDataFineNoleggio);
}
else if (string.IsNullOrWhiteSpace(_txtDallaDataFineNoleggio.Text.Trim()) &&
!string.IsNullOrWhiteSpace(_txtAllaDataFineNoleggio.Text.Trim()))
{
DateTime _dtAllaDataFineNoleggio = DateTime.Parse(_txtAllaDataFineNoleggio.Text.Trim());
_sbFilter.AppendFormat("(uscita<='{0:yyyy-MM-dd}')", _dtAllaDataFineNoleggio);
}
else if (!string.IsNullOrWhiteSpace(_txtDallaDataFineNoleggio.Text.Trim()) &&
string.IsNullOrWhiteSpace(_txtAllaDataFineNoleggio.Text.Trim()))
{
DateTime _dtDallaDataFineNoleggio = DateTime.Parse(_txtDallaDataFineNoleggio.Text.Trim());
_sbFilter.AppendFormat("(uscita>='{0:yyyy-MM-dd}')", _dtDallaDataFineNoleggio);
}
#endregion
}
catch (FormatException ex)
{
_lblStatus.Text = ex.Message;
_lblStatus.ForeColor = System.Drawing.Color.Red;
}
try
{
#region Data esportazione
if (!string.IsNullOrWhiteSpace(_txtDallaDataEstrazione.Text.Trim()) &&
!string.IsNullOrWhiteSpace(_txtAllaDataEstrazione.Text.Trim()))
{
DateTime _dtDallaDataEstrazione = DateTime.Parse(_txtDallaDataEstrazione.Text.Trim());
DateTime _dtAllaDataEstrazione = DateTime.Parse(_txtAllaDataEstrazione.Text.Trim());
_sbFilter.AppendFormat("((data_esportazione_conducenti>='{0:yyyy-MM-dd}') AND (data_esportazione_conducenti<='{1:yyyy-MM-dd}'))", _dtDallaDataEstrazione, _dtAllaDataEstrazione);
}
else if (string.IsNullOrWhiteSpace(_txtDallaDataEstrazione.Text.Trim()) &&
!string.IsNullOrWhiteSpace(_txtAllaDataEstrazione.Text.Trim()))
{
DateTime _dtAllaDataEstrazione = DateTime.Parse(_txtAllaDataEstrazione.Text.Trim());
_sbFilter.AppendFormat("(data_esportazione_conducenti<='{0:yyyy-MM-dd}')", _dtAllaDataEstrazione);
}
else if (!string.IsNullOrWhiteSpace(_txtDallaDataEstrazione.Text.Trim()) &&
string.IsNullOrWhiteSpace(_txtAllaDataEstrazione.Text.Trim()))
{
DateTime _dtDallaDataEstrazione = DateTime.Parse(_txtDallaDataEstrazione.Text.Trim());
_sbFilter.AppendFormat("(data_esportazione_conducenti>='{0:yyyy-MM-dd}')", _dtDallaDataEstrazione);
}
#endregion
}
catch (FormatException ex)
{
_lblStatus.Text = ex.Message;
_lblStatus.ForeColor = System.Drawing.Color.Red;
}
#region Tipo Noleggio
if (!string.IsNullOrWhiteSpace(_ddlTipoNoleggio.SelectedValue) && !_ddlTipoNoleggio.SelectedValue.Equals("TUTTI"))
{
if (_sbFilter.Length > 0)
_sbFilter.Append(" AND");
_sbFilter.Append("(modalita_noleggio = '" + _ddlTipoNoleggio.SelectedValue + "')");
}
#endregion
if (_sbFilter.Length == 0)
return null;
return _sbFilter.ToString();
}
I tested the stored procedure trough MySQL Workbench and I'm sure it works (both with a valid parameter and with NULL).
BUT when I try to use it within the form it works ONLY if the parameter value is provided and when then value is set to NULL (i.e. _sdsConducenti.SelectParameters["_id_convenzionato"].DefaultValue = null) the query did not provide any data (while it should retrieve a large number of records).
Where did I fail? How can I check if the NULL value is correctly set as the parameter value before calling the stored procedure?
Full code available here.

Try specifying below property in SQLDataSource definition -
CancelSelectOnNullParameter="false"
And it is described as
true if a data retrieval operation is canceled when a parameter
contained in the SelectParameters collection evaluated to null;
otherwise, false. The default is true
The similar problem is explained here -
Set SqlDataSource parameter to null
For more information refer here-

Related

Show/Hide Button depending on stored procedure return value

I'd like to get some help on an issue I'm having. I have a stored procedure that returns a dataset to fill a datagriview. One of the data grid's columns contains 2 manually set buttons, 'View' & 'Add'. These buttons open up a new popup window which displays extra information etc. I would like to be able to hide a 'View' button if 1 of the returned parameter's, POCount, count is equal to 0. i.e. there is nothing to view for that row. What is the best way to make this happen.
My stored procedure is
SELECT PM.ProjectCode,
PM.ProjectDesc,
PM.Active,
PM.Chargeable,
(SELECT COUNT(*) FROM POMaster PO WHERE PO.ProjectCode = PM.ProjectCode) AS POCount
FROM PROJECTMASTER PM
Front End Code
<asp:TemplateField HeaderText="P.O. Number" ItemStyle-Wrap="false" >
<ItemTemplate>
<asp:LinkButton ID="linkPONumber" runat="server" Text="View" CssClass="buttonStyle" OnClick="LinkPONumber_Click" CommandArgument='<%# Eval("ProjectCode") + ";" + Eval("ProjectDesc") %>' ></asp:LinkButton>
<asp:LinkButton ID="linkAddPO" runat="server" Text="Add" CssClass="buttonStyle" OnClick="LinkAddPO_Click" CommandArgument='<%# Eval("ProjectCode") + ";" + Eval("ProjectDesc") %>' ></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
Code Behind
private void BindGrid()
{
DSProjectDetails = objProjectMasterBL.GetProjectDetails();
GvProject.DataSource = DSProjectDetails;
GvProject.DataBind();
}
public DataSet GetProjectDetails()
{
try
{
SqlProcedureName = "USP_GetProjectListWithPO";
SqlConnectionObject = DBConnection.InitializeConnection(SqlConnectionObject);
dsrepeater = SqlHelper.ExecuteDataset(SqlConnectionObject, CommandType.StoredProcedure, SqlProcedureName);
return dsrepeater;
}
catch (Exception ex)
{
log.Error("Exception in ProjectMasterBL.GetProjectDetails:", ex);
throw ex;
}
}
Apologies if I've sent the wrong sections of code, still residing in the noob ranks
You can use the Visible property of Link Button:-
<asp:LinkButton ID="linkAddPO" runat="server" Text="Add" CssClass="buttonStyle"
OnClick="LinkAddPO_Click" Visible='<%# Convert.ToInt32(Eval("POCount")) == 0 %>'
CommandArgument='<%# Eval("ProjectCode") + ";" + Eval("ProjectDesc") %>'>
</asp:LinkButton>
Whenever your SP returns POCount as 0, you LinkButton will be hidden.

Could not find control 'ControlID' in ControlParameter 'ParamName'

Ok guys, I know this question has been asked a million times. I've searched for days and none of the online solutions found actually work for me. Here's my code:
<asp:SqlDataSource
ID="SqlDataSource2"
runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
ProviderName="<%$ ConnectionStrings:ConnectionString.ProviderName %>"
SelectCommand="SELECT VTPNAME, NETWORKKEY, FKVTPDOMAIN, VLANNUMBER, NETDESCRIPTION, BEGINNINGIP,
HOSTS, DEFAULTGATEWAY FROM NETWORK.NETWORK, NETWORK.VTPDOMAIN WHERE
NETWORK.FKVTPDOMAIN = VTPDOMAIN.VTPDOMAINKEY"
DeleteCommand="DELETE FROM NETWORK.NETWORK WHERE NETWORKKEY =: NETWORKKEY"
UpdateCommand="UPDATE NETWORK.NETWORK SET FKVTPDOMAIN =:updateFKVTP, VLANNUMBER = :VLANNUMBER,
NETDESCRIPTION = :NETDESCRIPTION,BEGINNINGIP = :BEGINNINGIP,
HOSTS = :HOSTS,DEFAULTGATEWAY = :DEFAULTGATEWAY WHERE NETWORKKEY = :NETWORKKEY"
InsertCommand="INSERT INTO NETWORK.NETWORK (VLANNUMBER,NETDESCRIPTION,BEGINNINGIP,HOSTS,DEFAULTGATEWAY,FKVTPDOMAIN) VALUES (:vlanNet,:descNet,:begIpNet,:hostNet,:defNet,:vtpdomainkey)">
<InsertParameters>
<asp:ControlParameter Name="vlanNet" ControlID="vlanTextbox" />
<asp:ControlParameter Name="descNet" ControlID="descTextbox" />
<asp:ControlParameter Name="begIpNet" ControlID="beginIPTextbox" />
<asp:ControlParameter Name="hostNet" ControlID="hostsTextbox" />
<asp:ControlParameter Name="defNet" ControlID="defaultGatTextBox" />
<asp:ControlParameter Name="vtpdomainkey" ControlID="vtpDomainFKDropDown" />
</InsertParameters>
<UpdateParameters>
<asp:ControlParameter Name="updateFKVTP" ControlID="vtpNameDropDownUpdate" />
</UpdateParameters>
</asp:SqlDataSource>
<asp:GridView
ID="GridView2"
runat="server"
AutoGenerateColumns="False"
DataSourceID="SqlDataSource2"
AllowPaging="True"
AllowSorting="True"
DataKeyNames="NETWORKKEY"
Width="650px"
OnRowUpdating="GridView2_RowUpdating">
<Columns>
<asp:CommandField HeaderText="Options" ShowDeleteButton="True" ShowEditButton="True" />
<asp:TemplateField HeaderText="VTP Domain" SortExpression="VTPNAME">
<EditItemTemplate>
<asp:DropDownList ID="vtpNameDropDownUpdate" runat="server" DataSourceID="SqlDataSource6" DataTextField="VTPNAME" DataValueField="VTPDOMAINKEY">
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("VTPNAME") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
Here's the actual error given:
Could not find control 'vtpNameDropDownUpdate' in ControlParameter 'updateFKVTP'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: Could not find control 'vtpNameDropDownUpdate' in ControlParameter 'updateFKVTP'.
Everything works as is supposed to, except the dropDownList. It will NOT find it, I have tried dollar signs, colons,underscore, you name it, to tell it where the control is and no result. They are in the same and they both lay one under the other, just as I posted it here. I got the first row to actually update because I tried the method where you right click on the dropdownlist while running and you "inspect the element" and copy and paste the whole ControlID string into the ControlParameter ControlID. The problem is, there are several rows, so it will only work for the one element I inspected and not all the other ones. Any help would be appreciated and thank you in advance for your time!
-Fernando
The DropDownList is inside The Template Control, so you should find the template control first.In this example template control is in 7th column of Gridview. after find template inside that you can find DropDownList :
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
var index = e.RowIndex;
var dropDownctr= GridView1.Rows[index].Controls[6].FindControl("vtpNameDropDownUpdate")
}

How to make multiple rows in single cell using GridView

here i am facing one task...
In my gridview there are two cols ok, named as user and profile. i need to display profile list related to user in single cell(multiple rows). how do i do that???
This what i tried
<asp:BoundField DataField="UserName" HeaderText="User">
<HeaderStyle HorizontalAlign="Left" />
<ItemStyle HorizontalAlign="Left" />
</asp:BoundField>
<%--<asp:BoundField DataField="ProfileName" HeaderText="Profile">
<HeaderStyle HorizontalAlign="Left" />
<ItemStyle HorizontalAlign="Left" />
</asp:BoundField>--%>
<asp:TemplateField>
<HeaderTemplate>Profile</HeaderTemplate>
<ItemTemplate>
<%#Eval("UserName.ProfileName")%>
</ItemTemplate>
</asp:TemplateField>
You merge the row according to condition. Here is a good example
http://www.codeproject.com/Articles/34337/How-to-merge-cells-with-equal-values-in-a-GridView
public static void MergeRows(GridView gridView)
{
for (int rowIndex = gridView.Rows.Count - 2; rowIndex >= 0; rowIndex--)
{
GridViewRow row = gridView.Rows[rowIndex];
GridViewRow previousRow = gridView.Rows[rowIndex + 1];
for (int i = 0; i < row.Cells.Count; i++)
{
if (row.Cells[i].Text == previousRow.Cells[i].Text)
{
row.Cells[i].RowSpan = previousRow.Cells[i].RowSpan < 2 ? 2 :
previousRow.Cells[i].RowSpan + 1;
previousRow.Cells[i].Visible = false;
}
}
}
}

Validate dynamically created fields when one is changed

I have a program that dynamically creates various text boxes / drop down lists. I am trying to figure out how to validate these fields only when one is changed. Basically if someone entered a date in the text box then I need the program to validate that the drop down list was changed or vice versa. If there are no changes to both fields then it should not validate. Any help would be extremely appreciated. Here is the code:
<asp:TemplateField HeaderText="ValidatedDate" SortExpression="ValidatedDate">
<EditItemTemplate>
<asp:TextBox ID="txtValDate" Width="100px" MaxLength="10" runat="server" AutoPostBack="true"
Text='<%# Bind("ValidatedDate","{0:MM/dd/yyyy}") %>'></asp:TextBox>
<asp:RegularExpressionValidator ValidationGroup="g1" ID="RegularExpressionValidator10"
runat="server" ControlToValidate="txtValDate" Display="None" ErrorMessage="Validated Date: ##/##/####"
ValidationExpression="\d{1,2}/\d{1,2}/\d{4}"></asp:RegularExpressionValidator>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblValidatedDate" runat="server" Text='<%# Bind("ValidatedDate","{0:MM/dd/yyyy}")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ProductStatus" SortExpression="ProductStatusDescription">
<EditItemTemplate>
<asp:DropDownList ID="DropDownList4" runat="server" DataSourceID="SqlDataSource6" AutoPostBack="true"
DataTextField="StatusDescription" DataValueField="StatusID" SelectedValue='<%# Bind("Status") %>'>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblProductStatus" runat="server" Text='<%# Bind("ProductStatusDescription")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
My apologies, the code can be a bit confusing without the correct context.
ebyrob, thank you for your help. I figured it out however and it works beautifully. Here is the code that fixed it all:
protected void AddError(string errorMessage)
{
cstValidate.IsValid = false;
cstValidate.ErrorMessage = errorMessage;
cstValidate.EnableClientScript = false;
}
protected void GridView2_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
TextBox txtValidatedDate = GridView2.Rows[e.RowIndex].FindControl("txtValDate") as TextBox;
DropDownList ddlStatusCompare = GridView2.Rows[e.RowIndex].FindControl("dropdownlist4") as DropDownList;
if (txtValidatedDate.Text == string.Empty && ddlStatusCompare.SelectedValue == "1")
{
AddError("Please enter a Validated Date");
e.Cancel = true;
}
else if (txtValidatedDate.Text != string.Empty && ddlStatusCompare.SelectedValue == "0"
|| txtValidatedDate.Text != string.Empty && ddlStatusCompare.SelectedValue == "99")
{
AddError("Please remove the Validated Date");
e.Cancel = true;
}
if (!e.Cancel)
Helpers.LogChanges(GridView2, e, _employeeID, "SaleProducts");
}

Partial page updating using update panel

I am creating "edit my profile page" where I have some text boxes and drop down lists.I have a requirement such that when I select a value in my first drop down, the second drop down should fill. But this is not happening.
<asp:UpdatePanel runat="server" ID="updatepanel1" UpdateMode="Conditional">
<ContentTemplate >
<asp:Label runat="server" Id="lbljobIndus" Text="Preferred Job Industry" Font-Names="Calibri" Font-Size="Small" ForeColor="Black"></asp:Label>
<span style="color: black; font-family: Calibri; font-size: small">:</span>
<asp:Label runat="server" ID="lblPreferredJobIndustry" Font-Names="Calibri" Font-Size="Small" ForeColor="Black"></asp:Label>
<asp:DropDownList ID="tbPreferredJobIndustry" runat="server" Height="19px" OnSelectedIndexChanged="ddlTargetedIndustry_SelectedIndexChanged">
<asp:ListItem Selected="True" Value="-1">--Select Industry--</asp:ListItem>
<asp:ListItem Value="1">Administration</asp:ListItem>
<asp:ListItem Value="2">Hospital/HealthCare</asp:ListItem>
<asp:ListItem Value="3">Medical Transcription</asp:ListItem>
</asp:DropDownList>
<br />
<br />
<br />
<asp:Label runat="server" ID="lblJobCat" Text="Preferred Job Category" Font-Names="Calibri" Font-Size="Small" ForeColor="Black"></asp:Label>
<span style="color: black; font-family: Calibri; font-size: small">:</span>
<asp:Label runat="server" ID="lblJobCategory" Font-Names="Calibri" Font-Size="Small" ForeColor="Black"></asp:Label>
<asp:DropDownList ID="tbJobCategory" runat="server">
<asp:ListItem Selected="True" Value="-1">-Position Category-</asp:ListItem>
</asp:DropDownList>
<br />
<br />
</ContentTemplate>
</asp:UpdatePanel>
This is the code to populate the second drop down list :-
protected void ddlTargetedIndustry_SelectedIndexChanged(object sender, EventArgs e)
{
DataSet ds = new DataSet();
SqlDataAdapter myda = new SqlDataAdapter("Select s_CategoryName,FK_TargetedIndustryID FROM [OfinityJobSearch].[dbo].[tm_JobCategory] where FK_TargetedIndustryID='" + tbPreferredJobIndustry.SelectedItem.Value + "'", con);
myda.Fill(ds);
tbJobCategory.DataSource = ds;
tbJobCategory.DataValueField = "FK_TargetedIndustryID";
tbJobCategory.DataTextField = "s_CategoryName";
tbJobCategory.DataBind();
tbJobCategory.Items.Insert(0, new ListItem("--Select Job Category--", "0"));
}
I used update panel so that the values in other text boxes will not get cleared on the post back. But right now, I think the post back is not happening.Can you please check my code and tell me where the error is?
Set AutoPostBack= true for the first ddl
U can use AjaxToolkit CascadingDropDown it's very helpful and useful. But in case of CascadingDropDown u need additional service.
<ajaxToolkit:CascadingDropDown ID="CDD1" runat="server"
TargetControlID="DropDownList2"
Category="Model"
PromptText="Please select a model"
LoadingText="[Loading models...]"
ServicePath="CarsService.asmx"
ServiceMethod="GetDropDownContents"
ParentControlID="DropDownList1"
SelectedValue="SomeValue" />
UPDATE:
Full example here
your *.aspx
<asp:DropDownList ID="DropDownList1" runat="server" Width="170" />
<asp:DropDownList ID="DropDownList2" runat="server" Width="170" />
<ajaxToolkit:CascadingDropDown ID="CascadingDropDown1" runat="server" TargetControlID="DropDownList1"
Category="Make" PromptText="Please select a make" LoadingText="[Loading makes...]"
ServicePath="CarsService.asmx" ServiceMethod="GetDropDownContents" />
and add code to page
[WebMethod]
[System.Web.Script.Services.ScriptMethod]
public static CascadingDropDownNameValue[] GetDropDownContentsPageMethod(string knownCategoryValues, string category)
{
return new CarsService().GetDropDownContents(knownCategoryValues, category);
}
add web service
<%# WebService
Language="C#"
CodeBehind="~/App_Code/CarsService.cs"
Class="CarsService" %>
Code for service
[System.Web.Script.Services.ScriptService]
public class CarsService : WebService
{
// Member variables
private static XmlDocument _document;
private static Regex _inputValidationRegex;
private static object _lock = new object();
// we make these public statics just so we can call them from externally for the
// page method call
public static XmlDocument Document
{
get
{
lock (_lock)
{
if (_document == null)
{
// Read XML data from disk
_document = new XmlDocument();
_document.Load(HttpContext.Current.Server.MapPath("~/App_Data/CarsService.xml"));
}
}
return _document;
}
}
public static string[] Hierarchy
{
get { return new string[] { "make", "model" }; }
}
public static Regex InputValidationRegex
{
get
{
lock (_lock)
{
if (null == _inputValidationRegex)
{
_inputValidationRegex = new Regex("^[0-9a-zA-Z \\(\\)]*$");
}
}
return _inputValidationRegex;
}
}
/// <summary>
/// Helper web service method
/// </summary>
/// <param name="knownCategoryValues">private storage format string</param>
/// <param name="category">category of DropDownList to populate</param>
/// <returns>list of content items</returns>
[WebMethod]
public AjaxControlToolkit.CascadingDropDownNameValue[] GetDropDownContents(string knownCategoryValues, string category)
{
// Get a dictionary of known category/value pairs
StringDictionary knownCategoryValuesDictionary = AjaxControlToolkit.CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);
// Perform a simple query against the data document
return AjaxControlToolkit.CascadingDropDown.QuerySimpleCascadingDropDownDocument(Document, Hierarchy, knownCategoryValuesDictionary, category, InputValidationRegex);
}