stop refreshing page on button click - c#

I need to make the asp button to not refresh the whole page when I click it.
my code is just to make a picture change to another picture but the index of the picture is set in the page load method. And every time you click the button to go to the next picture index, the whole page refreshes and calls the page load method. That then sets the index back to 0.
how can I make the page stop calling the page load method when I click a button
Here's the basic code I'm using
in a table:
<tr>
<td> <asp:Button ID="Button1" runat="server" Text="Prev" OnClick="Button1_Click" OnClientClick="return false"/> </td>
<td> <img ID="pic" alt="" src="010.JPG" runat="server" width="200" height="200" /> </td>
<td> <asp:Button ID="Button2" runat="server" Text="Next" OnClick="Button2_Click" OnClientClick="return false"/> </td>
</tr>
and this is the .cs file
private List<String> imagePathList = new List<String> { };
private List<Boolean> isActivePath = new List<Boolean> { };
protected void Page_Load(object sender, EventArgs e)
{
Debug.WriteLine("GALLARY *page load*");
pic.Width = 200;
pic.Height = 200;
addToList();
getImagePath(1);
}
protected void Button1_Click(object sender, EventArgs e)
{
Debug.WriteLine("GALLARY *Button1_Click*");
int index = getActive();
getImagePath(index = index - 1);
}
protected void Button2_Click(object sender, EventArgs e)
{
Debug.WriteLine("GALLARY *Button2_Click*");
int index = getActive();
getImagePath(index = index + 1);
}
private void getImagePath(int index)
{
Debug.WriteLine("GALLARY *getImagePath* index = "+index);
int length = imagePathList.Count;
if (index < length && index >= 0)
{
//pic.Src = imagePathList[index];
//pic.Alt = imagePathList[index];
pic.Src = imagePathList[index];
pic.Alt = imagePathList[index];
setActive(index);
}
else
{
pic.Src = "DOES NOT EXIST";
pic.Alt = "DOES NOT EXIST";
}
}
private void addToList()
{
Debug.WriteLine("GALLARY *addToList*");
imagePathList.Clear();
isActivePath.Clear();
addImage("08.JPG");
addImage("09.JPG");
addImage("010.JPG");
addImage("011.JPG");
addImage("012.JPG");
}
private void addImage(String filename)
{
Debug.WriteLine("GALLARY *addImage* filename = "+filename);
imagePathList.Add(filename);
isActivePath.Add(false);
}
private void setActive(int index)
{
Debug.WriteLine("GALLARY *setActive* index = " + index);
for (int i = 0; i > isActivePath.Count; i++)
{
isActivePath[i] = false;
}
isActivePath[index] = true;
}
private int getActive()
{
Debug.Write("GALLARY *getActive*");
int temp = 0;
for (int i = 0; i > isActivePath.Count; i++)
{
if (isActivePath[i] == true)
{
temp = i;
}
}
Debug.WriteLine("index = " + temp);
return temp;
}

You need to use UpdatePanel for Partial Updates.
<asp:ScriptManager runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Always" >
<ContentTemplate>
<asp:Image ID="Image1" runat="server" Height="23px" Width="24px" />
<asp:Button ID="btnImageChange" runat="server" Text="Check" OnClick="btnImageChange_Click1" />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnImageChange" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
Then in code behind .cs write this:
protected void btnImageChange_Click1(object sender, EventArgs e)
{
// you can add a loop here for the list of images...
Image1.ImageUrl = "~/Images/loading.gif";
}

onClientClick="return false"
That should do it! Onclick will refer to an ASP.net function, onClientClick will render as OnClick on the control in HTML.

