Select Values from two combobox from a list of combobox? - asp.net

I have six combobox placed on my form and at same time i want user can select values from maximum of two combobox.
for this i have take a counter variable which get incremented every time when selectedindex of a combobox get changed but didn't reach to solution.
Can you guys explain how can i do this ?

I created an example for you. I hope it can be usefull.
ASP.Net Page:
<form id="form1" runat="server">
<div>
<div>
<label>Combobox 1</label>
<asp:DropDownList runat="server" OnSelectedIndexChanged="Unnamed1_SelectedIndexChanged" AutoPostBack="True">
<asp:ListItem>Select</asp:ListItem>
<asp:ListItem>Combo-1-1</asp:ListItem>
<asp:ListItem>Combo-1-2</asp:ListItem>
</asp:DropDownList>
</div>
<div>
<label>Combobox 2</label>
<asp:DropDownList runat="server" OnSelectedIndexChanged="Unnamed1_SelectedIndexChanged" AutoPostBack="True">
<asp:ListItem>Select</asp:ListItem>
<asp:ListItem>Combo-2-1</asp:ListItem>
<asp:ListItem>Combo-2-2</asp:ListItem>
</asp:DropDownList>
</div>
<div>
<label>Combobox 3</label>
<asp:DropDownList runat="server" OnSelectedIndexChanged="Unnamed1_SelectedIndexChanged" AutoPostBack="True">
<asp:ListItem>Select</asp:ListItem>
<asp:ListItem>Combo-3-1</asp:ListItem>
<asp:ListItem>Combo-3-2</asp:ListItem>
</asp:DropDownList>
</div>
<div>
<label>Combobox 4</label>
<asp:DropDownList runat="server" OnSelectedIndexChanged="Unnamed1_SelectedIndexChanged" AutoPostBack="True">
<asp:ListItem>Select</asp:ListItem>
<asp:ListItem>Combo-4-1</asp:ListItem>
<asp:ListItem>Combo-4-2</asp:ListItem>
</asp:DropDownList>
</div>
<div>
<label>Combobox 5</label>
<asp:DropDownList runat="server" OnSelectedIndexChanged="Unnamed1_SelectedIndexChanged" AutoPostBack="True">
<asp:ListItem>Select</asp:ListItem>
<asp:ListItem>Combo-5-1</asp:ListItem>
<asp:ListItem>Combo-5-2</asp:ListItem>
</asp:DropDownList>
</div>
<div>
<label>Combobox 6</label>
<asp:DropDownList runat="server" OnSelectedIndexChanged="Unnamed1_SelectedIndexChanged" AutoPostBack="True" Height="19px">
<asp:ListItem>Select</asp:ListItem>
<asp:ListItem>Combo-6-1</asp:ListItem>
<asp:ListItem>Combo-6-2</asp:ListItem>
</asp:DropDownList>
</div>
<div>
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
</div>
</div>
</form>
ASP.Net Code-Behind
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["DropdownSelectLimit"] = 0;
}
}
protected void Unnamed1_SelectedIndexChanged(object sender, EventArgs e)
{
if (ViewState["DropdownSelectLimit"] != null)
{
if ((int)ViewState["DropdownSelectLimit"] < 2)
{
int count = (int)ViewState["DropdownSelectLimit"];
count++;
ViewState["DropdownSelectLimit"] = count;
}
else
{
DropDownList dropDown = (DropDownList)sender;
dropDown.SelectedIndex = 0;
Label1.Text = "You can't select any option anymore";
}
}
}
If you have any question just ask me on comments :)

