ListBox SelectedIndex always -1 in slectedindexchanged event handler - c#

In the sample code there are two listboxes. In ListBox1 the items are defined in Default.aspx. In ListBox2 they are defined in the codefile. ListBox1 behaves as expected, the text box is updated whenever an item is selected. When ListBox2 triggers an event the selectedindex is always -1.
Default.aspx:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ListBox ID="ListBox1" runat="server" OnSelectedIndexChanged="lb1_OnSelectedIndexChanged" AutoPostBack="true">
<asp:ListItem>a</asp:ListItem>
<asp:ListItem>b</asp:ListItem>
</asp:ListBox>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:ListBox ID="ListBox2" runat="server" OnSelectedIndexChanged="lb1_OnSelectedIndexChanged" AutoPostBack="true">
</asp:ListBox>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</div>
</form>
</body>
</html>
Default.aspx.cs:
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
List<string> ab = new List<string>();
ab.Add("a");
ab.Add("b");
ListBox2.DataSource = ab;
ListBox2.DataBind();
ListBox1.SelectedIndexChanged += new EventHandler(lb1_OnSelectedIndexChanged);
ListBox2.SelectedIndexChanged += new EventHandler(lb2_OnSelectedIndexChanged);
}
protected void lb1_OnSelectedIndexChanged(object sender, EventArgs e)
{
if (ListBox1.SelectedIndex != -1)
{
TextBox1.Text = ListBox1.SelectedItem.Text;
}
}
protected void lb2_OnSelectedIndexChanged(object sender, EventArgs e)
{
if (ListBox2.SelectedIndex != -1)
{
TextBox2.Text = ListBox2.SelectedItem.Text;
}
}
}
The list of items has been moved to Default.aspx to get it working, but I'd really like to know what I'm doing wrong with this. -- Thanks!

You can't databind ListBox2 on every page load. Try:
Page_Load()...
{
if(!IsPostBack)
{
//databind listbox2
}
}
Try reading up a bit on the ASP.NET page lifecycle. On the postback, the ListBox2 will have it's correct state due to viewstate.
Your current code resets it. Hence the -1.

Related

Invalid postback or callback argument. AutoPostBack is set and also !Page.IsPostBack in Page_Load

Im getting the following error when I click on any item in my ListBox:
Invalid postback or callback argument. Event validation is enabled
using in configuration or <%#
Page EnableEventValidation="true" %> in a page. For security
purposes, this feature verifies that arguments to postback or callback
events originate from the server control that originally rendered
them. If the data is valid and expected, use the
ClientScriptManager.RegisterForEventValidation method in order to
register the postback or callback data for validation.
However, I've set AutoPostBack="True" in my ListBox and also in my DropDownList:
<%# Page Language="C#" EnableEventValidation="false" AutoEventWireup="true" CodeBehind="Form1.aspx.cs" Inherits="WebApplication1.Form1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="dropDown" runat="server" AutoPostBack="True" Height="19px" Width="226px">
</asp:DropDownList>
</div>
<asp:ListBox ID="ListBox1" runat="server" AutoPostBack="True" Height="349px" Width="501px" OnSelectedIndexChanged="ListBox1_SelectedIndexChanged" ></asp:ListBox>
<br />
</form>
</body>
</html>
and I've set if (!Page.IsPostBack) in my .cs code:
using System;
using System.Collections.Generic;
using System.Web.UI;
namespace WebApplication1
{
public partial class Form1 : System.Web.UI.Page
{
public ServiceReference1.WebService1SoapClient client= new ServiceReference1.WebService1SoapClient();
public localhost.WebService1 asd = new localhost.WebService1();
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
List<string> igralci = new List<string>();
foreach (localhost.Igralec ig in asd.vrniVseIgralce())
{
igralci.Add(ig.id + ", " + ig.ime + ", " + ig.priimek + ", " + ig.letoRojstva + "\n");
}
ListBox1.DataSource = igralci;
ListBox1.DataBind();
List<string> klubi = new List<string>();
klubi.Add("Vsi klubi");
foreach (localhost.Klub ig in asd.vrniVseKlube())
{
klubi.Add(ig.naziv);
}
dropDown.DataSource = klubi;
dropDown.DataBind();
}
}
protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string script = "alert(\"Hello!\");";
ScriptManager.RegisterStartupScript(this, GetType(),
"ServerControlScript", script, true);
}
}
}
Anyone know how to get rid of the error?
The error it self says you need to add "<%# Page EnableEventValidation="true" %> " in page, like below :-
" <%# Page Language="C#" AutoEventWireup="false" EnableEventValidation="false" CodeBehind="Form1.aspx.cs" Inherits="WebApplication1.Form1" %>"
and the error gets sorted out.

DropdownList Linked to a Textbox

