Why my combobox count is 0? - asp.net

Why the count of items in my ComboBox is always 0 although the datasource of this combobox has data !!
<div align="right" dir="rtl">
<asp:Label ID="lbl_contactListName" runat="server" Text="Menu Name :" CssClass="span"></asp:Label>
<telerik:RadComboBox ID="ddl_contactList" runat="server" AutoPostBack="True" CausesValidation="False"
CollapseDelay="0" Culture="ar-EG" ExpandDelay="0" Filter="StartsWith" ItemsPerRequest="10"
MarkFirstMatch="true" Skin="Outlook" EnableAutomaticLoadOnDemand="True" EmptyMessage="-New Menu-"
ShowMoreResultsBox="True" OnSelectedIndexChanged="ddl_contactList_SelectedIndexChanged"
EnableVirtualScrolling="True" DataTextField="list_desc" DataValueField="list_code"
DataSourceID="ObjectDataSource1" EnableViewState="true" Width="300px">
</telerik:RadComboBox>
</div>
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server" SelectMethod="GetContactListsByDep"
TypeName="SendSMS_EmailModule.ContactList">
<SelectParameters>
<asp:SessionParameter Name="year" SessionField="year" Type="Int32" />
<asp:SessionParameter Name="main_code" SessionField="main_code" Type="Int32" />
</SelectParameters>
</asp:ObjectDataSource>

The property value of of Rad combo "EnableAutomaticLoadOnDemand=True" here.This property load all the data on demand. So when you click on your combobox it will load the data in it untill that it is empty. If you do not want to make your combo on demand then Make that property false. By doing that you will get the count directly.
If you want to keep that EnableAutomaticLoadOnDemand property to True. you can use ItemDataBound event of the Rad Combo. By using it you can change the Item's Text and Value properties as well as modify its Attributes collection based on the DataItem
You will find more details at telerik rad combo. Let me know if you want more detail on this.

Perhaps you should call DataBind() before you call Count().
ddl_contactList.DataBind();
ddl_contactList.Items.Count();

Are you getting the Count as Zero on Page Load.
If that's the case it is because the page load event hits before the ComboBox is populated. An easier way is to populate the items on Page Load itself.
(This code is untested)
if(!Page.IsPostBack)
{
using(var context = new Entities())
{
foreach(var item in context.Employee)
{
RadComboBox1.Items.Add(new RadListBoxItem(item.Name, item.ID.ToString()));
}
}
}
//Here you can get the count.

Related

How to pass value using ImageButton to update database?

I having problem when I try to pass value from ImageButton to a controlparameter, then the update command can retrieve the value from control parameter to execute update statement.
I want to pass value Status=1 when ImageButton APPROVE is clicked, else pass value Status=2 when ImageButton REJECT is clicked.
Where and how should I assign value Status?
When I run my code, I receive this error : Must declare the scalar variable "#Status".
Or any recommendation to pass the value Status?
My ImageButton:
<ItemTemplate>
<asp:ImageButton runat="server" ID="APPROVE" CommandName="update"
ImageUrl="~/images/accept.png"
OnClientClick="if (!window.confirm('Are you sure you want to approve this booking?')) return false;" />
</ItemTemplate>
<ItemTemplate>
<asp:ImageButton runat="server" ID="REJECT" CommandName="update"
ImageUrl="~/images/reject.png"
OnClientClick="if (!window.confirm('Are you sure you want to reject this booking?')) return false;" />
</ItemTemplate>
My UPDATE statement
UpdateCommand="UPDATE [bookingschedule] SET status=#Status WHERE [bookingScheduleID] = #bookingScheduleID"
My ControlParameter
<UpdateParameters>
<asp:Parameter Name="bookingScheduleID" Type="Int32" />
<asp:ControlParameter Name="Status" ControlID="APPROVE" Type="Int32" />
<asp:ControlParameter Name="Status" ControlID="REJECT" Type="Int32" />
</UpdateParameters>
A button does not have a value in html and thus you can't use it in the ControlParameter declaration. One solution is to make a hidden textbox on the form. Lets call it "StatusType".
<input type="hidden" name="StatusType" value="0">
Now, in the "OnClientClick" of each of the buttons; assign the StatusType's value to either 1 or 2 (or whatever your defined status codes are).
OnClientClick="if (!window.confirm('Are you sure you want to reject this booking?')) {
return;
}
else {
$('#StatusType').val(0);
}"
Then use "StatusType" in the ControlParameter.
<asp:ControlParameter Name="Status" ControlID="StatusType" Type="Int32" />
Have you tried using the CommandArgument property of the ImageButton?
From MSDN:
Sometimes, multiple ImageButton controls are related and share the same value for the CommandName property, such as Sort. Use this property to supplement the CommandName property with additional information about the command to perform, such as Ascending. The values of the CommandName and CommandArgument properties are typically used in the OnCommand event handler to determine the action to perform when the ImageButton control is clicked.
<asp:ImageButton id="imagebutton1" runat="server"
AlternateText="Sort Ascending"
ImageUrl="images/pict.jpg"
OnCommand="ImageButton_Command"
CommandName="Sort"
CommandArgument="Ascending"/>