I created a setup for Winforms as it wasn't complete clear if you wanted it for Winforms or ASP.Net
I will not handle how you should fill a combobox, i'm sure you know how to do this, whether this is filled static or dynamic.
My solution (although quite rude) makes you link a simplified handler named HandleComboBoxSelectedIndexChanged to each combobox SelectionChanged event. This can be The SelectedItemChanged, SelectedValueChanged or SelectedIndexChanged.
Quite important: each combo needs a null value.
//will hold a list of your combobox names
private List<string> SelectedCombos;
//form load: Link the events to the correct handler
private void Form_Load()
{
foreach(var combo in Controls)
{
if(combo is ComboBox)
combo.SelectedValueChanged += HandleComboBoxSelectedIndexChanged;
}
}
//will handle the selectedIndexOrItemchanged event
private void HandleComboBoxSelectedIndexChanged(object sender, EventArgs e)
{
if(SelectedCombos = null)
SelectedCombos = new List<string>();
var combo = (ComboBox)sender;
if(combo.SelectedValue == null)
if(!SelectedCombos.Exist(combo.Name))
SelectedCombos.Remove(combo.Name);
else
if(!SelectedCombos.Exist(combo.Name) && SelectedCombos.Count < 2)
SelectedCombos.Add(combo.Name)
SetComboAvailability();
}
Another function which might be useful, whenever 2 combos are selected, make the enabled state false. This means that your user can only select from the 2 selected combos untill one of them is reset at it's null position. This way your user can only select what is possible.
//set the combos availability, less then 2 selections ok, own selection also ok else not ok
private void SetComboAvailability()
{
foreach(var combo in Controls)
{
if(combo is ComboBox)
combo.Enabled = SelectedCombos.Count < 2 || SelectedCombos.Contains(combo.Name);
}
}
Below a small example of how you could retrieve all your values from the combos based on their names.
//Something for handling all the values
private void RetrieveValues()
{
foreach(var v in SelectedCombos)
{
var combo = this.Controls.Find(v);
if(combo is ComboBox)
{
//do something with the selectedValue
var val = combo.SelectedValue; // or selecteditem
MessageBox.Show(string.Format("Control {0} has value {1}", combo.Name, val);
}
}
}
If you don't understand something feel free to ask.
Also:
the EventArgs property might change according to the selected event:
do: _comboBox1.SelectedValueChanged+= (TAB TWICE in VS) to see what the automatic code generation looks like. (always handy)
Example:
_comboBox1.SelectedValueChanged += _comboBox1_SelectedValueChanged;
private void _comboBox1_SelectedValueChanged(object sender, EventArgs e){}

Related

Custom validator message not displaying

VS2013, WebForms, .NET 4.51
I have a FormView defined and in my EditTemplate I have as follows:
<div class="form-group">
<asp:Label ID="lblClientClassification" CssClass="col-md-2 control-label" runat="server" for="cblClientClassifications" Text="Kind"></asp:Label>
<div class="col-md-5">
<asp:CheckBoxList ID="cblClientClassifications" runat="server"></asp:CheckBoxList>
<asp:CustomValidator ID="cfvClientKinds" runat="server" Display="Dynamic" CssClass="label label-danger" ErrorMessage="XXXX" ValidationGroup="Default" OnServerValidate="cfvClientClassifications_OnServerValidate"></asp:CustomValidator>
</div>
and then in the code behind:
protected void cfvClientClassifications_OnServerValidate(object aSource, ServerValidateEventArgs aArgs)
{
CustomValidator cvCheckBoxKinds = aSource as CustomValidator;
int checkedCount = 0;
if (cvCheckBoxKinds != null)
{
CheckBoxList cblClientClassifications = GuiClientClassificationsFind();
foreach (ListItem listItem in cblClientClassifications.Items)
{
if (listItem.Selected)
{
checkedCount++;
}
}
if (checkedCount == 0)
{
aArgs.IsValid = false;
cvCheckBoxKinds.ErrorMessage = "Select client kind.";
}
}
}
The OnServerValidate is firing and I am getting to set the validator to invalid as well as setting the error message (Page.IsValid is also false as expected). However, the error text is not displaying. When I view the page source I see:
<span id="ctl00_cphMainContent_fvData_cfvClientKinds" class="label label-danger" style="display:none;">XXXX</span>
instead of the error message I set as well as the fact that it is not visible.
Has anyone got any pointers here on how to track this down? I have looked at similar questions of SO but none of the comments seem to apply. Is this related to FormView perhaps?
Try your control without the CssClass="label label-danger" bootstrap first, and use the code below to check your boxes:
protected void cfvClientKinds_ServerValidate(object aSource, ServerValidateEventArgs aArgs)
{
aArgs.IsValid = cblClientClassifications.SelectedItem != null;
cfvClientKinds.ErrorMessage = "Hey! this is a new message";
}
and I guess you call this line before you fire the above event:
protected void btnValidate_Click(object sender, EventArgs e)
{
Page.Validate();
}
In Short, I think that your problem is either related to your way of finding cblClientClassifications checkBoxList or other code that you haven't stated above.
CheckBoxList cblClientClassifications = GuiClientClassificationsFind();
I decided to try out your case and created a new webform added formview and bind it to northwind categories table then inside edititemtemplate I added a checkboxlist and populated it manually. added CustomValidator double clicked it copied your codebehind and it works for me except for the findcontrol part: GuiClientClassificationsFind();
Here is the formview:
<asp:FormView ID="FormView1" runat="server" DataKeyNames="CategoryID" DataSourceID="SqlDataSource1">
<EditItemTemplate>
...
<asp:CheckBoxList ID="cblClientClassifications" runat="server">
<asp:ListItem>Bir</asp:ListItem>
<asp:ListItem>iki</asp:ListItem>
<asp:ListItem>Üç</asp:ListItem>
<asp:ListItem>Dört</asp:ListItem>
</asp:CheckBoxList>
<asp:CustomValidator ID="cfvClientKinds" runat="server" Display="Dynamic" CssClass="label label-danger" ErrorMessage="CustomValidator" OnServerValidate="cfvClientKinds_ServerValidate"></asp:CustomValidator>
<br />
<asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True" CommandName="Update" Text="Update" />
<asp:LinkButton ID="UpdateCancelButton" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel" />
</EditItemTemplate>
</asp:FormView>
And codebehind with your code:
protected void cfvClientKinds_ServerValidate(object aSource, ServerValidateEventArgs aArgs)
{
CustomValidator cvCheckBoxKinds = aSource as CustomValidator;
CheckBoxList cblClientClassifications = (CheckBoxList)FormView1.FindControl("cblClientClassifications");
int checkedCount = 0;
if (cvCheckBoxKinds != null)
{
foreach (ListItem listItem in cblClientClassifications.Items)
{
if (listItem.Selected)
{
checkedCount++;
}
}
if (checkedCount == 0)
{
aArgs.IsValid = false;
cvCheckBoxKinds.ErrorMessage = "Select client kind.";
}
}
}
I Ali Shahrokhi's method is shorter and works as well as yours..
protected void cfvClientKinds_ServerValidate(object aSource, ServerValidateEventArgs aArgs)
{
CustomValidator cvCheckBoxKinds = aSource as CustomValidator;
CheckBoxList cblClientClassifications = (CheckBoxList)FormView1.FindControl("cblClientClassifications");
aArgs.IsValid = cblClientClassifications.SelectedItem != null;
cvCheckBoxKinds.ErrorMessage = "Select client kind.";
}
if you check as you entered edititemtemplate in formview you'll see before submitting that your customvalidators span will be there just as you mentioned that's because server hasn't sent it to the client yet somehow.

asp.net create uzer wizard getting a handle on controls in custom steps

I have added an extra step to my uzerwizard
<asp:TemplatedWizardStep id="stpPayment" runat="server" Title="Payment">
<ContentTemplate>
<asp:DropDownList ID="cmbSubs" runat="server" ClientIDMode="Static"
Width="200px">
<asp:ListItem Value="month">Monthly Subscription</asp:ListItem>
<asp:ListItem Value="year">Annual Subscription</asp:ListItem>
</asp:DropDownList>
i am successfully navigating to the new step
protected void NewUserprofileWizard_NextButtonClick(object sender, WizardNavigationEventArgs e)
{
if (NewUserprofileWizard.ActiveStepIndex == 0)
{
NewUserprofileWizard.ActiveStepIndex = 1;
}
}
but I cant get access to the dropdownlist from my codebehind
note: i can get a handle onto the controls in the 1st (createuser) step.
but any controls in the next step always return a null.
this is the code i am using
DropDownList cmb = (DropDownList)NewUserprofileWizard.WizardSteps[1].FindControl("cmbSubs");
i always return a null.
note that this works just fine
TextBox tmp = (TextBox)NewUserprofileWizard.CreateUserStep.ContentTemplateContainer.FindControl("Email");
userProfile.AccountEmail = tmp.Text;
problem seems unique to custom steps
Thanks for the help
Tried Gregors suggestion. no luck. mine always comes up as null.
if thsi helps any:
my wizard is inside a user control..
the page that uses the user control is inside a master page.....
Here is little sample I have created for you, first aspx code:
<asp:CreateUserWizard ID="CreateUserWizard1" runat="server" OnNextButtonClick="CreateUserWizard1_NextButtonClick">
<WizardSteps>
<asp:WizardStep runat="server" Title="My Custom Step">
<asp:DropDownList ID="cmbSubs" runat="server" ClientIDMode="Static"
Width="200px">
<asp:ListItem Value="month">Monthly Subscription</asp:ListItem>
<asp:ListItem Value="year">Annual Subscription</asp:ListItem>
</asp:DropDownList>
</asp:WizardStep>
<asp:CreateUserWizardStep runat="server" />
<asp:CompleteWizardStep runat="server" />
</WizardSteps>
</asp:CreateUserWizard>
And now the code to find first dropdown:
protected void CreateUserWizard1_NextButtonClick(object sender, WizardNavigationEventArgs e)
{
if (e.CurrentStepIndex == 0)
{
//get instance to dropdown...
string selectedValue = null;
string controlId = null;
foreach (var item in CreateUserWizard1.WizardSteps[0].Controls)
{
DropDownList ddl = item as DropDownList;
if (ddl != null)
{
selectedValue = ddl.SelectedValue;
controlId = ddl.ClientID;
break;
}
}
}
}
Of course you can also find your dropdown like this:
DropDownList cmbSubs = CreateUserWizard1.WizardSteps[0].FindControl("cmbSubs") as DropDownList;
Happy coding!
it appears that today my google foo was doing much better
because i am in a templateswizardstep, i have to cast the wizardstep into the templatedwizardstep.
from here i can now find the control. whooohoo!
TemplatedWizardStep step = (TemplatedWizardStep)NewUserprofileWizard.WizardSteps[1];
cmb = (DropDownList)step.ContentTemplateContainer.FindControl("cmbSubs");
Thanks all for the help

How to disable first checkbox after other one clicked in repeater

I have a repeater and there is a checkbox. When I click first one in checkedchanged event row information appear down below. But after first click I have a trouble. Sometimes informations are same. Because foreach always see the first click. For instance, I checked second one and I saw the informations. Then I click second one ok again I saw the informations, but this time I clicked again first one. Foreach can take first checkbox and the last one still checked before postback it's again doing second one's operation.
Is there any way to fix this?
Here is my sample code.
<asp:Repeater ID="rptInformations" runat="server">
<ItemTemplate>
<asp:CheckBox ID="ckChoose" runat="server" OnCheckedChanged="ckChoose_CheckedChanged" AutoPostBack="true" />
<div id="foo" runat="server"> ... some basic titles ...</div>
</ItemTemplate>
<asp:Repeater>
<div id="info" runat="server"> ... informations in here (textboxes, labels ..etc)</div>
CodeBehind:
foreach (RepeaterItem item in rptInformations.Items)
{
//CheckBox ckChoose= (CheckBox)sender;
CheckBox ckChoose= item.FindControl("ckChoose") as CheckBox;
if (cBoxChoose.Checked)
{
... database process ...
}
}
As for what I understand you are trying to trigger an event everytime you check the checkbox and it will show certain info according to the row of the repeater it belongs to, for this I have made this example on a page called Repeater.aspx, using an event that will only fire for one checkbox and not for all:
Repeater.aspx:
<asp:Repeater runat="server" ID="repeater">
<ItemTemplate>
<asp:CheckBox ID="ckChoose" runat="server" AutoPostBack="true" OnCheckedChanged="ckChoose_CheckedChanged"/>
<div id="foo" runat="server"> <%# Eval("Field2")%></div>
</ItemTemplate>
</asp:Repeater>
<div id="info" runat="server"> ... informations in here (textboxes, labels ..etc)</div>
Repeater.aspx.cs (Codebehind):
partial class Repeater1 : System.Web.UI.Page
{
private System.Collections.Generic.List<Item> Elements()
{
Generic.List<Item> itemList = new Generic.List<Item>();
itemList.Add(new Item("1", "One"));
itemList.Add(new Item("2", "Two"));
return itemList;
}
protected void Page_Load(object sender, System.EventArgs e)
{
if (!Page.IsPostBack) {
this.repeater.DataSource = this.Elements();
this.repeater.DataBind();
}
}
protected void ckChoose_CheckedChanged(object sender, System.EventArgs e)
{
CheckBox chk = (CheckBox)sender;
this.info.InnerHtml = "checkbox:" + chk.ID + " foo:" + ((HtmlGenericControl)chk.Parent.FindControl("foo")).InnerText;
}
}
Hope this helps.
I guess I fix it with namingcontainer. It works perfect.
foreach (RepeaterItem item in Repeater1.Items)
{
CheckBox cBoxx = item.FindControl("ckChoose") as CheckBox;
current_cbId = cBoxx.NamingContainer.UniqueID.ToString();
if (cBoxx.Checked)
{
... some operations ...
}
if (cBoxChoose.NamingContainer.UniqueID.ToString() != current_cbId)
cBoxChoose.Checked = false;
}

Why do I have to click a button twice in an ASP.NET repeater to get the command to fire?

I have an ASP.NET page with the following 3 main areas:
1 - list of checkboxes on the left for fitlering results
2 - Repeater that displays the matching results in the middle (with a button for each item)
3 - Repeater that displays the selected items on the right
On initial page load the page will show the data bound checkboxes and will show all results (since nothing has been checked in the filters). As the user checks or unchecks the checkboxes, the page will reload and the matching results will change. So far this part works great.
In the Results Repeater, each item has a Button. When the user clicks the button for an item in the Results the idea is that the item will get added to the Selected Repeater on the right. What is happening is that after I check or uncheck filter checkboxes - the first time that I then try and click on the buttons in the Results repeater, nothing happens. The page just reloads. Then if I click the button a second time, the Repeater Command will fire and the item will get added to the Repeater on the right hand side. Then, as long as I don't change any of the checkboxes I can click on one of the command buttons and it will work right away. But if I check one of the checkboxes in the filters area (which causes the Results to get re-bound) then I have to click one of the buttons twice to get it to fire.
I have a sense that this has something to do with ViewState but I have no idea. Does anyone know why this would be happening?
Below is my code for both the ASPX page and the code behind.
ASPX Code:
<h3>Filters</h3>
<asp:Repeater ID="rptTechnologies" runat="server" OnItemDataBound="rptFacet_ItemDataBound">
<HeaderTemplate><h4>Technology</h4></HeaderTemplate>
<ItemTemplate><asp:CheckBox ID="chkFacet" runat="server" AutoPostBack="true" OnCheckedChanged="chkFacet_Changed" /><br /></ItemTemplate>
</asp:Repeater>
<asp:Repeater ID="rptVerticals" runat="server" OnItemDataBound="rptFacet_ItemDataBound">
<HeaderTemplate><h4>Vertical</h4></HeaderTemplate>
<ItemTemplate><asp:CheckBox ID="chkFacet" runat="server" AutoPostBack="true" OnCheckedChanged="chkFacet_Changed" /><br /></ItemTemplate>
</asp:Repeater>
<asp:Repeater ID="rptIndustries" runat="server" OnItemDataBound="rptFacet_ItemDataBound">
<HeaderTemplate><h4>Industry</h4></HeaderTemplate>
<ItemTemplate><asp:CheckBox ID="chkFacet" runat="server" AutoPostBack="true" OnCheckedChanged="chkFacet_Changed" /><br /></ItemTemplate>
</asp:Repeater>
<asp:Repeater ID="rptSolutions" runat="server" OnItemDataBound="rptFacet_ItemDataBound">
<HeaderTemplate><h4>Solution</h4></HeaderTemplate>
<ItemTemplate><asp:CheckBox ID="chkFacet" runat="server" AutoPostBack="true" OnCheckedChanged="chkFacet_Changed" /><br /></ItemTemplate>
</asp:Repeater>
<h3>Results</h3>
<asp:Repeater ID="rptMatchingSlides" runat="server" OnItemDataBound="rptMatchingSlides_ItemDataBound" OnItemCommand="rptMatchingSlides_Command">
<ItemTemplate>
<h4><asp:Literal ID="litName" runat="server"></asp:Literal></h4>
<asp:Button ID="btnSelect" runat="server" Text="Select" CommandName="Select" />
</ItemTemplate>
<SeparatorTemplate><hr /></SeparatorTemplate>
</asp:Repeater>
<h3>Selected</h3>
<asp:Repeater ID="rptSelectedSlides" runat="server" OnItemDataBound="rptSelectedSlides_ItemDataBound">
<ItemTemplate>
<h4><asp:Literal ID="litName" runat="server"></asp:Literal></h4>
</ItemTemplate>
<SeparatorTemplate><hr /></SeparatorTemplate>
</asp:Repeater>
Here is the code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
this.BindData();
}
}
public List<string> SelectedSlides
{
get
{
if (Session["SelectedIDs"] != null)
{
string[] _ids = Session["SelectedIDs"].ToString().Split(new char[] { '|' });
List<String> _retVal = new List<string>();
foreach (string _id in _ids)
{
_retVal.Add(_id);
}
return _retVal;
}
else
{
return new List<string>();
}
}
set
{
//Set the session value
string _val = "";
foreach (string _id in value)
{
if (_val == "")
{
_val = _id;
}
else
{
_val += "|" + _id;
}
}
Session["SelectedIDs"] = _val;
}
}
protected void BindData()
{
//Filters
rptTechnologies.DataSource = Repository.GetTaxonomyItems();
rptTechnologies.DataBind();
rptVerticals.DataSource = Repository.GetTaxonomyItems();
rptVerticals.DataBind();
rptIndustries.DataSource = Repository.GetTaxonomyItems();
rptIndustries.DataBind();
rptSolutions.DataSource = Repository.GetTaxonomyItems();
rptSolutions.DataBind();
this.BindMatchingSlides();
}
protected void BindMatchingSlides()
{
...build list of ids from checkboxes...
rptMatchingSlides.DataSource = Repository.GetMatchingSlides(_selectedIDs);
rptMatchingSlides.DataBind();
}
protected void BindSelectedSlides()
{
if (this.SelectedSlides.Count > 0)
{
rptSelectedSlides.DataSource = this.SelectedSlides;
rptSelectedSlides.DataBind();
}
else
{
divSelectedSlides.Visible = false;
}
}
protected void rptMatchingSlides_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Literal _litName = (Literal)e.Item.FindControl("litName");
Button _btnSelect = (Button)e.Item.FindControl("btnSelect");
_litName.Text = ...set name here...
_btnSelect.CommandArgument = ...use unique ID of item from database...
_btnSelect.ID = "btnSelect_" + e.Item.ItemIndex;
}
}
protected void rptMatchingSlides_Command(object sender, RepeaterCommandEventArgs e)
{
if (e.CommandName == "Select")
{
Item _slide = ...get data from database based on Command Argument...
if (_slide != null)
{
List<string> _selectedSlides = this.SelectedSlides;
_selectedSlides.Add(_slide.ID.ToString());
this.SelectedSlides = _selectedSlides;
}
this.BindSelectedSlides();
}
}
Thanks to Jeremy - removing the line of code where I was setting the ID fixed it. Doh! Somewhere else I had read that you needed to set a unique value for the IDs of the buttons in a repeater. So that must have been the culprit. Thanks to Jeremy.