on button click call this javascript functon
<script type="text/Javascript">
function ChangeIndex(){
$.ajax({
url: "Url of your page/Methodname",
data: JSON.stringify({variableName,VariableValue}),
dataType: 'json',
type: 'POST',
contentType: 'application/json',
success: function (data) {
//set your image scr here
},
error: function (data, status, jqXHR) {
//alert('There was an error.');
}
}
</script>
in your code behind write a webmethod
[WebMethod]
public static string Methodname(string variableName)
{
//Logic to get the index.
return "Index";
}
Hope this helps. Please post your code so that I can help you further.

Try not to implement such old fashion buttons. Instead you can use fly buttons or jQuery triggered button which won't post back.

Related

How Can I retrieve data from TextBox, when it's dynamically added by button?

I'm new to coding, hope some can help me a bit, I got stuck at retrieving data from my Dynamically added Text boxes in ASP.NET.
I Master Site and a Content site. I have added some buttons to the content site there are adding or removing the textboxes, after what's needed by the user.
My problem is, that i'm not sure how to retrieve the data correct. hope some body can help me on the way.
My Content site:
<%# Page Title="" Language="C#" MasterPageFile="~/main.master" AutoEventWireup="true" CodeFile="CreateRMA.aspx.cs" Inherits="CreateRMA" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="mainsite" Runat="Server">
<div id="div_fortext" class="div_fortext">
<p class="header2">
Opret RMA Sag
</p>
<p class="text1">
Her Kan de oprette alt det udstyr der skal sendes til reperation hos zenitel.
</p>
</div>
<div id="div_insert_devices" runat="server">
</div>
// 3 buttons one who add, one who remove textboxes and a submit button
<asp:Button ID="btnAddRow" runat="server" Text="Add Row" CssClass="butten1" OnClick="btnAddRow_Click" />
<asp:Button ID="btnRemoveRow" runat="server" Text="Remove Row" CssClass="butten1" OnClick="btnRemoveRow_Click" />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" CssClass="butten1" OnClick="btnSubmit_Click" />
</asp:Content>
My C# code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class CreateRMA : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
ViewState["DeviceCount"] = ViewState["DeviceCount"] == null ? 1 : ViewState["DeviceCount"];
InsertLine();
}
}
private void InsertLine()
{
int DeviceCount = int.Parse(ViewState["DeviceCount"].ToString());
for (int i = 0; i < DeviceCount; i++)
{
LiteralControl text = new LiteralControl("<div class=\"divPerDevice\">");
div_insert_devices.Controls.Add(text);
TextBox txtbox = new TextBox();
txtbox.ID = "serial" + i;
txtbox.CssClass = "textbox1";
txtbox.Attributes.Add("runat", "Server");
div_insert_devices.Controls.Add(txtbox);
text = new LiteralControl("</div>");
div_insert_devices.Controls.Add(text);
}
}
protected void btnAddRow_Click(object sender, EventArgs e)
{
int count = int.Parse(ViewState["DeviceCount"].ToString());
count++;
ViewState["DeviceCount"] = count;
InsertLine();
}
protected void btnRemoveRow_Click(object sender, EventArgs e)
{
int count = int.Parse(ViewState["DeviceCount"].ToString());
count--;
ViewState["DeviceCount"] = count;
InsertLine();
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
// Submit - save the textboxes to Strings ??? Can any body help
}
}
((TextBox)div_insert_devices.FindControl("txtboxname")).Text
Try this one
you can use the following code
protected void btnSubmit_Click(object sender, EventArgs e)
{
// Submit - save the textboxes to Strings ??? Can any body help
int DeviceCount = int.Parse(ViewState["DeviceCount"].ToString());
for (int i = 0; i < DeviceCount; i++)
{
TextBox txtbx= (TextBox)div_insert_devices.FindControl("serial" + i);
if(txtbx!=null)
{
var value= txtbx.Text;
}
}
}
The way i would attempt this is like the following:
protected void btnSubmit_Click(object sender, EventArgs e)
{
foreach (Control control in div_insert_devices.Controls){
if (control.GetType() == typeof(textbox)){
Textbox myDynTextbox = (Textbox)control;
Var myString = myDynTextbox.Text;
Please note this code can be simplyfied further but, i have written it this was so you understand how it would work, and my advise would be to store all the strings in a collection of Strings, making it easier to maintain.
}
}
}
Kush
Why don't you use javascript to save the value of textbox. just hold the value in some hidden field and bind it everytime when you need it.
Hi I found the solution after some time here... I did not got any of examples to work that you have provided. sorry.
But I almost started from scratch and got this to work precis as I wanted :)
My Content Site:
<%# Page Title="" Language="C#" MasterPageFile="~/main.master" AutoEventWireup="true" CodeFile="CreateRMA.aspx.cs" Inherits="CreateRMA" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="mainsite" Runat="Server">
<div id="div_fortext" class="div_fortext">
<p class="header2">
Opret RMA Sag
</p>
<p class="text1">
Some TEXT
</p>
</div>
</div>
<asp:Button ID="btnAddRow" runat="server" Text="Add Row" CssClass="butten1" OnClick="btnAddRow_Click" />
<asp:Button ID="btnRemoveRow" runat="server" Text="Remove Row" CssClass="butten1" OnClick="btnRemoveRow_Click" />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" CssClass="butten1" OnClick="btnSubmit_Click" />--%>
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:PlaceHolder runat="server" id="DynamicDevices"></asp:PlaceHolder>
<asp:Button id="btnAddTextBox" runat="server" text="Tilføj" CssClass="butten1" OnClick="btnAddTextBox_Click" />
<asp:Button id="btnRemoveTextBox" runat="server" text="Fjern" CssClass="butten1" OnClick="btnRemoveTextBox_Click" />
<asp:Button runat="server" id="Submit" text="Submit" CssClass="butten1" OnClick="Submit_Click" />
<br /><asp:Label runat="server" id="MyLabel"></asp:Label>
</asp:Content>
My C# code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class CreateRMA : System.Web.UI.Page
{
static int myCount = 1;
private TextBox[] dynamicTextBoxes;
private TextBox[] Serial_arr;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
myCount = 1;
}
}
protected void Page_Init(object sender, EventArgs e)
{
Control myControl = GetPostBackControl(this.Page);
if (myControl != null)
{
if (myControl.ID.ToString() == "btnAddTextBox")
{
myCount = myCount >= 30 ? 30 : myCount + 1;
}
if (myControl.ID.ToString() == "btnRemoveTextBox")
{
myCount = myCount <= 1 ? 1 : myCount - 1;
}
}
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
dynamicTextBoxes = new TextBox[myCount];
Serial_arr = new TextBox[myCount];
int i;
for (i = 0; i < myCount; i += 1)
{
LiteralControl literalBreak = new LiteralControl("<div>");
DynamicDevices.Controls.Add(literalBreak);
TextBox Serial = new TextBox();
Serial.ID = "txtSerial" + i.ToString();
Serial.CssClass = "";
DynamicDevices.Controls.Add(Serial);
Serial_arr[i] = Serial;
TextBox textBox = new TextBox();
textBox.ID = "myTextBox" + i.ToString();
DynamicDevices.Controls.Add(textBox);
dynamicTextBoxes[i] = textBox;
literalBreak = new LiteralControl("</div>");
DynamicDevices.Controls.Add(literalBreak);
}
}
public static Control GetPostBackControl(Page thePage)
{
Control mycontrol = null;
string ctrlname = thePage.Request.Params.Get("_EVENTTARGET");
if (((ctrlname != null) & (ctrlname != string.Empty)))
{
mycontrol = thePage.FindControl(ctrlname);
}
else
{
foreach (string item in thePage.Request.Form)
{
Control c = thePage.FindControl(item);
if (((c) is System.Web.UI.WebControls.Button))
{
mycontrol = c;
}
}
}
return mycontrol;
}
protected void Submit_Click(object sender, EventArgs e)
{
int deviceCount = Serial_arr.Count();
DataSet ds = new DataSet();
ds.Tables.Add("Devices");
ds.Tables["Devices"].Columns.Add("Serial", System.Type.GetType("System.String"));
ds.Tables["Devices"].Columns.Add("text", System.Type.GetType("System.String"));
for (int x = 0; x < deviceCount; x++)
{
DataRow dr = ds.Tables["Devices"].NewRow();
dr["Serial"] = Serial_arr[x].Text.ToString();
dr["text"] = dynamicTextBoxes[x].Text.ToString();
ds.Tables["Devices"].Rows.Add(dr);
}
//MyLabel.Text = "der er " + deviceCount +" Devices<br />";
//foreach (TextBox tb in Serial_arr)
//{
// MyLabel.Text += tb.Text + " :: ";
//}
//MyLabel.Text += "<br />";
//foreach (TextBox tb in dynamicTextBoxes)
//{
// MyLabel.Text += tb.Text + " :: ";
//}
}
protected void btnAddTextBox_Click(object sender, EventArgs e)
{
}
protected void btnRemoveTextBox_Click(object sender, EventArgs e)
{
}
}
Thanks For all the help anyway :)
Hope somebody can use this.
Best regards Kasper :)

