Populating a list box with text AND value, ASP.Net - asp.net

I am wanting to know if there is a way to populate a list box with both text and value. The text bit is easy, but I want a value so I can have a user select something in it then press a button which gets the chosen value and uses an SQL query to do the rest.
My code so far for populating the text is:
listAllLessons.Items.Add(detail);
It runs in a loop and is populated from a database.
Thanks

You can do this in Web Forms:
HTML Side:
<asp:DropDownList ID="ddlList"
runat="server" />
<br />
<asp:Button ID="btnSubmit"
runat="server"
OnClick="btnSubmit_Click"
Text="Click Me" />
Code Behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Generate 20 items
foreach(var count in Enumerable.Range(1, 20))
{
var newItem = new ListItem();
newItem.Value = count.ToString();
newItem.Text = "Item " + count.ToString();
ddlList.Items.Add(newItem);
}
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
//Gets the selected value
var selectedValue = ddlList.SelectedValue;
System.Diagnostics.Debugger.Break();
}

Have you tried concatenating the items just like this:
while (reader.Read())
{
ListBox1.Items.Add(reader[0].ToString() + "\t" + reader[1].ToString());
}

Please try this:
while (reader.Read())
{
ListItem li = new ListItem(Convert.ToString(reader["test"]), Convert.ToString(reader["value"]));
ListBox1.Items.Add(li);
}

This worked for me.
dt = db.GetAllEmployeeForManagement();
foreach (DataRow item in dt.Rows)
{
ListItem li = new ListItem(Convert.ToString(item["Name"]), Convert.ToString(item["EmployeeID"]));
if (!ListBox1.Items.Equals(li.Text))
{
ListBox1.Items.Add(li);
}
}
where dt is actually a ref name of Datasource so.. it is quite simple!

Related

CheckedItems.Count Always Returns a Value of Zero (0)

I have Use telerik:radcombobox with mutiple select value.I have bind data LoadOndemand.All Work Fine but when i click on submit button then CheckedItems.Count=0.
Thank you,
Dhiren Patel
I believe you are using EnableLoadOnDemand property of the RadComboBox. RadComboBox items are not accessible on the server-side when loading them on demand and therefore always return CheckedItems as well as SelectedItems count as zero and this is a known issue. This is because RadComboBox items loaded on demand using the ItemsRequested event handler or WebService do not exist on the server and cannot be accessed using the server-side FindItemByText / Value methods. SelectedItem and SelectedIndex properties are always Null / Nothing. This is needed for speed (otherwise the combobox will not be that responsive upon each keypress if state information and ViewState were persisted).
Please have a look at the following code without using load on demand which works fine at my end.
<telerik:RadComboBox runat="server" ID="RadComboBox1" CheckBoxes="true">
</telerik:RadComboBox>
<br />
<br />
<telerik:RadButton ID="RadButton1" runat="server" Text="Get Count" OnClick="RadButton1_Click">
</telerik:RadButton>
Code Behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
populateRadCombobox("select ContactName from Customers");
}
}
protected void populateRadCombobox(string query)
{
String ConnString =
ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(ConnString);
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = new SqlCommand(query, conn);
DataTable myDataTable = new DataTable();
conn.Open();
try
{
adapter.Fill(myDataTable);
RadComboBox1.DataTextField = "ContactName";
RadComboBox1.DataSource = myDataTable;
RadComboBox1.DataBind();
}
finally
{
conn.Close();
}
}
protected void RadButton1_Click(object sender, EventArgs e)
{
if (RadComboBox1.CheckedItems.Count > 0)
{
//business logic goes here
}
else
{
}
Reference:
http://www.telerik.com/forums/checkeditems-count-always-returns-a-value-of-zero-0
http://www.telerik.com/forums/radcombobox-losing-client-selections-on-postback

Cannot get the selected value of combobox in asp.net

I created a dropdown combobox in asp.net. Here it is:
<asp:ComboBox ID="dropdown_course3" runat="server" AutoPostBack="False"
DropDownStyle="DropDownList"
AutoCompleteMode="Suggest" CaseSensitive="False"
ItemInsertLocation="Append">
</asp:ComboBox>
Then i have a button in my page, and when i click it, i want to get the value of selected item in combobox. The button causes postback. Here is my code:
protected void button_conflict_check_button_Click(object sender, EventArgs e)
{
string dr3 = dropdown_course3.Text;
}
But this returns an empty string even though it should not be empty. Also, i tried selectedItem and it returns null. Can anyone help me with this?
And also, here is how i fill the combobox:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DataTable subjects = new DataTable();
CommonFunctions.con.ConnectionString = CommonFunctions.getConnectionString();
CommonFunctions.con.Open();
try
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT [crn], [subj], [numb], [section] FROM Courses", CommonFunctions.con);
adapter.Fill(subjects);
foreach (DataRow dr in subjects.Rows)
{
string displayVal = dr["subj"].ToString() + " " + dr["numb"].ToString() + " " + dr["section"].ToString();
dropdown_course1.Items.Add(new ListItem(displayVal));
dropdown_course2.Items.Add(new ListItem(displayVal));
dropdown_course3.Items.Add(new ListItem(displayVal));
}
}
catch (Exception ex)
{
// Handle the error
}
// Add the initial item - you can add this even if the options from the
// db were not successfully loaded
CommonFunctions.con.Close();
}
}
Thanks
I have found the problem, since i fill the combobox at page load and inside if(!Page.IsPostBack) block, the button causes postback and combobox seems to be empty.