I am trying to display the selectedIndex of my dropdownlist in the textBox (field number 2) and in my ajax htmlEditor (field number 3). I already can show field number 1 on my dropdown, but I cant seem to show anything on the other boxes, all I get are errors :(, implying that the dataSource has not any items which is weird. Here are my classes.
Messages.aspx
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Messages.aspx.cs" Inherits="ASF.HC.JobApplication.Admin.Messages" %>
<%# Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="ajaxToolkit" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>Messages</h2>
<asp:ScriptManager ID="ScriptManager2" runat="server"></asp:ScriptManager>
<legend>Pick the template to use:</legend>
<asp:dropdownlist id ="ddlTemplate" runat ="server" Height="38px" Width="397px">
<asp:listitem value ="1"> Juan Valdez </asp:listitem >
<asp:listitem Value ="2"> Querido bebe</asp:listitem>
</asp:dropdownlist >
<p> </p>
<asp:TextBox ID="textDos" AutoPostBack="true" runat="server" MaxLength="40"></asp:TextBox>
<ajaxToolkit:HtmlEditorExtender ID="textoTemplate" runat="server" TargetControlID="txtDetails"
EnableSanitization="false" DisplaySourceTab="true" >
</ajaxToolkit:HtmlEditorExtender>
</asp:Content>
Message.aspx.cs
public partial class Messages : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
loadList();
}
public void loadList()
{
try
{
BO.Messages template = new BO.Messages();
ddlTemplate.DataSource = template.GetAll();
ddlTemplate.DataValueField = "Title";
DataSet ds = new DataSet("Templates");
ddlTemplate.DataSource = ds;
ddlTemplate.DataBind();
ddlTemplate.SelectedIndexChanged += DdlTemplate_SelectedIndexChanged;
textDos.Text = ds.Tables[0].Rows[0]["id"].ToString();
} catch (Exception e)
{
}
}
private void DdlTemplate_SelectedIndexChanged(object sender, EventArgs e)
{
//when we change the dropdownlist we need to get the student id and set it to the textbox
DropDownList mydropdownlist = sender as DropDownList;
textDos.Text = mydropdownlist.SelectedValue;
}
}
Been checking this error all day long, with no plausible answer and can not detect what am I doing wrong.
Thanks for your assistance.

How to add DoubleClick Event To List Box

I have a asp Listbox Control as
<asp:ListBox ID="lstBox" runat="server" CssClass="listBox"></asp:ListBox>
I want to add a doubleclick event to the Listbox I want a popup. I have googled it and haven't found any of my requirement.
Is there any event that captures the DoubleClick event. If not any alternatives to achieve this.
By the way I want to do it everything on the server side and I'm doing it in WebForm
Well use a hidden input field here to indentify when ever the listbox was clicked:
<%# 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);
}
}
</script>
<html>
<head>
<title></title>
<script lang="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 id="Form1" runat="server">
<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" />
</form>
You can add double click event on page load to listbox and can detect double click on page load as below code.
<asp:ListBox ID="lstitem" runat="server"></asp:ListBox>
page load
protected void Page_Load(object sender, EventArgs e)
{
if (Request["__EVENTARGUMENT"] != null && Request["__EVENTARGUMENT"] == "lstdbclick")
{
//your popup code here
}
lstitem.Attributes.Add("ondblclick", ClientScript.GetPostBackEventReference(lstitem, "lstdbclick"));
}

FileUpload Null reference error

I want to use FileUpload Control to save Image to Database. The HasFiles return always false after I click on BtnSave. I tried with and without UpdatePanel but could not find the solution.
My code is:
protected void BtnSave_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile == true)
{
var ChNumber = txtNumber.Text;
string img = this.FileUpload1.PostedFile.FileName;
//Save image to database function
}
else
{
lblStatus.Text="Image not Uploaded";
}
}
Try with a simple form without UpdatePanel. Here's the markup:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="BtnSave" runat="server" Text="Button" OnClick="BtnSave_Click" />
<asp:TextBox ID="txtNumber" runat="server"></asp:TextBox>
<asp:Label ID="lblStatus" runat="server" Text="Label"></asp:Label>
</div>
</form>
</body>
</html>
And here's the code:
using System;
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void BtnSave_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile == true)
{
var ChNumber = txtNumber.Text;
string img = this.FileUpload1.PostedFile.FileName;
//Save image to database function
}
else
{
lblStatus.Text = "Image not Uploaded";
}
}
}
I set a brekapoint at if (FileUpload1.HasFile == true) and see the uploaded file is there.

Dynamically created textbox values losses when i click the button

I have created a TextBox dynamically, and i am getting the value of the textbox when i click the button. But the value entered in the dynamic textbox gets empty when i click the button.
Below is my ASPX Code:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="Reports.WebForm1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<asp:DropDownList ID="DropDownList1" runat="server"
onselectedindexchanged="DropDownList1_SelectedIndexChanged" AutoPostBack = "true">
<asp:ListItem>Text</asp:ListItem>
<asp:ListItem>Check</asp:ListItem>
</asp:DropDownList>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="GetTextBoxValue" />
</form>
</body>
</html>
CodeBehind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Reports
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
TextBox TB = new TextBox();
TB.ID = "abc";
form1.Controls.Add(TB);
Response.Write(Request.Form["abc"]);
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
createcontrol();
}
protected void createcontrol()
{
if (DropDownList1.SelectedValue.ToLower().Trim() == "text")
{
TextBox TB = new TextBox();
TB.ID = "abc";
form1.Controls.Add(TB);
}
}
}
}
When you use dynamic controls in .NET and want their values to be accessible after postback you need to create them within the Page_Init method of the page. In essence its not working because ViewState has already been set by the time you created the controls. See this guide for detailed info on this topic https://web.archive.org/web/20211020131055/https://www.4guysfromrolla.com/articles/081402-1.aspx . To fix the problem elevate your Textbox instantiation code to the Page_Init method and all should be well.

Categories

Resources