Add ValidationControls dynamically to updatepanel? [ASP.NET]

I have a problem with my dynamic updatepanel that I've created.
The problem is that i want to add a validator,i.e RequriedFieldValidator, to every element that i'm creating on the serverside.
This above works fine.
But when i'm clicking the submit button it does nothing. I can see in the htmlShellcode that a span element is there showing the error, but it has the "style="visibility=hidden".
How do i solve this issue? i'm not really sure i'm doing it right from the beginning either(very new to programming).
MARKUP:
<asp:Panel ID="UpdatepanelWrapper" CssClass="Updatepanelwrapper" runat="server">
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:PlaceHolder runat="server" ID="WholeWrapper">
<asp:PlaceHolder runat="server" ID="QuestionWrapper">
<asp:PlaceHolder runat="server" ID="LabelQuestion"><asp:PlaceHolder>
<asp:PlaceHolder runat="server" ID="Question"></asp:PlaceHolder>
</asp:PlaceHolder>
</asp:PlaceHolder>
</asp:PlaceHolder>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnAdd" EventName="Click" />
<asp:AsyncPostBackTrigger ControlID="btnDelete" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
<asp:Panel ID="ButtonPanel" CssClass="ButtonPanel" runat="server">
<asp:ImageButton ID="btnDelete" runat="server" ImageUrl="~/Images/Deleteicon.png" CssClass="DeleteButton" OnClientClick="btnDelete_Click" />
<asp:ImageButton ID="btnAdd" runat="server" ImageUrl="~/Images/Addicon.png" CssClass="AddButton" OnClientClick="btnAddQuestion_Click" />
</asp:Panel>
</asp:Panel>
SERVERSIDE CODE: (Override method OnInit is the important one)
public partial class _Default : Page
{
static int CountOfQuestions = 1;
private RequiredFieldValidator[] ArrRequiredFieldQuestion;
private Panel[] ArrWholePanel;
private Panel[] ArrQuestionPanel;
private Label[] ArrQuestionLabel;
private TextBox[] ArrQuestionBox;
protected void Page_Load(object sender, EventArgs e)
{
}
private void LoadControls()
{
Control myControl = GetPostBackControl(this.Page);
if (myControl != null)
{
if (myControl.ID.ToString() == "btnAdd") //Ändra till btnAddQuestion om en "button" ska användas
{
CountOfQuestions++;
}
if (myControl.ID.ToString() == "btnDelete")
{
CountOfQuestions--;
}
}
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
if (!IsPostBack)
{
CountOfQuestions = 1;
}
LoadControls();
ArrRequiredFieldQuestion = new RequiredFieldValidator[CountOfQuestions];
ArrWholePanel = new Panel[CountOfQuestions];
ArrQuestionPanel = new Panel[CountOfQuestions];
ArrQuestionLabel = new Label[CountOfQuestions];
ArrQuestionBox = new TextBox[CountOfQuestions];
for (int i = 0; i < CountOfQuestions; i++)
{
RequiredFieldValidator ReqFieldQuestion = new RequiredFieldValidator();
PlaceHolder WholeWrapper = UpdatePanel1.FindControl("WholeWrapper") as PlaceHolder;
Panel WholePanel = new Panel();
Panel QuestionPanel = new Panel();
Panel CorrectAnswerPanel = new Panel();
Label QuestionLabel = new Label();
TextBox Question = new TextBox();
QuestionLabel.Text = "Write your question";
Question.TextMode = TextBoxMode.MultiLine;
Question.Width = 550;
Question.Height = 50;
WholePanel.ID = "WholePanel" + i.ToString();
QuestionPanel.ID = "QuestionPanel" + i.ToString();
Question.ID = "tbxQuestion" + i.ToString();
ReqFieldQuestion.ID = "Validate" + i.ToString();
ReqFieldQuestion.ControlToValidate = "tbxQuestion" + i.ToString();
ReqFieldQuestion.ValidationGroup = "QuestionGroup";
ReqFieldQuestion.ErrorMessage = "Error";
ReqFieldQuestion.Attributes.Add("runat", "server");
QuestionPanel.CssClass = "QuestionEntry";
QuestionPanel.Controls.Add(QuestionLabel);
QuestionPanel.Controls.Add(Question);
QuestionPanel.Controls.Add(ReqFieldQuestion);
WholeWrapper.Controls.Add(WholePanel);
WholePanel.Controls.Add(QuestionPanel);
ArrRequiredFieldQuestion[i] = ReqFieldQuestion;
ArrQuestionPanel[i] = QuestionPanel;
ArrQuestionLabel[i] = QuestionLabel;
ArrQuestionBox[i] = Question;
}
}
protected void btnAddQuestion_Click(object sender, EventArgs e)
{
//Handeld by Pre_init and LoadControls
}
protected void btnDelete_Click(object sender, EventArgs e)
{
//Handeld by Pre_init and LoadControls
}
public static Control GetPostBackControl(Page thePage)
{
Control postbackControlInstance = null;
if (postbackControlInstance == null)
{
for (int i = 0; i < thePage.Request.Form.Count; i++)
{
if ((thePage.Request.Form.Keys[i].EndsWith(".x")) || (thePage.Request.Form.Keys[i].EndsWith(".y")))
{
postbackControlInstance = thePage.FindControl(thePage.Request.Form.Keys[i].Substring(0, thePage.Request.Form.Keys[i].Length - 2));
return postbackControlInstance;
}
}
}
return postbackControlInstance;
}
But when i'm clicking the submit button it does nothing.
Since I don't see a Submit button, I'm taking a guess that you mean the Add and Remove buttons. If this is the case, the problem is that all your RequiredFieldValidators have the ValidationGroup property set to QuestionGroup but this is not set in any of your buttons.
Modify the Buttons like this:
<asp:ImageButton ID="btnAdd" runat="server" ValidationGroup="QuestionGroup" ... />

Request.Form giving extra values from Dynamic Textboxes

i am working with dynamic TextBoxes and then Getting their Values in code behind file. I am creating these boxes using Javascript. my asp.net page code is
<script type="text/javascript">
$(document).ready(function () {
var counter = 1;
$("#addButton").click(function () {
if (counter > 10) {
alert("Only 10 textboxes allow");
return false;
}
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.html('<input type="text" name="textbox' + counter +
'" id="textbox' + counter + '" value="" >');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
return false;
});
});
</script>
</head>
<body>
<form id="form2" runat="server">
<h1>jQuery add / remove textbox example</h1>
<asp:TextBox runat="server" ID="txt1" type='text' name="textname" />
<asp:Panel runat="server" ID='TextBoxesGroup'>
</asp:Panel>
<asp:LinkButton ID="addButton" runat="server">Add TextBox</asp:LinkButton>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</form>
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
</body>
i have one Textbox shown on the page, which should shows only one values when no dynamic Textbox is created. My C# code is
protected void Button1_Click(object sender, EventArgs e)
{
string name = txt1.Text + ",";
if (TextBoxesGroup.Controls.Count > 0)
{
for (int i = 1; i <= TextBoxesGroup.Controls.Count; i++)
{
name += Request.Form["textbox" + i] + ",";
}
}
Label1.Text = name;
}
on asp:button click it should display all the values separated by (,). but it is only showing top 2 values, one of which is asp:Textbox and second is dynamic Textbox,, i want the values of all the Textboxes created dynamically, and when no dynamic textbox is added it should only show the value from asp:textBox... Thanks in Advance
Html input elements created through javascript on the client, are not going to be in TextBoxesGroup.Controls on the server.
Changes in the client DOM structure have no effect on the Page's Control tree. The only thing affected will be the content of HttpRequest during postback. One way to know how many dynamically created input elements contributed to Request.Form data is to pass this information as part of the request. This is why you will have to go with the hidden field suggestion. The hidden field value will bring back the count of client-side inputs. You have to set it in javascript every time you create a new input, read it in server-side code, convert to integer and use in your for loop.
Add
<asp:HiddenField runat="server" ID="txtDynamicCount" value="0" />
to the the markup inside form tag.
In javascript click event after counter++; line add
$("#txtDynamicCount").val(counter);
In Button1_Click:
int count;
if (!int.TryParse(txtDynamicCount.Value, out count))
count = 0;
for (int i = 1; i <= count; i++)
{
...
}
The important difference from the other answer is that textboxes (input elements) will not persist between form submits.
You cannot populate server controls in client side. Instead, you want to populate them from server. Here is the sample -
<asp:PlaceHolder runat="server" ID="PlaceHolder1"></asp:PlaceHolder>
<asp:LinkButton ID="addButton" runat="server" OnClick="btnAdd_Click">Add TextBox</asp:LinkButton>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" /><br/>
Posted Results: <asp:Label ID="Label1" runat="server" Text=""></asp:Label>
private List<int> _controlIds;
private List<int> ControlIds
{
get
{
if (_controlIds == null)
{
if (ViewState["ControlIds"] != null)
_controlIds = (List<int>)ViewState["ControlIds"];
else
_controlIds = new List<int>();
}
return _controlIds;
}
set { ViewState["ControlIds"] = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
foreach (int id in ControlIds)
{
var textbox = new TextBox();
textbox.ID = id.ToString();
PlaceHolder1.Controls.Add(textbox);
}
}
}
protected void btnAdd_Click(object sender, EventArgs e)
{
var reqs = ControlIds;
int id = ControlIds.Count + 1;
reqs.Add(id);
ControlIds = reqs;
var textbox = new TextBox();
textbox.ID = id.ToString();
PlaceHolder1.Controls.Add(textbox);
}
protected void Button1_Click(object sender, EventArgs e)
{
var ids = ControlIds;
foreach (var id in ids)
{
var textbox = (TextBox)PlaceHolder1.FindControl(id.ToString());
Label1.Text += textbox.Text + ", ";
}
}

Copying items from one <asp:ListBox> to another dynamically

This is our code:
<div>
<table style="width: 349px">
<tr>
<td class="style1">
<asp:ListBox ID="leftbox" runat="server" Height="114px" Width="212px"
SelectionMode="Multiple" AutoPostBack="True">
</asp:ListBox>
</td>
<td>
<asp:Button ID="Button1" runat="server" Text=">>" onclick="Button1_Click" /><br />
<asp:Button ID="Button2" runat="server" Text="<<" onclick="Button2_Click" />
</td>
<td>
<asp:ListBox ID="rightbox" runat="server" Height="117px" Width="231px"
SelectionMode="Multiple" AutoPostBack="True"></asp:ListBox>
</td>
</tr>
</table>
</div>
The code behind is:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<string> list= GetNameList();
leftbox.DataSource = list;
leftbox.DataBind();
}
}
private static List<string> GetNameList()
{
List<string> list = new List<string>();
list.Add("keerthana");
list.Add("sirisha");
list.Add("anusha");
list.Add("Anuradha");
list.Add("Bhavani");
list.Add("divya");
list.Sort();
return list;
}
Please tell me how to add two or more selected items one by one from leftbox to rightbox, without using server-side code (as below):
protected void Button1_Click(object sender, EventArgs e)
{
if (leftbox.SelectedIndex != -1)
{
rightbox.Items.Add(leftbox.SelectedItem.Text);
leftbox.Items.Remove(leftbox.SelectedItem.Text);
}
}
Thanks in advance...
Use client side javascript to do this, so you don't postback every time someone moves something, if you have jquery it can be as easy as:
$("#Button1").button().click(function() {
$("#leftbox option:selected").each(function() {
$("#rightbox").append(this);
});
});
Here is Linq way of get selected items form ListBox
var selectedItems = leftbox.Items.OfType<ListItem>().Where(item => item.Selected).ToList();
then you can add all selected values to rightbox and finally remove from leftbox
EDIT
protected void Button1_Click(object sender, EventArgs e)
{
List<ListItem> selectedItems = new List<ListItem>();
if (leftbox.SelectedIndex >= 0)
{
for (int i = 0; i < leftbox.Items.Count; i++)
{
if (leftbox.Items[i].Selected)
{
selectedItems.Add(leftbox.Items[i]);
}
}
}
for (int i = 0; i < selectedItems.Count; i++)
{
if (!rightbox.Items.Contains(selectedItems[i]))
rightbox.Items.Add(selectedItems[i]);
leftbox.Items.Remove(selectedItems[i]);
}
}
this will do the work
but the problem here is..
after you transfer the item and click save button
it will submit first before your save code will read
all the item you move to Leftbox from Rightbox will go back to Rightbox viseversa
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#left").bind("click", function () {
var options = $("[id*=RIghtBox] option:selected");
for (var i = 0; i < options.length; i++) {
var opt = $(options[i]).clone();
$(options[i]).remove();
$("[id*=LeftBox]").append(opt);
}
});
$("#right").bind("click", function () {
var options = $("[id*=LeftBox] option:selected");
for (var i = 0; i < options.length; i++) {
var opt = $(options[i]).clone();
$(options[i]).remove();
$("[id*=RIghtBox]").append(opt);
}
});
});
</script>