ASP:Dropdownlist onselectedindexchanges function does not fire even when I set autopostback to true

I am using a wizard. and in step two the user can add information about a location that will be stored. He can add as many locations as he likes.
In step three I want to enter more information about the specific location.
To select which location to use I have ASP:dropdownlist that I populate when user enters stuff.
I want to change index but it just does not work It never goes into the function when I tried debugging. I am using a label to debug.
When I change the selected item the page reloads and the first item in the dropdown list is always selected even though I selected something else. I do not understand why that happens
here is what I have
ASPX File
Select location to enter data for:
<asp:DropDownList ID="s3_location_list" runat="server" AutoPostBack="true" OnSelectedIndexChanged="stepThree_location_list_SelectedIndexChanged">
</asp:DropDownList>
Current location index:
<asp:Label ID="Label3" runat="server" Text="Label"></asp:Label>
CS files
/*This is where I add data to the drop down list
protected void stepTwo_addLocationData(object Sender, System.EventArgs e)
{
//initialize a temporary string array to get all the data from the form
//Console.Write("AAAAA"+ Context.Items["IsRefreshed"]);
Boolean refreshed = (Boolean)Context.Items["IsRefreshed"];
if (!refreshed)
{
//if user is adding a new entry to the location table
LocationData new_location = new LocationData();
//add stuff to locationData
if (stepTwo_locationTableIndex == -1)
{
//add the new_location element into the location_data array
location_data.Add(new_location);
//redraw the table
DataRow dr = dt.NewRow();
dr["Location"] = new_location.City;
//dr["Name"] = loc;
dt.Rows.Add(dr);
}
else
{
location_data[stepTwo_locationTableIndex] = new_location;
dt.Rows[stepTwo_locationTableIndex]["Location"] = City.Text;
}
GridView1.DataSource = dt.DefaultView;
GridView1.DataBind();
///CreateTable();
stepFive_setLocationListOptions();
stepThree_setLocationListOptions();
stepTwo_resetForm();
}
/*this is the page load on step 3
protected void stepThree_load()
{
if (!IsPostBack && Session["s_s3_locationDropdownIndex"] == null)
{
stepThree_locationDropdownIndex = s3_location_list.SelectedIndex;
Session["s_s3_locationDropdownIndex"] = stepThree_locationDropdownIndex;
}
else
{
stepThree_locationDropdownIndex = (int) Session["s_s3_locationDropdownIndex"];
}
s3_location_list.SelectedIndex = stepThree_locationDropdownIndex;
Label3.Text = "" + s3_location_list.SelectedIndex;
}
/*this is my where I populate the list
protected void stepThree_setLocationListOptions()
{
s3_location_list.Items.Clear();
int i = 0;
foreach (LocationData item in location_data)
{
s3_location_list.Items.Add(new ListItem(item.City, "" + i));
}
s3_location_list.DataBind();
}
/* this is the function thats callled when selected index is changed.
protected void stepThree_location_list_SelectedIndexChanged(object sender, EventArgs e)
{
Label3.Text = "Hello";
}
I think the problem is the order of execution. You should only initialize a DropDownList once, otherwise it will overwrite your SelectedIndex. For example, use the OnInit event:
<asp:DropDownList ID="s3_location_list"
runat="server"
OnInit="s3_location_list_Init"/>
And write the event method like this:
protected void s3_location_list_Init(object sender, EventArgs e)
if (!IsPostBack) {
foreach (LocationData item in location_data)
{
s3_location_list.Items.Add(new ListItem(item.City, "" + i));
}
s3_location_list.DataBind();
}
}

Radio button doesn't get selected after a post back

I have an item template within repeater:
<ItemTemplate>
<li>
<input type="radio"
value="<%# GetAssetId((Guid) (Container.DataItem)) %>"
name="AssetId"
<%# SelectAsset((Guid) Container.DataItem) %> />
</li>
</ItemTemplate>
I have a method that compares ids and decides whether to check the radio button.
protected string SelectAsset(Guid uniqueId)
{
if (uniqueId == GetSomeId())
return "checked=\"checked\"";
return string.Empty;
}
SelectAsset gets hit, but it doesn't select a radio button on a post back, but it does work if I just refresh the page. What am I doing wrong here?
Answer here: How to display "selected radio button" after refresh? says that it's not possible to achieve, is this really the case?
Thank you
Update
It appears that view state isn't available for simple controls if they don't have a runat attribute. I have solved this by using a custom GroupRadioButton control. Thank you for your help.
I'd suggest using a RadioButtonList:
Page Code
<asp:RadioButtonList RepeatLayout="UnorderedList" OnSelectedIndexChanged="IndexChanged" AutoPostBack="true" ID="RadioRepeater" runat="server" />
<asp:Label ID="SelectedRadioLabel" runat="server" />
Code Behind
if (!Page.IsPostBack)
{
/* example adds items manually
- you could iterate your datasource here as well */
this.RadioRepeater.Items.Add(new ListItem("Foo"));
this.RadioRepeater.Items.Add(new ListItem("Bar"));
this.RadioRepeater.Items.Add(new ListItem("Baz"));
this.RadioRepeater.SelectedIndex = this.RadioRepeater.Items.IndexOf(new ListItem("Bar"));
this.RadioRepeater.DataBind();
}
protected void IndexChanged(object sender, EventArgs e)
{
this.SelectedRadioLabel.Text = string.Format("Selected Item Text: {0}", this.RadioRepeater.SelectedItem.Text);
}
I assume you only need to select one item.
As described in the comments, it even works to access the SelectedItem in the Page_Loadevent handler:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// previous code omitted
}
else
{
string foo = this.RadioRepeater.SelectedItem.Text;
}
}
If you are creating all your controls dynamically at run-time (directly from code), then things are a little different. Here is the code that I used:
Page Code
<form id="form1" runat="server">
</form>
Code Behind
protected void Page_Load(object sender, EventArgs e)
{
RadioButtonList rbl = new RadioButtonList();
rbl.AutoPostBack = true;
rbl.SelectedIndexChanged += rbl_SelectedIndexChanged;
rbl.Items.Add("All");
// generate your dynamic radio buttons here
for (int i = 0; i<5; i++)
{
rbl.Items.Add(string.Format("Dynamic{0}", i));
}
form1.Controls.Add(rbl);
if (!Page.IsPostBack)
{
rbl.SelectedValue = "All";
PopulateTextBox(rbl.SelectedValue);
}
}
void rbl_SelectedIndexChanged(object sender, EventArgs e)
{
RadioButtonList foo = (RadioButtonList)sender;
PopulateTextBox(foo.SelectedValue);
}
void PopulateTextBox(string selection)
{
TextBox box = new TextBox();
box.Text = selection;
form1.Controls.Add(box);
}

