I have created a ListView that has editing enabled, the wizard generated the table with the use of textboxes but i require the use of dropdown lists for some options.
I have created the dropdown list
<asp:DropDownList ID="ActionStatusTextBox" runat="server">
<asp:ListItem Value="Ongoing">Ongoing</asp:ListItem>
<asp:ListItem Value="Open">Open</asp:ListItem>
<asp:ListItem Value="Closed">Closed</asp:ListItem>
</asp:DropDownList>
The drop down list generates successfully but doesn't submit and enter itself in the databse.
<%# Bind("ActionStatus") %>'
The above snippet needs to used somewhere in order to bind the data but which parameter does it need attaching to to pass the data?
I've tried everything and its giving me a right headache!
Thanks
Did you try:
<asp:DropDownList .. SelectedValue='<%# Bind("ActionStatus") %>' />
The SelectedValue property doesn't appear, but I believe you can set it this way.
HTH.
What are you attempting to insert into the database? You shouldn't need to bind anything if you add your listitems manually. You could just
string value = ActionStatusTextBox.SelectedValue;
I had the same issue. Check out this thread: Why is employee_id not being inserted into database
The key was in adding a function:
Protected Sub AbsentListView_ItemInserting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewInsertEventArgs) Handles AbsentListView.ItemInserting
e.Values("employee_id") = DirectCast(AbsentListView.InsertItem.FindControl("ExcusedAbsences_employee_idDropDownList2"), DropDownList).SelectedValue
End Sub
Which basically set the value of the dropdown when it needed it, and once i did this, the value was going into the database.
protected void ContactsListView_ItemDataBound(object sender, ListViewItemEventArgs e)
{
//Verify there is an item being edited.
if (ContactsListView.EditIndex >= 0)
{
//Get the item object.
ListViewDataItem dataItem = (ListViewDataItem)e.Item;
// Check for an item in edit mode.
if (dataItem.DisplayIndex == ContactsListView.EditIndex)
{
// Preselect the DropDownList control with the Title value
// for the current item.
// Retrieve the underlying data item. In this example
// the underlying data item is a DataRowView object.
DataRowView rowView = (DataRowView)dataItem.DataItem;
// Retrieve the Title value for the current item.
String title = rowView["Title"].ToString();
// Retrieve the DropDownList control from the current row.
DropDownList list = (DropDownList)dataItem.FindControl("TitlesList");
// Find the ListItem object in the DropDownList control with the
// title value and select the item.
ListItem item = list.Items.FindByText(title);
list.SelectedIndex = list.Items.IndexOf(item);
}
}
}
Related
I am working with C# .NET 4.0
I am trying to get the value of a single selected item in a listbox.
This is how I populate the control:
this.files_lb.DataSource = DataTable object
In my designer, I have specified file_name as the DisplayMember and file_id as the DisplayValue
After selecting an item in the listbox, I tried the following to get the value:
this.files_lb.SelectedValue.ToString()
But all it returns is "System.Data.DataRowView".
At this link : Getting value of selected item in list box as string
someone suggested -
String SelectedItem = listBox1.SelectedItem.Value
However, 'Value' is not an option when I try this.
How can I get the ValueMember value from a single selected item in a listbox?
var text = (listBox1.SelectedItem as DataRowView)["columnName"].ToString();
Replace columnName with the name of the column you want to get data from, which will correspond with a column in your datasource.
Also watch out for nulls if there's no selected item.
It really should be this easy; I have the following in a click event for button to make sure I wasn't over simplifying it in my head:
private void button1_Click(object sender, EventArgs e)
{
string selected = listBox1.GetItemText(listBox1.SelectedValue);
MessageBox.Show(selected);
}
And the result:
Edit
It looks like your issue may be from not setting a property on the control:
Select the ListBox control
Click the little arrow to show the binding / items options
Select Use Data Bound Items
If I deselect that box, I get the exact same behavior you are describing.
var selectedValue = listBoxTopics.SelectedItem;
if (selectedValue != null)
{
MessageBox.Show(listBoxTopics.SelectedValue.ToString());
}
You may need to set the DataValueField of the listbox.
NewEmployeesLB.DataSource = newEmployeesPersons.DataList.Select(np => new
ListItem() { Text = np.LastName + ", " + np.FirstName, Value = np.PersonID.ToString() }).ToList();
NewEmployeesLB.DataTextField = "Text";
NewEmployeesLB.DataValueField = "Value";
NewEmployeesLB.DataBind();
I have an asp.net chckebox list:
<asp:EntityDataSource ID="GradeLevelEntityDataSource" runat="server"
ConnectionString="name=NewCourseRequestDataEntities"
DefaultContainerName="NewCourseRequestDataEntities" EnableFlattening="False"
EntitySetName="grade_levels" OrderBy="it.grade_level_index">
</asp:EntityDataSource>
<asp:CheckBoxList ID="GradeLevelCheckBoxList" runat="server" cssClass="horizontalcontrols"
DataSourceID="GradeLevelEntityDataSource"
DataTextField="grade_level_description" DataValueField="grade_level_id" AutoPostBack="True"
OnSelectedIndexChanged="CollegeInstitutionsListboxChange"
RepeatDirection="Horizontal" RepeatLayout="Flow">
</asp:CheckBoxList>
A user can return to the page, it gets the record ID, pulls the record data, and should check the appropriate checkboxes:
CheckBoxList grades = (CheckBoxList)FindControl("GradeLevelCheckBoxList");
foreach (request_grade_college r in CurrentRequest.request_grade_college)
{
ListItem grade = grades.Items.FindByValue(r.grade_level_id.ToString());
if (grade != null)
{
grade.Selected = true;
}
}
the portion of the code r.grade_level_id.ToString() does return the correct GUID, as type String. However, ListItem grade remain null, so none of the GradeLevelCheckboxList get checked.
What am I missing please?
I think that the data is not yet bound when you try to access it using Items.FindByValue(), try calling
grades.DataBind();
before the foreach loop.
Please make sure the listbox item's Value property has the correct value, if Item's Text and Value are different.
Also, Value Property and grade_level_id are exactly of same case and with trimmed spaces.
I face the following problem when i use RadComboBox :
ddl_contactList.Items.Clear();
ddl_contactList.DataSource = ContactList.GetContactListsByDep(year, main_code);
ddl_contactList.DataTextField = "list_desc";
ddl_contactList.DataValueField = "list_code";
ddl_contactList.DataBind();
ddl_contactList.Items.Insert(0, new Telerik.Web.UI.RadComboBoxItem("NewList", "-1"));
ddl_contactList.SelectedIndex = 0;
<telerik:RadComboBox ID="ddl_contactList" runat="server" AutoPostBack="True" CausesValidation="False"
CollapseDelay="0" Culture="ar-EG" ExpandDelay="0" Filter="StartsWith" ItemsPerRequest="10"
MarkFirstMatch="true" Skin="Outlook" EnableAutomaticLoadOnDemand="True" EmptyMessage="-List name-"
ShowMoreResultsBox="True"
onselectedindexchanged="ddl_contactList_SelectedIndexChanged" AppendDataBoundItems ="true">
</telerik:RadComboBox>
always the number of items in the combo box is 1 !!! although the datasource contains many items so when i try to get the selected value for any item in any time, i always get -1 !!
How to get the correct selectedvalue ?
Add the NewList item before databinding and add the following attribute to RadComboBox.
Setting AppendDataBoundItems to True preserves the items that are already present in RadComboBox. This lets you bind RadComboBox to multiple data sources or use both unbound and bound modes.
Then add the datasource to the control.
ddl_contactList.Items.Clear();
ddl_contactList.Items.Insert(0, new Telerik.Web.UI.RadComboBoxItem("NewList", "-1"));
ddl_contactList.SelectedIndex = 0;
ddl_contactList.DataSource = ContactList.GetContactListsByDep(year, main_code);
ddl_contactList.DataTextField = "list_desc";
ddl_contactList.DataValueField = "list_code";
ddl_contactList.DataBind();
How about adding them individually instead of binding.
var items = ContactList.GetContactListsByDep(year, main_code);
foreach(var item in items)
{
ddl_contactList.Items.Add(new RadComboBoxItem(item.list_desc, item.list_code));
}
ddl_contactList.Items.Insert(0, new RadComboBoxItem("NewList", "-1"));
ddl_contactList.SelectedIndex = 0;
This is a Dropdown control where I am binding the data, after bind I am putting the select statement. Even though the index is kept to 0 always select comes last like this:
Current output:
india
Auz
US
--select--
Required output:
--select--
india
AUZ
US
My Code
ddlcounty.DataSource = dtNew;
ddlcounty.DataTextField = "Weight";
ddlcounty.DataValueField = "Weight";
ddlcounty.DataBind();
ddlcounty.Items.Add("--Select--");
ddlcounty.SelectedValue = "0";
What is the change required here?
Thanks
You're doing your binding first.
When you get to the part where you are adding your default condition, you're actually adding to the end of the list.
Instead of :-
ddlcounty.Items.Add("--Select--");
Do :-
ddlcounty.Items.Insert(0, new ListItem("--Select--"));
This will insert your default option as the first element of Items.
Announced edit
You won't need :-
ddlcounty.SelectedValue = 0;
.. as if you don't explicitly specify, the first item in a drop down list is automatically selected.
If, however, you want to be explicit about it, you can do the following:-
ddlcounty.Items.Insert(0, new ListItem("--Select--","0"));
ddlcounty.SelectedValue = 0;
Would you please try below way:
Just set AppendDataBoundItems to true and Insert a ListItem as selected, and 'ClearSelection' before selecting item as below.
ddlcounty.AppendDataBoundItems = true;
ddlcounty.DataSource = dtNew;
ddlcounty.DataTextField = "Weight";
ddlcounty.DataValueField = "Weight";
ddlcounty.DataBind();
ddlcounty.ClearSelection();
ddlcounty.Items.Insert(0, new ListItem { Value = "0", Text = "--Select--", Selected = true });
ddlcounty.SelectedValue = "0";
You could also declare the "select one" ListItem declaratively in your aspx page like so
<asp:DropDownList ID="ddUIC" runat="server" AppendDataBoundItems="true" Width="200px" BackColor="White" Font-Size="10px" SelectedValue='<%# Bind("Weight") %>' DataTextField="Weight" DataValueField="Weight" >
<asp:ListItem Text="Select One" Value=""></asp:ListItem>
/asp:DropDownList>
But your AppendDataBoundItems would have to be set to true
And you could still perform your databinding on the backend.
I have a basic DropDownList bound to a ObjectDataSource:
<asp:DropDownList ID="DropDownList1" runat="server"
AutoPostBack="True" DataSourceID="objDataSource1"
DataTextField="FieldName" DataValueField="FieldID" />
The DataTable from which it receives the DataTextField and DataValueField values also returns some other interesting information about the records. Say Active = Y/N for simplicity's sake.
What I'd like to do is to set the background-color property of the DropDownList Item based on that Active field in the DataSource results. Further, I'd like to do this "in the same pass" as when the DropDownList is bound to the data. So my guess is that it has to happen during OnDataBound.
Things I already know/tried:
I could go back and loop through the DropDownList items later. But it would involve embedding loops and re-visiting the DataTable rows and it just seems inefficient
int row;
for (row = 0; row < DropDownList1.Items.Count - 1; row++)
{
[[if this row = that data row]]
DropDownList1.Items[row].[[DoStuffHere, etc.]]
}
We already do stuff like this with the GridView OnRowDataBound event, by accessing the GridViewRowEventArgs e. What I seem to be missing is an OnDropDownListItemBound event, so to speak.
Hope I've been clear and concise. Seems as though it should be easy...
You can't do it during OnDataBinding because the data has not actually been bound yet. Your best shot is (1), that is, use OnDataBound and loop through the items.
protected void DropDownList1_DataBound(object sender, EventArgs e)
{
foreach(ListItem myItem in DropDownList1.Items)
{
//Do some things to determine the color of the item
//Set the item background-color like so:
myItem.Attributes.Add("style","background-color:#111111");
}
}
I am using This code and it's working fine with me:
DropDownList1.Items(0).Attributes.CssStyle.Add("color", "Blue");
DropDownList1.Items(0).Attributes.CssStyle.Add("background-color", "#eae9e9");