Ajax Timer: Execute only 5 times

I have a ajax Timer control. It adds “+” to the text value of a label. This timer should work only five times with an interval of “1000” – i.e, only five “+” should be available. After that, the lblPostbackType
Should be updated with the count. How do I achieve it?
public partial class _Default : System.Web.UI.Page
{
static int partialPostBackCount = 0;
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
if (ScriptManager.GetCurrent(this).IsInAsyncPostBack)
{
partialPostBackCount = partialPostBackCount + 1;
lblPostbackType.Text = "Partial Postback:: " + partialPostBackCount.ToString();
}
else
{
lblPostbackType.Text = "Full Postback";
}
}
}
protected void Timer1_Tick(object sender, EventArgs e)
{
Label1.Text = Label1.Text + "+";
}
}
And the designer code is
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:Timer runat="server" ID="Timer1" Interval="1000" OnTick="Timer1_Tick" />
<asp:Label runat="server" ID="lblPostbackType" >SAMPLE</asp:Label>
<asp:UpdatePanel runat="server" ID="TimePanel" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />
</Triggers>
<ContentTemplate>
<asp:Label runat="server" ID="Label1" />
</ContentTemplate>
</asp:UpdatePanel>
</form>
Thanks
try this
protected void Timer1_Tick(object sender, EventArgs e)
{
if (partialPostBackCount > 5 )
{
lblPostbackType.Text = "Partial Postback:: " +
partialPostBackCount.ToString();
//Timer1.Enabled = false; //if you don't want it to continue
}
else
{
partialPostBackCount = partialPostBackCount + 1;
Label1.Text = Label1.Text + "+";
}
}
*static variables are not recommended..
keep the Page_Load event method clean..

Categories

Resources