Loop in code block on click argument - asp.net

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>

Related

Data binding along with the value in ASP.NET

How do you achive something like below in asp.net?
<asp:Label runat="server" Text="The '<%# CustomValue %>' you assigned."/>
This usually depends on where your Label resides. If it is a stond alone control, not nested inside a repeater, you just set your code in code behind:
Label1.Text = $"The {CustomValue} you assigned.";
If the label is nested inside an ItemTemplate in some sort of Repeater control, you can strongly type it to an objects property:
<asp:Repeater runat="server" ID="MyRepeater" ItemType="WebFormsSandbox.Person">
<ItemTemplate>
<li>
<%#: Item.FirstName %> <%#: Item.LastName %>
</li>
</ItemTemplate>
</asp:Repeater>
and the corresponding code behind:
protected void Page_Load(object sender, EventArgs e)
{
MyRepeater.DataSource = Persons();
MyRepeater.DataBind();
}
IEnumerable<Person> Persons()
{
for (int i = 0; i < 10; i++)
{
yield return new Person { Id= i, FirstName = $"Foo{i}", LastName = $"Bar{i}" };
}
}
This would create a list of links, where you then could do anything with it. Whether this would pop up a custom window or does a postback .. up to you.
If you really want to do it that way, write the string inside the server tags.
<asp:Label runat="server" Text='<%# "The " + CustomValue + " you assigned." %>'/>
However if the Label is not inside a GridView, Repeater etc you have to call DataBind manually.
protected void Page_Load(object sender, EventArgs e)
{
DataBind();
}
You would typically do this in the code behind on page load, unless you were using a datagrid or repeater control. Assign an ID to your control and reference it like so.
<asp:Label runat="server" ID="Label1" />
protected void Page_Load(object sender,EventArgs e)
{
Label1.Text = "Your Value";
}

ASP.NET DropDownList SelectedIndexChanged event not working

I have a basic drop down list. Upon selection of an item in the list, I expect to update the label with the choice of drop down list. But my code section does not show any update. Here is the code:
MainPage.aspx.cs:
protected void Page_Load(Object sender, EventArgs e)
{
if (!this.IsPostBack)
{
// Use integers to index each item. Each item is a string.
Dictionary<int, string> fruit = new Dictionary<int, string>();
fruit.Add(1, "Kiwi");
fruit.Add(2, "Pear");
fruit.Add(3, "Mango");
fruit.Add(4, "Blueberry");
fruit.Add(5, "Apricot");
fruit.Add(6, "Banana");
fruit.Add(7, "Peach");
fruit.Add(8, "Plum");
// Define the binding for the list controls.
benimDropDownList.DataSource = fruit;
// Choose what you want to display in the list.
benimDropDownList.DataTextField = "Value";
// Activate the binding.
this.DataBind();
}
}
protected void benimDropDownList_SelectedIndexChanged(object sender, EventArgs e)
{
lblSonuc.Text = "You picked: " + benimDropDownList.SelectedItem.Text;
lblSonuc.Text += " which has the key: " + benimDropDownList.SelectedItem.Value;
}
MainPage.aspx:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="benimDropDownList" runat="server" OnSelectedIndexChanged="benimDropDownList_SelectedIndexChanged">
</asp:DropDownList>
<asp:Label ID="lblSonuc" runat="server"></asp:Label>
</div>
</form>
</body>
</html>
What is wrong with it?
Add AutoPostBack="true" to the <asp:DropDownList>:
<asp:DropDownList ID="benimDropDownList" runat="server"
OnSelectedIndexChanged="benimDropDownList_SelectedIndexChanged" AutoPostBack="true">
</asp:DropDownList>
By default <asp:DropDownList> do not post back changes to the server.
You might also want to set the DataValueField for your dropdownlist:
benimDropDownList.DataValueField = "Key";

Why isn't my code-behind working properly?