PostBack DataBind error: "Ensure that the control is added to the page before calling DataBind."

I have a program that allows the user to use a few dropdowns to pick a topic and attribute, then the data are pulled that match on both of those conditions. In the gridview are a lot of templatefields use textboxes for instant editing (a submit button saves all changes) as well as a template with a dropdown bound to a parameter. This was all working hunky-dory for quite a while.
Then, we changed some of the data in the tables (keeping all the same field names) and now the page loads perfectly fine on launch but then as soon as you select something different in any of the drilldown dropdowns the page fails. I get an error saying
"The DropDownList control 'TagDDL' does not have a naming container.
Ensure that the control is added to the page before calling DataBind."
(TagDDL is the dropdown in the templatefield in gridview). If I simply remove this templatefield, I get a similar (though different) error on a hyperlinkfield, removing this gives me an error in a boundfield, so obviously it's not tied to any one thing.
My idea is that it has something to do with how databinding works on post-back, since the page loads perfectly initially, the dropdowns have 'Enable PostBack' and the error messages refer to DataBind. Any ideas?
The SqlDataSource that builds Gridview (leaving out the drilldown dropdowns for now)
<asp:SqlDataSource ID="MasterTable" runat="server"
ConnectionString="<%$ ConnectionStrings:spvConnectionString %>"
SelectCommand="exec pmtv2.maintable_display 1, #IPG_Assigned, #CompetitorName, #enterprise_zone, #Banner, #BrandName"
<SelectParameters>
<asp:ControlParameter ControlID="ChooseBanner" Name="Banner" PropertyName="SelectedValue" Type="String" />
<asp:ControlParameter ControlID="ChooseIPGs" Name="IPG_Assigned" PropertyName="SelectedValue" Type="Int32" />
<asp:ControlParameter ControlID="ChooseBrands" Name="BrandName" PropertyName="SelectedValue" Type="String" />
<asp:ControlParameter ControlID="ChooseComps" Name="CompetitorName" PropertyName="SelectedValue" Type="String" />
<asp:ControlParameter ControlID="ChooseZone" Name="enterprise_zone" PropertyName="SelectedValue" Type="Int32" />
</SelectParameters>
<div id="MasterDiv" style="width:90%">
<asp:GridView ID="MasterDisplay" runat="server"
AllowSorting="True" AutoGenerateColumns="False"
DataKeyNames="productKey,banner,enterprise_zone,userID" DataSourceID="MasterTable"
OnRowDataBound="MasterDisplay_RowDataBound"
OnSorting="MasterDisplay_Sorting"
class="mGrid" AlternatingRowStyle-CssClass="mGridAlt">
</AlternatingRowStyle>
<Columns>
<asp:TemplateField HeaderText="Description" SortExpression="productdescriptionlong">
<ItemTemplate>
<a href="javascript:openPopup('JustinPractice4.aspx?UPC=<%# Eval("UPC") %>
&banner=<%# Eval("banner") %>&enterprise_zone=<%# Eval("enterprise_zone") %>')"><%# Eval("productdescriptionlong")%></a>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="BrandName" HeaderText="Brand"
SortExpression="BrandName" />
<asp:TemplateField HeaderText="New Price" SortExpression="new_base_retail">
<ItemTemplate>
<asp:TextBox ID="RWNextPrice" runat="server"
Text='<%# Bind("new_base_retail", "{0:N2}") %>' Width="60px"
class="calculate" onchange="lineItemRipple(this)"
Visible='<%# ShowBox %>'></asp:TextBox>
<asp:Label ID="RNextPrice" runat="server" Text='<%# Eval("new_base_retail", "{0:c}") %>'
Visible='<%# ShowLabel %>'></asp:Label>
<asp:HiddenField ID="lineCode" runat="server" Value='<%# Eval("line_code") %>'/>
</ItemTemplate>
</asp:TemplateField>
<asp:ImageField DataImageURLField="unique_flags" HeaderText="Flags"
DataImageURLFormatString="Media/Images/{0}.png" SortExpression="unique_flags"/>
<asp:TemplateField HeaderText="Tag Type" SortExpression="tag_type">
<ItemTemplate>
<asp:DropDownList ID="TagDDL" runat="server"
DataSourceID="dimTags"
DataTextField="Tag_type_name"
DataValueField="Tag_type_name"
SelectedValue='<%#Bind("tag_type") %>'
visible='<%#ShowBox %>'>
</asp:DropDownList>
<asp:Label ID="TagR" runat="server"
Text='<%# Eval("tag_type") %>'
Visible='<%# ShowLabel %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="Commit" runat="server" Text="Commit Changes" OnClick="Commit_Click"
class="button"/>
and the relevant code behind:
protected void Page_Load(object sender, EventArgs e) {
ErrorMsg.Text = "test45";
}
protected void MasterDisplay_RowDataBound(object sender, GridViewRowEventArgs e) {
DataSourceSelectArguments sr = new DataSourceSelectArguments();
DataView dv = (DataView)CheckForCommit.Select(sr);
if (dv.Count != 0) {
CommittedOrNot.Text = dv[0][0].ToString();
}
//pulling results from a SqlDataSource confirming presence of data
//calculations to maintain a running tally of certain fields for later use
}
protected void Commit_Click(Object sender, EventArgs e) {
string tagValue = "FLAG";
foreach (GridViewRow gvr in MasterDisplay.Rows) {
tagValue = ((DropDownList)gvr.FindControl("TagDDL")).SelectedValue;
MasterDisplay.UpdateRow(gvr.RowIndex, false);
} //for every row, update it
MasterDisplay.DataBind();
}
It was a simple error of trying to add to a DDL before I had actually pulled the data needed to bind it. Changing the order of things slightly did the trick
I am glad you found your answer. I had a similar issue on a UserControl (ascx) that was being loaded a run-time. I, too, had made a change to my data source and the corresponding sql data sources. (In my case, I was replacing the sql data sources with an entity model.)
What I found was that one of my controls would bind to the new data source (via the code behind) with no problems. The code looked as follows:
gridSomeData.DataSource = controller.GetListOfAssociatedParts();
gridSomeData.DataBind();
However, in the same method, the next section of code would fail when the DataBind() method was called. The code looked as follows:
drpDataList.DataSource = controller.GetListOfParts();
drpDataList.DataTextField = "PartID"
drpDataList.DataValueField = "PartKey"
drpDataList.DataBind();
It turned out, that when I removed the prior ASCX markup for the SqlDataSource objects, I failed to remove the reference in the DataSourceID attribute of the drop down control. So when I called the DataBind() method, the binding engine checked the attributes of the control, found a name DataSourceID, and immediately went looking for it in the control hierarchy of the UserControl. When the binding engine failed to find the object, it threw the exception "The DropDownList control [...] does not have a naming container..."
I will admit that this particular exception is somewhat misleading, as it is really the binder being confused over which instructions to follow for the data source (the code behind, or the markup in the ascx file).
I hope this helps with some perspective. :)

