I have a DropDownList control which really don't want to enable ViewState for as the item list is readily available from the server.
In this situation a post-back will obviously show an empty Items list, but at the same time I want the SelectedIndexChanged event to fire (using AutoPostBack)
The DropDownList control is actually dynamically created as part of a Composite Control which created an arbitrary number of DDLs - some of whose Items are sourced from the ASPX file (composite control contents) and others whose Items are bound to a data source. I am hoping that this complication isn't the source of the problem.
My thinking is that I should bind the list data to the Items collection on initial PageLoad and also rebind it late on PostBacks but I am not sure when. I am also not sure if the SelectedIndexChanged event handler will get called if on PostBack there is an empty Items list again.
Because it is part of a CompositeControl, I wonder if I should store some additional information in Control State. Would implementing something in the Conposite Control's Save/LoadControlState, Save/LoadViewState, RaisePostDataChangedEvent or RaisePostbackEvent be the solution?
Maybe I should rebind the Item list again early on PostBack e.g.before PageLoad?
Any pointers will be appreciated.
Thanks
Code provided below (cut out most of what is not relevant to problem)
Page ASPX
Note that I want to populate the ListItems of the { Group, Location, Division and BusinessUnit } DropDownLists dynamically with the items not being in dumped to ViewState but { Enabled } DDL is the static items defined below.
<cc1:FilterBar ID="FilterBar1" runat="server" CssClass="filterbar" OnFilterChanged="OnFilterChanged">
<cc1:Filter ID="Group" Label="Group" Type="DropDownList" />
<cc1:Filter ID="Location" Label="[Location]" Type="DropDownList" />
<cc1:Filter ID="Division" Label="[Division]" Type="DropDownList" />
<cc1:Filter ID="BusinessUnit" Label="[Business Unit]" Type="DropDownList" />
<cc1:Filter ID="Enabled" Label="Users" Type="DropDownList">
<asp:ListItem Value="X" Text="All"></asp:ListItem>
<asp:ListItem Value="1" Text="Active Only"></asp:ListItem>
<asp:ListItem Value="0" Text="Archived Only"></asp:ListItem>
</cc1:Filter>
</cc1:FilterBar>
Page Code Behind
protected void Page_Load(object sender, EventArgs e)
{
//if (!Page.IsPostBack) // whether to restire BindFilterBar() to first load or not?
BindFilterBar();
}
protected void BindFilterBar()
{
var h = new FilterBarBindHelper(FilterBar1);
h.AutoBindLocation(Filter.UserLocation.ID);
h.AutoBindDivision(Filter.UserDivision.ID);
h.AutoBindBusinessUnit(Filter.UserBusinessUnit.ID);
h.AutoBindGroup(Filter.UserGroup.ID);
var filter = FilterBar1.GetFilterByID("Enabled");
filter.SelectedValue = Filter.UserEnabledAsChar.ToString();
}
protected void OnFilterChanged(object sender, FilterChangedEventArgs e)
{
Debug.WriteLine($"[CompletionResults.aspx] OnFilterChanged(e={{FilterID={e.FilterID}; NewValue={e.NewValue} NewText={e.NewText}}})");
switch(e.FilterID)
{
case "Enabled":
Filter.UserEnabledAsChar = e.NewValue;
break;
case "Group":
if (e.NewValueAsInt == null)
Filter.UserGroup.Reset();
else
Filter.UserGroup.Set((int)e.NewValueAsInt, e.NewText);
break;
case "Division":
if (e.NewValueAsInt == null)
Filter.UserDivision.Reset();
else
Filter.UserDivision.Set((int)e.NewValueAsInt, e.NewText);
break;
case "BusinessUnit":
if (e.NewValueAsInt == null)
Filter.UserBusinessUnit.Reset();
else
Filter.UserBusinessUnit.Set((int)e.NewValueAsInt, e.NewText);
break;
case "Location":
if (e.NewValueAsInt == null)
Filter.UserLocation.Reset();
else
Filter.UserLocation.Set((int)e.NewValueAsInt, e.NewText);
break;
default:
return;
}
// Update Selection Text
BindSelectionText();
// Update the Grid
BindGrid();
}
/// <summary>
/// User has selected a new Page number from the UserGrid
/// </summary>
protected void OnPageChanged(object sender, EventArgs args)
{
Filter.ShowAllRows = false;
Filter.PageIndex = UserGrid.PageIndex;
BindGrid();
}
protected void OnAction(object sender, ToolbarActionClickedEventArgs args)
{
if (args.ActionValue == "email")
OnEmail();
}
FilterBarBindHelper.cs
public class FilterBarBindHelper
{
private readonly FilterBar _filterBar;
private readonly OrganisationProperties _orgProps;
public FilterBarBindHelper(FilterBar filterBar)
{
if (filterBar == null)
throw new ArgumentNullException(nameof(filterBar));
_filterBar = filterBar;
_orgProps = ObjectCache.GetOrganisationProperties();
}
/// <summary>
/// Binds Group list data to Filter, optionally creating the Filter if it doesn't exist
/// </summary>
/// <param name="selectedID">ID of currently selected Group to filter by (0 or null if none)</param>
/// <param name="createFilter">Create the Filter if not found</param>
public void AutoBindGroup(int? selectedID, bool createFilter = true)
{
// All Organisations have Groups.
// Only populate if a FilterBar Filter with ID="Groups" can be found or if createFilter = true
var f = _filterBar.GetFilterByID("Group");
if (f == null)
if (createFilter)
f = CreateFilter("Group", "Group");
else
return;
// Populate Filter list with items
var src = GroupCache.Get();
f.Items.Clear();
f.Items.Add(Any());
f.Items.AddRange(src.Select(s => new ListItem() { Value = s.StringID, Text = s.Name }).ToArray());
// Assign localised name
f.Label = _orgProps.GroupNm;
// Select
if((selectedID ?? 0) != 0)
f.SelectedValue = selectedID.Value.ToString();
_filterBar.RefreshFilter(f);
}
/// <summary>
/// Create a FilterBar Filter and add it to the FilterBar
/// </summary>
/// <param name="filterID">ID of filter to add</param>
/// <param name="label">Filter's label</param>
/// <param name="type">Filter's type</param>
/// <returns>New Filter</returns>
private Filter CreateFilter(string filterID, string label, FilterType type = FilterType.DropDownList)
{
var f = new Filter() { ID = filterID, Type = type, Label = label };
_filterBar.Filters.Add(f);
return f;
}
private ListItem Any()
{
return new ListItem("Any", "X");
}
}
Toolbar.cs
[
AspNetHostingPermission(SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Minimal),
AspNetHostingPermission(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal),
DefaultProperty("Items"),
ParseChildren(true, "Items"),
ToolboxData("<{0}:Toolbar runat=server />"),
Designer(typeof(ToolbarDesigner))
]
public class Toolbar : CompositeControl
{
private string _preText = "Actions: ";
private bool _showRight = true;
private readonly List<ToolbarItem> _list = new List<ToolbarItem>();
public Toolbar()
{
PreText = "Actions: ";
ObjectNameSingle = "Item";
ObjectNamePlural = "Items";
ShowRight = true;
}
protected override HtmlTextWriterTag TagKey { get { return HtmlTextWriterTag.Div; } }
[
Category("Behavior"),
Description("The Item collection"),
DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
Editor(typeof(ToolbarCollectionEditor), typeof(UITypeEditor)),
PersistenceMode(PersistenceMode.InnerDefaultProperty)
]
public List<ToolbarItem> Items
{
get { return _list; }
}
//various properties (snip)
protected override void RenderContents(HtmlTextWriter writer)
{
if(_leftSide != null)
_leftSide.RenderControl(writer);
if(_rightSide != null)
_rightSide.RenderControl(writer);
if(_leftSide == null && _rightSide == null && DesignMode)
writer.Write("No Toolbar Items have been set up in designer");
}
public void RebuildChildControls()
{
// Indicate that the child controls need rebuilding
// Ref: http://yourdotnetdesignteam.blogspot.co.uk/2008/09/life-cycle-of-aspnet-controls_28.html "Composite Controls" section:
// "Note 1: When the Composite Control is displayed normally, 'CreateChildControls' is called AFTER the 'Load' method.
// However, when a post back event occurs, 'CreateChildControls' is called AFTER the 'Init' method.
// This certainly makes the 'CreateChildControls' method an "interesting" aspect of the Life Cycle."
// So on postback, the calling method should call RebuildChildControls() after repopulating/modifying Filter Items
ChildControlsCreated = false;
//RecreateChildControls(); this will happen in due course anyway
}
// Controls in Composite Control
private ToolbarActionContainer _leftSide;
private WebControl _rightSide;
private ToolbarActionItem _liPreText;
private Literal _litPreText;
private HtmlGenericControl _spanRowCount;
private HtmlGenericControl _spanPageCount;
private DropDownList _ddlPage;
private Literal _litPageCount;
protected override void CreateChildControls()
{
Controls.Clear();
_leftSide = new ToolbarActionContainer(); // UL
_rightSide = new WebControl(HtmlTextWriterTag.Div);
_liPreText = new ToolbarActionItem(ToolbarActionType.PreText);
_litPreText = new Literal() { Text = "Actions: " };
// Create the Toolbar Action Items
var actionItems = new List<ToolbarActionItem>(_list.Count);
foreach (var item in _list)
{
if (item.Visible)
{
var li = CreateToolbarActionItemControls(item);
actionItems.Add(li);
}
}
_spanRowCount = new HtmlGenericControl("span"); // "NNN entitie(s) found";
_spanPageCount = new HtmlGenericControl("span"); // "Page [DDL] of [LIT]";
_ddlPage = new DropDownList() { ID = "PageDDL", AutoPostBack = true, EnableViewState = false };
_litPageCount = new Literal();
_spanPageCount.Controls.Add(new Literal() { Text = "Page " });
_spanPageCount.Controls.Add(_ddlPage);
_spanPageCount.Controls.Add(new Literal() { Text = " of " });
_spanPageCount.Controls.Add(_litPageCount);
_liPreText.Controls.Add(_litPreText);
_leftSide.Controls.Add(_liPreText);
foreach(var item in actionItems)
_leftSide.Controls.Add(item);
_rightSide.Controls.Add(_spanRowCount);
_rightSide.Controls.Add(_spanPageCount);
Controls.Add(_leftSide);
Controls.Add(_rightSide);
_ddlPage.SelectedIndexChanged += PageDDL_SelectedIndexChanged;
base.CreateChildControls();
ChildControlsCreated = true;
UpdateRowCountText(); // Assigns the RowCount text to the span control _spanPageCount
UpdatePageCountText(); // The Y in "Page X of Y"
ApplyStandardClassNames();
CreatePageDDLItems(); // Populates Items in PageDDL (if required)
AssignPageDDLSelectedValue(); // Assigns the current PageDDL value (if required)
}
protected virtual ToolbarActionItem CreateToolbarActionItemControls(ToolbarItem item)
{
// Create List Item and add CssClass if required
var li = CreateToolbarActionItem(ToolbarActionType.Action);
if (item.HasCssClass)
li.CssClass = item.CssClass;
if (item.TextOnly)
{
// Text Only Action Items are added as literal text
li.Controls.Add(new Literal() { Text = item.Text });
}
else
{
var btn = new LinkButton() { Text = item.Text, ToolTip = item.ToolTip, CssClass = item.CssClass };
if (item.HasURLLink)
btn.Attributes.Add("href", item.URLLink);
else
{
btn.Click += LinkButton_Clicked;
_map.Add(btn, item); // used if posting back
// btn.Attributes.Add("href", "#");
// var js = MakeButtonJavaScript(item);
// if (js != string.Empty)
// btn.Attributes.Add("onclick", "javascript:" + js);
if(!string.IsNullOrEmpty(item.PrePostbackJSFunction))
btn.OnClientClick = $"return {item.PrePostbackJSFunction}(this);";
}
li.Controls.Add(btn);
}
return li;
}
protected virtual ToolbarActionItem CreateToolbarActionItem(ToolbarActionType type)
{
return new ToolbarActionItem(type);
}
private void CreatePageDDLItems()
{
// No DDL control created yet?
if (!ChildControlsCreated)
return;
var pageCount = PageCount;
// Current count is already correct?
if (pageCount == _ddlPage.Items.Count - 1) // -1 = "all"
return;
_ddlPage.Items.Clear();
_spanPageCount.Visible = (pageCount > 1); // Show this section only if multipage
// Not multi page?
if (pageCount <= 1)
return;
var li = new ListItem("All", "all");
_ddlPage.Items.Add(li);
for (var i = 0; i < pageCount; i++)
{
li = new ListItem((i + 1).ToString());
_ddlPage.Items.Add(li);
}
// AssignPageDDLSelectedValue() is already called whenever CreatePageDDLItems() is called!
//AssignPageDDLSelectedValue();
}
private void AssignPageDDLSelectedValue()
{
if (!ChildControlsCreated)
return;
if (ShowAllPages)
_ddlPage.SelectedValue = "all";
else
_ddlPage.SelectedValue = CurrentPage.ToString();
}
private void LinkButton_Clicked(object sender, EventArgs e)
{
System.Diagnostics.Debug.Assert(sender is LinkButton);
var button = sender as LinkButton;
var item = _map[button];
// Raise event with item's value
OnActionButtonClicked(item.Value);
}
private void PageDDL_SelectedIndexChanged(object sender, System.EventArgs e)
{
System.Diagnostics.Debug.Assert(sender == _ddlPage);
var v = _ddlPage.SelectedValue;
var newShowAllPages = (v == "all");
var newPage = newShowAllPages ? 0 : int.Parse(v);
// No Change?
if (newShowAllPages == ShowAllPages &&
(!newShowAllPages && (newPage == CurrentPage)))
return;
// Assign and raise event
ShowAllPages = newShowAllPages;
CurrentPage = newPage;
OnPageChanged(newShowAllPages, newPage);
}
private void OnActionButtonClicked(string id)
{
var evt = ActionClicked;
// check there are subscribers, and trigger if necessary
if (evt != null)
evt(this, new ToolbarActionClickedEventArgs(id));
}
private void OnPageChanged(bool showAll, int newPageNumber)
{
var evt = PageChanged;
// check there are subscribers, and trigger if necessary
if (evt != null)
evt(this, new ToolbarPageChangedEventArgs(showAll, newPageNumber));
}
}
public class ToolbarPageChangedEventArgs : EventArgs
{
public bool ShowAllPages { get; }
public int NewPageNumber { get; }
internal ToolbarPageChangedEventArgs(bool showAllPages, int newPageNumber)
{
ShowAllPages = showAllPages;
NewPageNumber = newPageNumber;
}
}
public class ToolbarActionClickedEventArgs : EventArgs
{
public string ActionValue { get; }
internal ToolbarActionClickedEventArgs(string value)
{
ActionValue = value;
}
}
public delegate void ToolbarPageChangedEventHandler(object sender, ToolbarPageChangedEventArgs args);
public delegate void ToolbarActionClickedEventHandler(object sender, ToolbarActionClickedEventArgs args);
ToolbarItem.cs
[TypeConverter(typeof(ExpandableObjectConverter))]
public class ToolbarItem
{
public ToolbarItem() : this(string.Empty, string.Empty, string.Empty, string.Empty)
{
}
public ToolbarItem(string text, string value, string jslink, string urllink)
{
Text = text;
Value = value;
JSLink = jslink;
URLLink = urllink;
CssClass = string.Empty;
ToolTip = string.Empty;
PrePostbackJSFunction = string.Empty;
Visible = true;
}
.... snip ...
}
public enum ToolbarActionType
{
None = 0,
PreText = 1,
Action = 2,
}
I am trying to get specific cell value so i can pass it in my method when i press the button but i get always null on both (and i know that is not null).
P.s: None row is selected because i made a loop to get all the rows. The variable "p" is getting correct the number of the rows that i have on the grid.
protected void PostRadButton_Click(object sender, EventArgs e)
{
int p;
if (DocStatTxtBox.Text == "2")
{
foreach (GridDataItem item in RadGrid1.Items)
{
p = item.RowIndex;
string itemcodeparam = item["ItemCode"].Text;//error null (4th cell)
int quantityparam = Convert.ToInt16(item.Cells[5].Text);//error null
Boolean x = Methods.UpdateStock(WhTxtBoxRadDropDownList.SelectedValue,itemcodeparam,-quantityparam);
}
}
}
Finally i did it with this code
protected void PostRadButton_Click(object sender, EventArgs e)
{
int p;
if (DocStatTxtBox.Text == "2")
{
foreach (GridDataItem item in RadGrid1.Items)
{
p = item.RowIndex;
Label itemparam = (Label)item["ItemCode"].FindControl("ItemCodeLabel");
Label qparam = (Label)item["Quantity"].FindControl("QuantityLabel");
string itemcodeparam = itemparam.Text;
int quantityparam = Convert.ToInt16(qparam.Text);
Boolean x = Methods.UpdateStock(WhTxtBoxRadDropDownList.SelectedValue, itemcodeparam, -quantityparam);
}
}
}
hi I'm Litte big english I want ComboboxID in datagridview query..
Aşağıdaki kod için yardıma ihtiyacım var ... Sanırmı çok kolay bir
şeydir ama yeni başladığım için içinden çıkamıyorum
public void cmbComp_SelectedValueChanged(object sender, EventArgs e)
{
ServisHEntities Context = new ServisHEntities();
cmbCus.DataSource = Context.SCustomers.ToList();
cmbCus.DisplayMember = "SDescription";
cmbCus.ValueMember = "SCustomerID";
cmbCus.SelectedIndex = -1;
cmbCus.Invalidate();
}
public void cmbCus_SelectedValueMemberChanged(object sender, EventArgs e)
{
{
grdUser.DataSource = (from USR in oe.SUsers
where (USR.SCustomerID == /* cmbCus.ValueMember() I Want SCustomerID is here /// ID nin buraya gelmesini istiyorum */ && USR.SUserStatus == true && USR.SUserType == 2)
select new { USR.SUserName, USR.SUserSurname, USR.SPhone, USR.SSEmail }).ToList();
}
}
This should give you the selected item's value. Good luck! You can use cmbCus.SelectedValue inline like you have in your example as well.
var val = cmbCus.SelectedValue;
So I am recieving some postback data back from a form and need to get the checkbox values for a group of checkboxes in a parent control. I coded it up and it was working but now no longer works and I can not figure out why. The checkboxes are created on page load dynamically but on postback nothing seems to be checked when the form had checked items, the only postback event is the submit button event.
// This is from the btnSubmit Postback event that isn't working anymore
foreach (CheckBox cb in ShowPermissions.Controls.OfType<CheckBox>())
{
if (cb.Checked)
{
// Add New Admins Permissions
Permission p = new Permission();
p.AdminUserID = au.id;
p.AdminMenuID = Convert.ToInt32(cb.ID.ToString().Substring(4));
ngdb.Permissions.InsertOnSubmit(p);
submitResult.InnerHtml += cb.ID.ToString();
// Does not run now?
}
// can see the checkbox object
}
protected void Page_Load(object sender, EventArgs e)
{
FunctionType = Request.QueryString["func"] != null && Request.QueryString["func"] != "" ? Request.QueryString["func"] : null;
RID = Request.QueryString["rid"] != null && Request.QueryString["rid"] != "" ? int.Parse(Request.QueryString["rid"]) : -1;
PopulateAdminTypes();
if (!IsPostBack && FunctionType == "edit" && RID != -1)
{
// Populate User details for Edit
PopulateUser(RID);
// Populate checkboxes and check selected options
PopulateAdminPermissionOptions(true, RID);
// Disable password change
ChangePassword(false);
}
else if (!IsPostBack)
{
chkChangePassword.Visible = false;
PopulateAdminPermissionOptions(false, -1);
}
}
private void PopulateAdminPermissionOptions(bool blnPopulateForEdit, int RID)
{
// Get Logged in Admin ID
int intAdminId = Convert.ToInt32(Session["AdminID"]);
int intAdminTypeId = Convert.ToInt32(Session["AdminTypeID"]);
using (NewGeorgeDataContext ngdb = new NewGeorgeDataContext())
{
var am = ngdb.AdminMenus.AsQueryable();
// Hide Add and Edit Options from Non Super Users
var amUsers = ngdb.AdminMenus.Where(x => x.id > 2 && x.id < 5);
if (intAdminTypeId > 1) am = am.Except(amUsers);
foreach (var m in am.OrderBy(x => x.MenuTypeID).ThenBy(x => x.id))
{
// Add New CheckBox
CheckBox cb = new CheckBox();
cb.ID = "chk_" + m.id;
cb.CssClass = "chkItems";
cb.Text = m.AdminMenuType.Name + ": " + m.Name;
// Get Admin Permission objects
if (blnPopulateForEdit)
{
var ap = ngdb.Permissions.SingleOrDefault(x => x.AdminUserID == RID && x.AdminMenuID == m.id);
if (ap != null)
{
cb.Checked = true;
}
}
ShowPermissions.Controls.Add(new LiteralControl("<p>"));
ShowPermissions.Controls.Add(cb);
ShowPermissions.Controls.Add(new LiteralControl("</p>"));
}
}
}
Can someone workout what I cannot see atm?
The view state isn't getting load into your controls. You must create all the controls before LoadViewState triggers. So, create all dynamic Controls OnPageInit event or Page_Init method to get the correct behavior. Take a look here to get more information about Asp.NET Page Life Cycle
Hopes this help you!
I have two DropDownLists one for the type of a soldier and one for the number of soldiers the player i allowed to buy. I populate ddlSoldiers with a LinqDataSource in the aspx page like this:
<asp:DropDownList ID="ddlSoldiers" runat="server"
DataSourceID="LinqDataSource2" DataTextField="type"
DataValueField="troopid" AutoPostBack="True">
</asp:DropDownList>
<asp:LinqDataSource ID="LinqDataSource2" runat="server"
ContextTypeName="BrowserSpill.LinqClass1DataContext" EntityTypeName=""
Select="new (type, troopid)" TableName="Troops">
</asp:LinqDataSource>
The other list ddlSoldierNumber is populated in the pageload like this:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["userRole"] == null || Session["userRole"].Equals("admin"))
{
Response.Redirect("Login.aspx");
}
int userid = Convert.ToInt32(Session["userid"]);
if(string.IsNullOrEmpty(ddlSoldiers.SelectedValue))
{
var varTroopType = dc.Troops.Single(t => t.troopid == 1).type;
string troopType = Convert.ToString(varTroopType);
var varBuildingId = dc.Buildings.Single(b => b.soldierType == troopType).buildingid;
int buildingId = Convert.ToInt32(varBuildingId);
var varNumberOfBuildings =
dc.Towns.Single(t => (t.buildingid == buildingId) && (t.userid == userid)).number;
int numberOfBuildings = Convert.ToInt32(varNumberOfBuildings);
for (int i = 1; i < numberOfBuildings + 1; i++)
{
ddlSoldierNumber.Items.Add(i.ToString());
}
}
else
{
ddlSoldierNumber.Items.Clear();
string troopType = ddlSoldiers.SelectedItem.Text;
var varBuildingId = dc.Buildings.Single(b => b.soldierType == troopType).buildingid;
int buildingId = Convert.ToInt32(varBuildingId);
var varNumberOfBuildings =
dc.Towns.Single(t => (t.buildingid == buildingId) && (t.userid == userid)).number;
int numberOfBuildings = Convert.ToInt32(varNumberOfBuildings);
for(int i = 1; i < numberOfBuildings+1; i++)
{
ddlSoldierNumber.Items.Add(i.ToString());
}
}
}
But when i want to get the values from ddlSoldierNumber i only get the first value in that list. I try to get the number with the click of a button like this:
protected void btnBuySoldier_Click(object sender, EventArgs e)
{
string numbertobuy = ddlSoldierNumber.SelectedItem.Value;
lblAntall.Text = numbertobuy;
}
I have tried to put the line:
ddlSoldierNumber.Items.Clear();
other places but without any luck. Does anyone know how i can clear the number list after I press the button and before the ddlSoldierNumber get repopulated?
if you want to populate ddlSoldierNumber on the basis of selection from ddlSoldiers then you can not add values to ddlSoldierNumber in page load event. for that you have to add your page load event code in (ddlSoldiers) selected index change event.
protected void ddlSoldiers_SelectedIndexChanged(object sender, EventArgs e)
{
if (Session["userRole"] == null || Session["userRole"].Equals("admin"))
{
Response.Redirect("Login.aspx");
}
int userid = Convert.ToInt32(Session["userid"]);
if (string.IsNullOrEmpty(ddlSoldiers.SelectedValue))
{
var varTroopType = dc.Troops.Single(t => t.troopid == 1).type;
string troopType = Convert.ToString(varTroopType);
var varBuildingId = dc.Buildings.Single(b => b.soldierType == troopType).buildingid;
int buildingId = Convert.ToInt32(varBuildingId);
var varNumberOfBuildings =
dc.Towns.Single(t => (t.buildingid == buildingId) && (t.userid == userid)).number;
int numberOfBuildings = Convert.ToInt32(varNumberOfBuildings);
for (int i = 1; i < numberOfBuildings + 1; i++)
{
ddlSoldierNumber.Items.Add(i.ToString());
}
}
else
{
ddlSoldierNumber.Items.Clear();
string troopType = ddlSoldiers.SelectedItem.Text;
var varBuildingId = dc.Buildings.Single(b => b.soldierType == troopType).buildingid;
int buildingId = Convert.ToInt32(varBuildingId);
var varNumberOfBuildings =
dc.Towns.Single(t => (t.buildingid == buildingId) && (t.userid == userid)).number;
int numberOfBuildings = Convert.ToInt32(varNumberOfBuildings);
for (int i = 1; i < numberOfBuildings + 1; i++)
{
ddlSoldierNumber.Items.Add(i.ToString());
}
}
}
If I remember correctly, the pageload is run before your eventhandler for the button, have you tried placing the ddlSolderNumber.Items.Clear(); in the Click eventhandler after you change the label?
(I know this doesnt solve the issue with your first question)
For that you could try: (If Im confusing I apologize, Im bad at explaining myself)
You could create a "populate" method for your ddlSoldierNumber list, that you call after your click-event.
In your pageload, you could then on a check of "if (!PostBack)" run your default startup logic.