Here's my code-behind file for a web form. I can't get certain arguments to work properly with my form.
protected void btn_Submit_Click(object sender, EventArgs e)
{//Enter arguments here...
}
protected void btn_Clear_Click(object sender, EventArgs e)
{
Response.Redirect("~/ContentRequest/BMC_PR_Event.aspx", true);
}
protected void ShowForm()
{
Open.Visible = true;
Success.Visible = false;
Failure.Visible = false;
}
protected void ShowSuccess()
{
Open.Visible = false;
Success.Visible = true;
Failure.Visible = false;
}
protected void ShowFailure()
{
Open.Visible = false;
Success.Visible = false;
Failure.Visible = true;
}
}
Here's the code I'm trying to get it to work with...
<asp:Button TabIndex="12" Text="Submit Request" ID="Button1" CssClass="submit" OnClientClick="return validateForm();" runat="server" onclick="btn_Submit_Click"></asp:Button>
<asp:Button TabIndex="13" Text="Clear Fields" ID="Button2" CssClass="clear" UseSubmitBehavior="false" runat="server" onclick="btn_Clear_Click"></asp:Button>
<asp:Label ID="Label1" runat="server"></asp:Label>
</div>
</asp:Panel>
<asp:Panel ID="Success" Visible="false" runat="server">
<div class="message"><p>Your submission was sucessful.</p><p>An email receipt has been sent to the address provided with the details of this request.</p><p>Thank you.</p></div>
</asp:Panel>
<asp:Panel ID="Failure" Visible="false" runat="server">
<div class="message">
<p>There was an error with your request. If this persists, please report your trouble to _OHE Web Strategies.</p>
Not sure what else I can do here...
--Edit--
This is the error I get...
From the code you have pasted, i cannot see a Panel control with the ID 'Open'. Please do one of the following.
If you need another Panel for the 'open' functionality, add another asp:Panel with the is 'Open'
If you have removed the Open panel once you had, remove the code (from code behind in your case) related to that.
Best of luck
James

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;
}

How to add Double Click mouse event to listbox?

I would like to add a double click mouse event to a listbox. When I double click an item I'd like to get the specific item and assign a method.
I have been searching for tuturials in this field, but tried but somehow wasn't working.
Thank you for helping !
This code works for me
protected void Page_Load(object sender, EventArgs e)
{
if (Request["__EVENTARGUMENT"] != null && Request["__EVENTARGUMENT"] == "event 1")
{
// code for the event
}
ListBox1.Attributes.Add("ondblclick", ClientScript.GetPostBackEventReference(ListBox1, "event 1"));
}
<%# Page Language="C#" %>
<script runat="server">
void Page_Load(Object sender, EventArgs e){
if(Request.Params["ListBox1Hidden"] != null
&& (string)Request.Params["ListBox1Hidden"] == "doubleclicked" {
//This means It was double click
Response.Write("Double Click was fired selected item is "
+ ListBox1.SelectedItem.Text);
}
}
void Button1_Click(object sender, EventArgs e) {
Response.Write("Button was clicked");
}
</script>
<html>
<head>
<script language="javascript">
function ListBox1_DoubleClick() {
/* we will change value of this hidden field so
that in
page load event we can identify event.
*/
document.forms[0].ListBox1Hidden.value = "doubleclicked";
document.forms[0].submit();
}
</script>
</head>
<body>
<form runat="server">
<div>Double click on Listbox
<br />
<asp:ListBox id="ListBox1"
ondblclick="ListBox1_DoubleClick()" runat="server">
<asp:ListItem Value="1">One</asp:ListItem>
<asp:ListItem Value="2">Two</asp:ListItem>
<asp:ListItem Value="3">Three</asp:ListItem>
<asp:ListItem Value="4">Four</asp:ListItem>
</asp:ListBox>
<input type="hidden" name="ListBox1Hidden" />
</div>
<div>click on button
<br />
<asp:Button id="Button1" onclick="Button1_Click"
runat="server" Text="Button"/>
</div>
</form>
</body>
</html>
Simple sample to send selected item on a listbox:
private void listBox1_MouseDoubleClick(object sender, MouseEventArgs e)
{
string test = listBox1.SelectedItem.ToString();
}

Resources