Data Binding Error in cascading Drop downs in asp.net

I have 2 drop down list within the edit item Template of a form view. The first drop down contains a lit of vehicle Makes and the second a list of Vehicle Models. The list of models needs to be filtered by the selection from the Makes drop down.
Here are the 2 Drop down List
<telerik:RadComboBox ID="RadComboBoxAssetMake" runat="server" DataTextField="AssetMakeName"
SelectedValue='<%# Bind("MakeId") %>' DataSourceID="odsAllAssetMakes" AutoPostBack="True" DataValueField="Id" Skin="Vista"
Width="212px" OnSelectedIndexChanged="RadComboBoxAssetMake_SelectedIndexChanged">
<telerik:Items>
<telerik:RadComboBoxItem Text="" Value="" />
</telerik:Items>
</telerik:RadComboBox>
<telerik:RadComboBox ID="RadComboBoxAssetModel" runat="server" DataTextField="AssetModelName"
SelectedValue='<%# Bind("ModelId") %>' DataSourceID="odsAssetModelByMake" DataValueField="Id" Skin="Vista" Width="212px">
<telerik:Items>
<telerik:RadComboBoxItem Text="" Value="" />
</telerik:Items>
</telerik:RadComboBox>
Initially I wanted to use a control select parameter on the object data source for the model Drop down. With the parameter getting the value from the Make drop down. However this doesn't seem to work as the select parameter on the object data source can't see the control with in the form view.
So now I am trying to use a session select parameter on the object data source.
<asp:ObjectDataSource runat="server" ID="odsAssetModelByMake" DataObjectTypeName="GPSO.Repository.AssetModel"
TypeName="GPSOnline.ATOMWebService" SelectMethod="GetAssetModelbyMake">
<SelectParameters>
<asp:SessionParameter DbType="Guid" SessionField="assetMakeId" Name="assetMakeId" />
</SelectParameters>
</asp:ObjectDataSource>
But now I get the this error "Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control." When I try to data bind the model drop down in the selected index changed method of the make drop down.
protected void RadComboBoxAssetMake_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
{
Session["assetMakeId"] = e.Value.ToString();
((RadComboBox) fvAsset.FindControl("RadComboBoxAssetModel")).DataBind();
}
Is there a simple way to achieve this kind of thing, it would seem like such a common scenario that there must be a standard way to do it?
Initially I wanted to use a control select parameter on the object
data source for the model Drop down. With the parameter getting the
value from the Make drop down. However this doesn't seem to work as
the select parameter on the object data source can't see the control
with in the form view.
You need to move the ObjectDataSource into templates:
<EditItemTemplate>
<telerik:RadComboBox ....
<telerik:RadComboBox ....
<asp:ObjectDataSource ....
<asp:ObjectDataSource ....
</EditItemTemplate>

