Get attribute from DropdownList SelectedItem - asp.net

I have a dropdownlist where I need to store more data than the standard list item allows. The approach I've taken is to add an attribute to each of the listitems.
I monitor for changes and can return the SelectedIndex, but I'm not sure how to get the attribute back from there, or whether there are any easier ways of achieving this.
Any ideas?

Try this:
ddl.SelectedItem.Attributes["key"];

I did try this once before and i figured i could not really use the attribute's on the DropDownList attributes.
What i did was the following:
Create a list containing a KeyValuePair. The Key in the KeyValuePair is the same ID as you put in your DropDownList Item.
The value of the KeyValuePair, is the value (or values) that you would like to keep/connect with your item.
You can store the List in your viewState and read the data once you have selected an item in your DropDownList and find the right KeyValuePair using the ID.
So you can "store" the data like this:
var listKeyValuePair = new List<KeyValuePair<int, string>>();
listKeyValuePair.Add(new KeyValuePair<int, string>(1, "data"));
ViewState["DataList"] = listKeyValuePair;
And you can get your data like this:
var listKeyValuePair = (List<KeyValuePair<int, string>>)ViewState["DataList"];
var dataILikeToHave = listKeyValuePair.Find(k => k.Key == Convert.ToInt16(dropDownlist.SelectedItem.Value));

Related

ASP.NET DropDownList OnItemDataBound

Is there a method on a <asp:DropDownList> that is equivalent to the OnItemDataBound on Repeaters?
The reason is I want to check each value before putting it in the drop down list.
Nothing similar to OnItemDataBound which will give you an item context.There are events like OnDataBound which will get triggered when it reaches binding.
Your reason for asking this event is for enriching the row instead to filterout, which would not have helped you even with this event.
The best option to solve your question
The reason is I want to check each value before putting it in the drop
down list.
is to do some thing like the following pseudo code
this.YourDropDownList.Items.Clear();
var lst = new List<ListItem>();
var yourCollection= <YOURCollection after Apply Linq Conditions check>
foreach (var obj in yourCollection)
{ //loop and add
this.YourDropDownList.Items.Add(new ListItem {Text = obj.Prop1, Value = obj.prop2});
}

How Can I Duplicate A Item/Record?

(Deleted my old question to simplify it. )
I enter data in a table, I then want to make an exact duplicate of that data in a new item/record/row*.
*not sure the proper term.
Is there any way to accomplish this?
Sorry for the slow response. Here is what you should do:
Add a "copy" button in the row. In the onClick on that button, add this code:
var createDataSource = widget.datasource.modes.create;
var rowDataSource = widget.datasource;
createDataSource.item.foo = rowDataSource.item.foo;
createDataSource.item.bar = rowDataSource.item.bar;
// And so on for each field
createDataSource.createItem();
You could probably make sure of javascript for-in to loop through all the properties of the item in so you don't have to manually specify each record, but I didn't have time to experiment with this.
Edit:
The above code won't show the copied record in the list immediately, because I used row's create data source, instead of the lists create data source. Try this instead:
var rowDataSource = widget.datasource;
// Instead of using the row datasource for create, explicitly use the data source of your list.
var listDatasource = app.datasources.NameOfYourListsDataSource;
var createDataSource = listDatasource.modes.create;
createDataSource.item.foo = rowDataSource.item.foo;
createDataSource.item.bar = rowDataSource.item.bar;
// And so on for each field
createDataSource.createItem();

Bind null value to a dropdown list

I am using items from sharepoint list to be binded to a dropdown list. However, I want the first value in the dropdown to be empty. I cannot insert a null value in the sharepoint list item.
Please let me know how can I do it programmatically.
Below is the code I am using to bind the list to dropdownlist
if (Fldname.Contains("xxxxxx"))
{
ddllist.DataSource = data.getCode();
ddllist.DataTextField = "Title";
ddllist.DataValueField = "Alphabetic_x0020_Code";
ddllist.DataBind();
ddllist.SelectedValue = string.Empty;
ddllist.Width = 120;
}
there has to be something like this. Where 0 is the position you want the new item be - which is the first in this case. Can do this after the databinding.
ddllist.Items.Insert(0 , string.empty);

DataBind of DropDownList works, but does not show in code behind