Loop in code block on click argument

Basically what i am trying to do is display a list of categories. And if the admin is logged in
i want to show some buttons next to each category. For example a button to delete it. The problem is that i dont know how to pass a parameter to the function that does the action.
Like i specify that on button click the function 'DeleteCat' must be called but if i cant pass the ID of the category to be deleted this wont work.
I know this can be done with commands and a repeater, but its not an option, i cant use a repeater.
So apparanly this is what i am aiming for:
But of course it does not work.
<%For Each Cat In Category.Children%>
<p class="SubCategory">
<%=Cat.Name%>
<%If User.Identity.Name = "Admin" Then%>
<asp:LinkButton ID="LinkButton6" runat="server" OnClick="AddItem" Text="A+" CommandArgument=<%=Cat.ID %> />
<%End If%>
</p>
<%Next %>
Your event handler AddItem should be able to evaluate the sender of the event and the CommandEventArgs
void AddItem(Object sender, EventArgs e)
{
int result;
bool returnValue;
Button clickedButton = (Button)sender;
returnValue = Int32.TryParse(clickedButton.CommandArgument, result);
// then other stuff happens ...
}
See detailed example here.
edit
Completed code sample as suggested by Brandon.
Alternative solution, using a CheckBoxList
...
<script language="C#" runat="server">
void Page_Load(Object Sender, EventArgs e)
{
if (!IsPostBack)
{
// bind data to controls
this.itemRepeater.DataSource = Category.Children;
this.adminList.DataSource = Category.Children;
this.itemRepeater.DataBind();
this.adminList.DataBind();
}
// set visibility according to user
this.itemRepeater.Visible = (User.Identity.Name != "Admin");
this.adminList.Visible = (User.Identity.Name == "Admin");
this.adminButton.Visible = (User.Identity.Name == "Admin");
}
protected void AddItem(object sender, EventArgs e)
{
foreach(ListItem currentitem in this.adminList.Items)
{
if(currentitem.Selected)
{
// do something with the selected value
int i;
bool isparsed = Int32.TryParse(currentitem.value, i);
}
}
}
</script>
</head>
<body>
<form id="mainForm" runat="server">
<asp:Repeater ID="itemRepeater" runat="server">
<ItemTemplate>
<p><%# DataBinder.Eval(Container.DataItem, "value") %></p>
</ItemTemplate>
</asp:Repeater>
<asp:CheckBoxList ID="adminList" runat="server" />
<br />
<asp:Button ID="adminButton" OnClick="AddItem" runat="server" Text="Add seleted Items" />
</form>
</body>

Resources