Dropdownlist bind with parameterized datasource don't keep value after postback

There is a drop down list bind with datasource -> Called This DropDownList A
This datasource get another parameter from another dropdownlist -> Called This DropDownList B
Everytime DropDownList B Change the selected value, Datasource of Dropdownlist A will receive the parameter and change dropdownlist A.
Whenever DropDownlist change its index, it will cause postback and the selected value will be reset to the first index (default).
After Switching DropDownList A to use a datasource with no parameter. This problems is not occur.
After DropDownList A has changed its value and postback, the recenly changed value still there.
I have tried using update panel but it still is not work either.
This is DropDownList B, Add On Type
<asp:DropDownList ID="ddlAddOnType" runat="server" AppendDataBoundItems="True"
AutoPostBack="True" ClientIDMode="Static" CssClass="controlOrdinary"
DataSourceID="odsAddOnType" DataTextField="AddOnTypeName"
DataValueField="AddOnTypeId"
onselectedindexchanged="ddlAddOnType_SelectedIndexChanged" Width="208px">
<asp:ListItem Value="0">--Please Select--</asp:ListItem>
</asp:DropDownList>
This is datasource for dropDownlist A
<asp:ObjectDataSource ID="odsAddon" runat="server"
SelectMethod="SelectAddOnThatIsNotInCurrentPromotionWithAddOnByAddOnTypeId"
TypeName="BackOfficeLib.SupportAdmin.PromotionBinder">
<SelectParameters>
<asp:ControlParameter ControlID="ddlAddOnType" Name="pIntAddOnTypeId"
PropertyName="SelectedValue" Type="Int32" />
</SelectParameters>
</asp:ObjectDataSource>
This is dropdownlist A, when this one change the value, the page being post back suddenly and the index is reseted.
<asp:DropDownList ID="ddlAddOn" runat="server" AppendDataBoundItems="True"
AutoPostBack="True" ClientIDMode="Static" CssClass="controlOrdinary"
DataTextField="AddOnName" DataValueField="AddOnId"
onselectedindexchanged="ddlAddOn_SelectedIndexChanged" Width="208px">
<asp:ListItem Value="0">--Please Select--</asp:ListItem>
</asp:DropDownList>
The solution i use is keeping value in hidden field by javascript, using onchange event ( change the first drop down list)
This asp.net ajax control provide some help.
http://www.asp.net/ajax/ajaxcontroltoolkit/samples/CascadingDropDown/CascadingDropDown.aspx

