I am loading a ListBox OnSelectedChange of DropDownlist. If I select a 3rd value from the ListBox, it always returns 0. What could be wrong? I appreciate any help. Thank you. Here is my code.
<asp:DropDownList ID="dropdown1" runat="server" Width="300" OnSelectedIndexChanged="onChange"
AutoPostBack="true">
<asp:ListBox ID="list1" runat="server" Width="300" Rows="12" CausesValidation="true"/>
protected void OnChange(object sender, EventArgs e)
{
LoadListBox();
}
void LoadListBox()
{
list1.Items.Clear();
System.Data.DataTable rows = new System.Data.DataTable();
rows = DAL.GetValues();
foreach (System.Data.DataRow row1 in rows.Rows) {
list1.Items.Add(new ListItem(row1["measurement"].ToString().Trim(), row1["measurement"].ToString()));
}
}
when you change the listbox value to three this will fire the onchange event
In your onchange event you should could check the value to see what the value has changed to.
in your code you are reloading the list of values in the onchanged event which will reset the selected value back to zero.
Related
I am trying to store the text of the currently selected item of an Asp:Listbox in a variable. The value is always stored a null, or I receive the error
"System.NullReferenceException: 'Object reference not set to an instance of an object.'"
Listbox declaration below
<asp:ListBox ID="lbModules" runat="server" AutoPostBack="true" OnSelectedIndexChanged="lbModules_SelectedIndexChanged" ></asp:ListBox>
Code for SelectedIndexChanged below
`
protected void lbModules_SelectedIndexChanged(object sender, EventArgs e)
{
string code = lbModules.SelectedItem.Text;
int week = 1;
UpdateTextBox(week, code);
}
`
The listbox is being populated elsewhere with a method looping and adding values with listbox.items.add
I have tried
listbox.SelectedItem.Text, listbox.SelectedValue.Text, listbox.SelectedItem.Value, listbox.SelectedValue.Value,
Nothing I try returns the text of the selected value, always throws an exception or returns null.
Ok, first up, it does not make much sense to use the selected index change event UNLESS you have a autopostback=true.
So, if the user is to enter some info into text box etc., then the user say hits your submit button, then I not really sure of any value of using the selected index change event. But, with autopost-back it does.
hence, this markup:
<h2>Select Hotels</h2>
<asp:ListBox ID="ListBox1" runat="server" AutoPostBack="true"
DataValueField="ID"
DataTextField="HotelName"
OnSelectedIndexChanged="ListBox1_SelectedIndexChanged"
Width="190px" Height="160px" >
</asp:ListBox>
<h3>Selected value</h3>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
And code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadData();
}
void LoadData()
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
string strSQL =
"SELECT ID,HotelName FROM tblHotelsA ORDER BY HotelName";
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
conn.Open();
DataTable rstData = new DataTable();
rstData.Load(cmdSQL.ExecuteReader());
ListBox1.DataSource = rstData;
ListBox1.DataBind();
}
}
}
protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (ListBox1.SelectedIndex >= 0)
{
TextBox1.Text = ListBox1.SelectedItem.Value;
TextBox2.Text = ListBox1.SelectedItem.Text;
}
}
Note VERY but BEYOND careful that we ONLY load the listbox ONE time. Since for any event trigger on a page, the on-load event fires first, and THEN you code stub for the given button or event. Thus, if you load up the lb, or grid or in fact "any" data, but fail to include the all important if !IsPostBack code stub?
Then you cannot actually build a working web page!!! (so, my last 200+ web pages I have built ALL have and ALWAYS have that real first page load, since as noted, the on-load event triggers always on post-backs. So, if you load up the lb or anything again, it will blow out and overwrite your selections you have made).
So, above results in this:
However, if user is to enter data, select things, and THEN hit a submit button, then of course you probably would remove the autopostback = true. And place the above code behind the button click, and NOT use the selected index change event.
Even if you add items to the lb with code, the above rules still apply.
So, say this listbox:
<h2>Select Hotels</h2>
<asp:ListBox ID="ListBox1" runat="server" AutoPostBack="true"
OnSelectedIndexChanged="ListBox1_SelectedIndexChanged"
Width="190px" Height="160px" >
</asp:ListBox>
<h3>Selected value</h3>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
We still need the autopostback, and thus this code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadData();
}
void LoadData()
{
for (int i = 1; i <= 6; i++)
{
string MyText = "Item # " + i;
ListBox1.Items.Add(new ListItem(MyText, i.ToString()));
}
}
protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (ListBox1.SelectedIndex >= 0)
{
TextBox1.Text = ListBox1.SelectedItem.Value;
TextBox2.Text = ListBox1.SelectedItem.Text;
}
}
And now we get/see this:
So, either you are missing autopostback, or you are re-running your code to fill the lb each time on post-back, and that will as noted blow out any selecting the user makes.
I have multiple dropdowns like this
<asp:DropDownList ID="ddl1"
runat="server"
DataTextField="Text"
DataValueField="ValID"
AutoPostBack="true"
OnSelectedIndexChanged="ddl_SelectedIndexChanged">
</asp:DropDownList>
<asp:DropDownList ID="ddl2"
runat="server"
DataTextField="Text"
DataValueField="ValID"
AutoPostBack="true"
OnSelectedIndexChanged="ddl_SelectedIndexChanged">
</asp:DropDownList>
Both the dropdowns has different set of values they are unique. I did the following on ddl_SelectedIndexChanged funtion
DropDownList ddl = sender as DropDownList;
string selectedId = ddl.ID;
string selectedText = ddl.SelectedItem.Text;
When I select values on the first dropdown I get correct selectedId and selectedText.
My Problem:
When I select the second dropdown the selectedId is of the second dropdown but selectedText is always the first dropdowns first value and it never changes. I need selectedText to be that of the Item which I select in the second dropdown.
Any Suggestion?
When binding the data to the DropDownLists, you must place them inside an IsPostBack check.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ddl1.DataSource = source;
ddl1.DataBind();
ddl2.DataSource = source;
ddl2.DataBind();
}
}
If you do not the SelectedIndexChanged will fire each time for the DropDownList because rebinding data will trigger that since the previous selecedindex is overwritten.
i am using radio button list control in asp.net.
i m trying to get selected value on button click Event
but,i m getting Empty string and i want it without javascript.
How can i do this?
<asp:RadioButtonList ID="RadioButtonList1" EnableViewState="true" runat="server"
Width="287px">
<asp:ListItem Value="Single" runat="server" Text="Single"></asp:ListItem>
<asp:ListItem Value="Jointly" runat="server" Text="Married Filing Jointly/Widower"></asp:ListItem>
<asp:ListItem Value="Separately" runat="server" Text="Married Filing Separately"></asp:ListItem>
<asp:ListItem Value="Household" runat="server" Text="Head Of Household "></asp:ListItem>
</asp:RadioButtonList>
C# code
protected void btnCalculate_Click(object sender, EventArgs e)
{
string selectedValue = RadioButtonList1.SelectedValue;
}
When you bind your RadioButtonList, you can place your code in ! IsPostback , in order to don't erase your `selected value, when you post your control (click event).
Page_Load :
if(! isPostBack)
{
//Bind your radioButtonList
}`
Nota : You persist your datas with ViewState
first check your postback event in your page_load..then you can use RadioButtonList1.SelectedValue
Or You could use :--
string selectedValue = RadioButtonList1.SelectedValue.ToString();
Remarks from MSDN for RadioButttonList SelectedValue
This property returns the Value property of the selected ListItem. The
SelectedValue property is commonly used to determine the value of the
selected item in the list control. If multiple items are selected, the
value of the selected item with the lowest index is returned. If no
item is selected, an empty string ("") is returned.
So suggest #1 is that you atleast make on the item as default selection by using the attribute Selected="true"
Suggestion #2 will be (just a opinion) for the sake of readability use SelectedItem.Value
protected void btnCalculate_Click(object sender, EventArgs e)
{
string selectedValue = RadioButtonList1.SelectedItem.Value;
}
I created my gridview with checkboxes inside of it with this code.
<asp:GridView ID="GridView1" runat="server" Width="366px" autogeneratecolumn="false">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="SelectAllCheckBox" runat="server" AutoPostBack="true" oncheckedchanged="SelectAllCheckBox_OnCheckedChanged" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="EachCheckBox" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I tried check/uncheck it.
enter link description here
protected void SelectAllCheckBox_OnCheckedChanged(object sender, EventArgs e)
{
String test = "test";
test = "newtest";
GridView1.DataSource = null;
GridView1.DataBind();
}
But it doesn't trigger any event.
enter link description here
I'm trying to find where my code is missing and searched so far but still can't.
Thank you for your help!
You must use OnItemCreated or OnItemDataBound and link your checkbox with your delegate
void Item_Created(Object sender, DataGridItemEventArgs e)
{
CheckBox cbx = (CheckBox)e.Item.FindControl("SelectAllCheckBox");
cbx.CheckedChanged += SelectAllCheckBox_OnCheckedChanged;
}
The code looks fine and works for me.
I suspect you might be binding the GridView on every postback.
When you click the CheckBox with the event attached it causes the page to refresh. If you bind the CheckBox on Page_Load (or any method that occurs on every trip to the server) it will bind the grid every time you click the CheckBox. In this case it will never get as far as firing your event.
If so, try checking for a postback before binding your GridView.
For example:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Gridview1.DataSource = myDataSource;
GridView1.DataBind();
}
}
I have a ListView setup with LinqDataSource and a button that triggers search function. To avoid display data on page_load, I set ListView's DataSourceID in the Click event of the search button, bind it and set result data in LinqDataSource's Selecting event. It works as I expected but It does't look pretty to set DataSourceId in the button Click event every time the search button is clicked. How can I do this in a better and clearer way?
ASPX code:
<asp:LinqDataSource ID="LinqDataSource1" runat="server"
ContextTypeName="WebApplication1.DataClasses1DataContext" EntityTypeName=""
TableName="Persons" onselecting="LinqDataSource1_Selecting">
</asp:LinqDataSource>
<asp:ListView ID="ListView1" runat="server" >...</asp:ListView>
<asp:Button ID="Search" Text="Search" runat="server" Click="Search_Clicked"/>
ASPX.CS code:
protected void Search_Clicked(object sender, EventArgs e)
{
ListView1.DataSourceID = LinqDataSource1.ID;
ListView1.DataBind();
}
protected void LinqDataSource1_Selecting(object sender, LinqDataSourceSelectEventArgs e)
{
//Search Criteria from CheckBoxList and TextBox applied here.
DataClasses1DataContext data = new DataClasses1DataContext();
var query = from result in data.Persons
where result.ID > 2
select result;
e.Result = query;
}
I honestly don't see anything wrong with your approach, however, if you don't like it, an alternate approach would be to just statically set the DataSourceID in your ListView markup as usual, but set Visible="False", and only make it visible once the button has been clicked.