DropDownList Binding items - asp.net

I have DDL in custom control that in the default case I insert new item with certain value.
but in a certain case I insert another item and want to the previous item to be deleted.
I tried to remove the first item and insert the another
I tried to change text and value of the inserted item
the 2 ways failed because:
in the first load of page, it take the value of the first item and text of the second,
then if I select another thing from DDL and then return to my Item, it take its correct value.
I need the second to take the correct value in the first load of the page.

Im not sure what you mean exactly,but let me try to help.
Page Load, the DDL has Item 1 loaded e.g. ItemText:Stack ItemValue:Overflow
Then on some action the above is deleted and a new Item is Inserted?
If so, could you try somthing like,
VB
With me.DDL
'Remove all Items from the DDL
.Items.Clear()
'Insert New Items
.Items.Insert(0, New ListItem("VALUE",TEXT"))
End With
C#
//Remove all Items from the DDL
this.DDL.Items.Clear();
//Insert New Items
this.DDL.Items.Insert(0, new ListItem("VALUE", "TEXT"));

Related

How can i select Datakey value of a grid

How can i select Datakey value of a grid .? I tried but only getting inside selected index changed event.
[In my application there is a grid.In that grid there link buttons.My issue is when i am clicking on link button i want to acceess value in Datakeynames. is there any method to access value in Datakeynames. or is there any other property for grid to keep key values ].Please help
You have your answer at below link
How to get the Command Argument on Row Data bound Event of gridview
Happy coding!!!
Try like this,
Assign your Value in the Command Argument.
In RowCommand Event,
if (e.CommandName == "Link")
{
string Value = e.CommandArgument.ToString();
}

Setting AspxComboBox.SelectedIndex not working after using LinqDataSource.Selecting. Any ideas?

I've posted this on the DevExpress forums as well, but you can't beat stackoverflow for good answers.
I seem to be having a problem with the DevExpress AspxComboBox control.
I'm using DevExpress 9.1.11 controls with Visual Studio 2008.
Here are my controls:
<asp:LinqDataSource ID="ContactsDataSource" runat="server"
ContextTypeName="DAL.MorrisDataContext"
Select="new (Id, FullName)"
TableName="Contact">
</asp:LinqDataSource>
<dxe:ASPxComboBox ID="SignerComboBox" runat="server" ToolTip="Select a Contact to use."
AutoPostBack="True" DataSourceID="ContactsDataSource" TextField="FullName"
ValueField="Id" ValueType="System.String" Width="140px" SelectedIndex="0">
</dxe:ASPxComboBox>
I am handling the Selecting event of the LinqDataSource to filter the list of items used in the ComboBox as follows:
Protected Sub ContactsDataSource_Selecting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.LinqDataSourceSelectEventArgs) Handles ContactsDataSource.Selecting
Dim Contacts As IList(Of Contact) = iEntity.Contacts.ToList
e.Result = Contacts
End Sub
iEntity.Contacts is just a LINQtoSQL object containing a child collection of LINQtoSQL objects known as "Contacts". All of this works perfectly.
The problem comes when I try to add a new Contact to the collection of contacts for the Entity and then try to update the ComboBox to reflect the addition as follows:
Private Sub SignerUpdate()
Dim m_Last = SignerContactLastTextBox.Text
Dim m_First = SignerContactFirstTextBox.Text
If m_Last <> "" OrElse m_First <> "" Then
Dim m_Middle = SignerContactMiddleTextBox.Text
Dim m_Suffix = SignerContactSuffixTextBox.Text
Dim m_ContactIndex As Int32 = SignerComboBox.SelectedIndex
Dim m_Contact As Contact = New Contact
If m_Last <> "" Then m_Contact.LastName = New Identifier With {.Value = m_Last}
If m_First <> "" Then m_Contact.FirstName = New Identifier With {.Value = m_First}
If m_Middle <> "" Then m_Contact.MiddleName = New Identifier With {.Value = m_Middle}
If m_Suffix <> "" Then m_Contact.Suffix = New Identifier With {.Value = m_Suffix}
iEntity.Contacts.Add(m_Contact)
SignerComboBox.DataBind()
SignerComboBox.SelectedIndex = SignerComboBox.Items.Count - 1
'SignerComboBox.SelectedIndex = 3
Else
SignerContactSuffixTextBox.ErrorText = "Must have First or Last name."
SignerContactSuffixTextBox.IsValid = False
End If
End Sub
The key lines being these:
iEntity.Contacts.Add(m_Contact)
SignerComboBox.DataBind()
SignerComboBox.SelectedIndex = SignerComboBox.Items.Count - 1
'SignerComboBox.SelectedIndex = 3
The first line adds a new Contact to the collection.
The second line rebinds the ComboBox which results in the Selecting event from above being fired and getting the updated list including the new contact.
Everything is still working fine. I can put a watch on SignerCombBox.Items and see that the new item is there after the bind. It was not there prior to the bind.
All is good.
Then we come to the third line. This is where we have a problem. I expect this to select the last item in the list of items. The results of SignerComboBox.Items.Count is correct. We get a count back that does include the new item.
What doesn't work, is that when we try to use that result to set the SelectedIndex property. It will not accept it.
The fourth line is where I've tried to do everything manually to make sure I'm not losing my mind. Turns out I'm not. As you can see this line is commented out.
Even though I have added another line to Items and I can see that line in Items. It can not be set as selected using SelectedIndex. When I try to set it, it just remains set to whatever it was set to previously (in my case 0). I've also tried setting it with SignerComboBox.SelectedItem = SignerComboBox.Items(SignerComboBox.Items.Count - 1) or SignerComboBox.SelectedItem = SignerComboBox.Items(3) to no avail.
So, for example. With my test data I start out with 3 items in the collection. 0 - 2 are in Items.
At this point I can set SignerComboBox.SelectedIndex to 0, 1, or 2. It works just fine.
I then add another item.
Rebind to get the updated Items.
Check the Items. They now contain 4 items. 0, 1, 2, and 3
Set SignerComboBox.SelectedIndex = 3. It will not work. It will remain 0. Even though I know that item is in the Items list of the control.
Set SignerComboBox.SelectIndex = 2. Works just fine. It will be set to 2.
It's as if it's deciding whether or not it's a valid index based on something other than it's own Items list.
I even tried inserting the new one higher in the list and using an index that had already existed. Once that had been done though, that index would not be accepted.
I really don't understand it. I'm pretty sure it must be a bug. Even that doesn't make much sense to me though, because it seems like the kind of bug that would have been reported about a million times over already. So my only guess is that perhaps it has something to do with the fact that I'm handling the Selecting event of the DataSource and giving it a custom result. I don't see why that would matter, but I can't see how anything else is the least bit out of the ordinary.
I've been pounding on this problem for a while now and I'm out of ideas. So any help would be greatly appreciated.
Thanks,
Tory
EDIT:
I thought maybe I could phrase the question a bit more succintly.
Here's what it comes down to:
Bind a combobox to a LinqDataSource based on a LinqToSql object that
is related as a child to another LinqToSql object.
Create an instance of the parent object.
Use the LinqDataSource.Selecting event to use the contents of the
parent object instance's child object collection, as the results of
the LinqDataSource in the form of an IList(Of ChildObject).
Show the contents of the ComboBox.
Add a new Child object to the child object collection of the parent
object instance.
Databind the ComboBox again in order to pick up the newly added
member of the collection.
Attempt to set the SelectedIndex of the ComboBox to the index of the
newly created member of it's contents, using something like this:
SignerComboBox.SelectedIndex = SignerComboBox.Items.Count - 1
You will not be able to.
It will show up in the ComboBox.Items list, but you will not be able
to assign it's index to the SelectedIndex property.

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

set label text to total row count of gridview

I'm using a stored procedure in a sql database as the data source for a SqlDataSourceControl on my .aspx page. I'm then using the SqlDataSourceControl as the data source for a gridview on my page. Paging is set to true on the gridview. What i would like to do is set the text of a label to the total number of rows in the gridview. I can use this code
'labelRowCount.Text = GridView2.Rows.Count & " layers found"
to return the number of results per page, but it doesn't give me the total. I've looked in several places and haven't been successful in finding a solution.
You should use the underlying datasource that the gridview is bound to (grid.DataSource). For instance if you have bound the grid to a datatable then just cast the grids datasource into the datatable and the use the rows.count property to get the total record count. Another alternative would be to get a reference to the the grids datasource object before you set it to the grid so you can get the record count directly.
So for example (assuming you are bound to a DataTable)
int count = ((DataTable)grid.DataSource).Rows.Count;
Enjoy!
Put an event handler on "selected" for the SQL DataSource. That event handler has an argument of type SqlDataSourceStatusEventArgs. In there AffectedRows is the row count of the entire data set (not just that shown on the current page). So catch that and write it out to your label:
protected void SqlDataSource_Selected(object sender,SqlDataSourceStatusEventArgs e)
{
if (e.Exception != null)
{
// do something useful, then...
e.ExceptionHandled = true;
}
else
labelRowCount.Text = String.Format("{0} layers found", e.AffectedRows);
}
GridView2.Rows saves only the rows that are visible, so when page-size is 5 you get only 5 records. As Doug suggested you have to set the labelRowCount.Text ondatabound and not on every postback, because on postback - when the datasource is not binded again - the datasource will be nothing. So a good place could be where you bind the grid to the datasource.

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