I'm working on web pages that have an ASP DropDownList defined, and on page load the data source is bound to it through DataSource.DataBind(). When I step through the code, the drop down list does not show anything in it, but when the page actually displays, it does have items in the list. When exactly does DataBind() get applied to the control?
The problem is that some of the values returned by the SQL back end have a null Text, so nothing is displayed in the drop down list for that row. I want to just use the Value as the Text, but only if the Text is null. And when I put the code to loop through and do that right after the DataBind(), there is nothing in the drop down list at that point in the code.
Thanks!
The best option for your specific example is to do what kd7 said, and modify your query. However, if you ever need to do other modifications to the items, you can access them in the DataBound event of the DropDownList. MSDN. This event fires after the binding occurs.
You could
a) Modify your database query to exclude null values
or
b) Before you databind, iterate through the data returned and remove the undesired values.
You can just use LINQ on the data before you assign it to create a new type on the fly with the data arranged how you want. Here is a quick example:
// This simulates the data you get from the DB
List<SomeObject> lstData = new List<SomeObject>();
lstData.Add(new SomeObject() { ID = "1", Text = "One" });
lstData.Add(new SomeObject() { ID = "2", Text = "" });
lstData.Add(new SomeObject() { ID = "3", Text = "Three" });
// This will take your data and create a new version of it substituting the
// ID field into the Text field when the Text is null or empty.
yourDropDownList.DataSource = lstData.Select(i => new {
ID = i.ID,
Text = string.IsNullOrEmpty(i.Text) ? i.ID : i.Text }).ToList();
// Then just databind
yourDropDownList.DataBind();
The DropDownList would have the following items:
One
2
Three

ASP.NET Dynamic Data setting the default value of a Dropdown list

I have a dropdown list (FK) which I would like to set and display a default value based on a login userid. Can you please tell me how to do it? I only want to affect the dropdown filter that appear at the top above the Gridview.
Thanks
Nikos
If you only want this functionality in the DropDown list that appears in the Filter Criteria section, just modify the URL by adding the QueryString parameters you would like to filter by. The DynamicFilter will pick up the values from the QueryString and set the DropDown lists accordingly. (fyi. this is the same functionality that the ForeignKey.ascx FieldTemplate provides)
It would be nice if there was a better way to actually create this URL (instead of using string), but as of right now, any solution I provide is probably going to break in a subsequent version.
example (in page_load)
Response.Redirect("~/Employees/List.aspx?ReportsTo=1234");
Is this a universal change, or just for one foreign key relationship?
Assuming it is for just one foreign key relationship, you could create a new FieldTemplate, to be used just for that relationship. The New FieldTemplate would be a copy of the default "ForeignKey" FieldTemplate. In the New FieldTemplate modify the OnDataBinding (or Page_PreRender) event to set the "default value" of the DropDownList.
Then, to force the New FieldTemplate to be used for that relationship, you would need to use the System.ComponentModel.DataAnnotations.UIHint attribute on the member of your Entity Class that represents that foreign key relationship. (links below)
http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.uihintattribute.uihint.aspx
or http://www.asp.net/learn/3.5-SP1/video-291.aspx (around 07:30 mins)
For a little help, you could take a look at the DynamicData Futures release on CodePlex. Specifically the "Populate Insert templates with values from filters" section. http://www.codeplex.com/aspnet/Release/ProjectReleases.aspx?ReleaseId=14475
I have figured out a workaround, but am open to a more elegant solution.
I edited the FilterUserControl.ascx.cs by inserting the following line in the Page_Init after PopulateListControl(DropDownList1);
DropDownList1.SelectedIndex = DropDownList1.Items.IndexOf(DropDownList1.Items.FindByText("Bob")); // Username is hardcoded just for test
This seems to work but I would prefer using the custom Partial Entity Class with metadata to solve this if possible.
I have solved this in an application I am working on, in your insert view template code behind:
In ItemCreated event for the details view:
foreach (DetailsViewRow row in DetailsView1.Rows)
{
foreach (Control ctl in row.Controls)
foreach (Control c in ctl.Controls)
foreach (Control x in c.Controls)
{
if (x.ClientID.Contains("tblName"))
{
foreach (Control y in x.Controls)
{
if (y.ClientID.Contains("DropDownList"))
{
ddl = y as DropDownList;
ddl.SelectedValue = Convert.ToString(UserId);
ddl.Enabled = false;
}
}
}
}
}
With this code, when a user is logged in and they go to insert some entity (tblName) the drop down list (fk to userId) is already selected and disabled.

Resources