ASP.NET DropDownList bound to data but allows for nulls?

I'm using LINQ to SQL and want to be able to select a parent or no parent. Let's say I have a People table with PersonId, Name and ParentId columns. In ASP I want to enter the name, select a parent and click 'Add' to create a new Person record, but I also want to be able to leave the ParentId null. Don't ask why, this is just a simplified explanation for what I want to do.
<asp:LinqDataSource ID="LinqPeople" runat="server"
ContextTypeName="MyDataContext" EntityTypeName=""
Select="new (PersonId, Name)" TableName="People"/>
<asp:TextBox ID="textName" runat="server" />
<asp:DropDownList runat="server" ID="dropParent"
DataSourceID="LinqPeople" DataTextField="Name" DataValueField="PersonId" />
<asp:Button ID="buttonAddPerson" runat="server" Text="Add" />
Is there any way to display 'None' in the list box with a value of null? I have thought of a few options, which is best or are there any others?
Create a stored procedure for the SQL "SELECT PersonId, Name FROM People UNION SELECT Null, 'NONE'"
Add a CheckBox for "NO PARENT"
Put a ListItem in the markup for the DropDownList
Add the item on the DataBound event handler
I found a better way, adding a ListItem in the markup:
<asp:LinqDataSource ID="LinqPeople" runat="server"
ContextTypeName="MyDataContext" EntityTypeName=""
Select="new (PersonId, Name)" TableName="People"/>
<asp:TextBox ID="textName" runat="server" />
<asp:DropDownList runat="server" ID="dropParent"
DataSourceID="LinqPeople" DataTextField="Name" DataValueField="PersonId">
<asp:ListItem Value="">(none)</asp:ListItem>
</asp:DropDownList>
<asp:Button ID="buttonAddPerson" runat="server" Text="Add" />
I cannot find any way to return the actual value 'NULL' in SelectedValue however, but I can handle that I guess. I think the ListItem way is the best because it is defined in the markup and doesn't require any code...
Don't think you can set the value of NULL since it's a string type.
I don't like the check for NULL, typically, I would use something that doesn't make sense, like -1 or something and check for that. You could also assume that your selected index is 0, however, that could cause problems somewhere else in code if you don't follow throughout the app.

Resources