Maintain selected item in DropDownList inside GridView after removing some ListItems

I have a GridView with a DropDownList in each row. (The items in the DropDownList are the same for each.) I have a DropDownList "ddlView" outside of the GridView that is used for filtering the available options in the other DropDownLists. The default selection for ddlView is no filter.
When a user selects a new value for ddlView any selected values in the other DropDownLists disappear if they are not one of the values present after the filter is applied. What I would like to happen in that case is the previously selected value still be present and selected.
What is the best way to accomplish this?
The previously selected values are available during postback but appear to be cleared once DataBind() is called on the GridView, so I am unable to determine their previous value in the method where they are populated (the RowDataBound event).
My best idea so far is to manually store that information into an object or collection during postback and reference it later during the databinding events.
Is there a better way?
I don't think there is a better way to accomplish this as when the GridView is bound all of the controls are recreated thus removing the selections.
The following works: (I store the selections on postback to retrieve again in the RowDataBound event)
Markup
<asp:Button ID="button1" runat="server" Text="Post Back" OnClick="button1_Click" />
<br />
<asp:GridView ID="gridView1" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:DropDownList ID="gridViewDropDownList" runat="server">
<asp:ListItem Value="1">Item 1</asp:ListItem>
<asp:ListItem Value="2">Item 2</asp:ListItem>
<asp:ListItem Value="3">Item 3</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code
public class GridViewDropDownSelections
{
public int RowIndex { get; set; }
public int SelectedIndex { get; set; }
}
...
private List<GridViewDropDownSelections> selectedDropDownListItems = new List<GridViewDropDownSelections>();
protected override void OnLoad(EventArgs e)
{
var selections = gridView1.Rows.Cast<GridViewRow>().Where(r => r.RowType == DataControlRowType.DataRow)
.Select(r => new GridViewDropDownSelections() { RowIndex = r.RowIndex, SelectedIndex = ((DropDownList)r.FindControl("gridViewDropDownList")).SelectedIndex }).ToList();
selectedDropDownListItems.AddRange(selections);
gridView1.RowDataBound += new GridViewRowEventHandler(gridView1_RowDataBound);
if (!IsPostBack)
{
BindDataGrid();
}
base.OnLoad(e);
}
protected void button1_Click(object sender, EventArgs e)
{
BindDataGrid();
}
private void BindDataGrid()
{
//Dummy data
string[] data = new string[] { "Item 1", "Item 2", "Item 3" };
gridView1.DataSource = data;
gridView1.DataBind();
}
void gridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var selection = selectedDropDownListItems.FirstOrDefault(i => i.RowIndex == e.Row.RowIndex);
if (selection != null)
{
try
{
DropDownList gridViewDropDownList = (DropDownList)e.Row.FindControl("gridViewDropDownList");
gridViewDropDownList.SelectedIndex = selection.SelectedIndex;
}
catch (Exception)
{
}
}
}
}
Hope it helps.
Instead of using DataBinding to apply the filter, you could add/remove the DropdownList items through the Items property, when another filter is selected. This way the selected value in the dropdowns should not be resetted.
You might be able to accomplish this with a simple condition. I don't know how you're filtering the items, but it would go something like this:
for (int itemIndex = 0; itemIndex < DropDownList1.Items.Count; itemIndex++)
{
ListItem item = DropDownList1.Items[itemIndex];
if (DropDownList1.Items.IndexOf(item) > ddlView.SelectedIndex)
{
if (!item.Selected)
{
DropDownList1.Items.Remove(item);
}
}
}
Not sure if this is what you're looking for, but hope it helps.
Use client side javascript
Search for all the appropriate select inputs and for each one found, go through the options and remove the one selected in the master ddl
function UpdateDropDowns (tbl) {
var controls = tbl.getElementsByTagName('select');
for (var i = 0; i < controls.length; i++) {
RemoveOption(controls[i], 'the value to remove');
}
}
function RemoveOption(ddl, val)
{
for (var i = ddl.options.length; i>=0; i--) {
if (ddl.options[i].value == val) {
ddl.remove(i);
}
}
}

Resources