How do I prevent selectedValue altering when calling tableAdapter's Fill() method? - c#

I have bound my ListBox to some data.
The problem is when I call myTableAdapter.Fill(..) method, SelectedValue changes to whatever is the first item ID in the list. Although "Selected Value" in VS is not bound anywhere (see image).
alt text http://img370.imageshack.us/img370/2548/ss20090108212745qz2.png
How do I prevent this behaviour, please?
Thank you very much for helping.

You shouldn't be binding on each request. If you absolutely have to bind on each request for some reason you have to set SelectedIndex on the ListBox manually. This is because the Fill method first clears the list then creates new list items for the fetched data.

The simplest way I can think of is to change your table adapter fill code to something like this:
string preSelected = myDropDownList.SelectedValue;
myTableAdapter.Fill(myDataTable);
myDropDownList.SelectedValue = preSelected;
You will run into an issue if the item doesn't exist anymore, so you may want to add a condition to check for that.

Related

Add item update listbox

So I have a databound listbox bound to a list produced from my entity:
myListbox.Datasource = myEntity.ToList();
That works fine. My question is, what is the 'correct' way to add a new element to the entity and have it reflected in my listbox?
Currently, I do this:
myEntity.Add(newItem);
myListbox.Datasource = myEntity.ToList();
Surely there is a better way than resetting the datasource each time?
try this, DataBind() will binds a data source to the invoked server control and all its child controls.
myListbox.DataBind()
Please try this:
myListbox.ResetBindings();
See https://msdn.microsoft.com/en-us/library/system.windows.forms.control.resetbindings%28v=vs.110%29.aspx

How to save the drop down list selected index in asp.net?

i want that after clicking a button saves the index i have selected in order to storage that number to my database. My drop-down-list is in a comment below.
The drop-down-list is filled by using a query. And so far what it does, is that after clicking the button it storages the first index (which is 0), even when i want to save another index.
I have done some research, and so far i cannot solve it, hope someone can help me out.
Code for Dropdown list:-
<asp:DropDownList ID="ddlCategory" runat="server" Height="25px" Width="428px" Font-Size="Large"> </asp:DropDownList>
here's how i fill the drop-down-list
ClsUtil clsutil = new ClsUtil();
DataSet ds = clsutilerias.FillDDL(Category);
ddlCategory.DataTextField = ds.Tables[0].Columns["Name"].ToString();
ddlCategory.DataValueField = ds.Tables[0].Columns["Category_ID"].ToString();
ddlCategory.DataSource = ds.Tables[0];
ddlCategory.DataBind();
The DropDownList has properties. You need to set SelectedIndex, SelectedItem or SelectedValue properly (and in the correct event in relation to when you do the binding etcetera).
Edit: Maybe you updated your question, or maybe I misunderstood, but either way it seems now that you don't want to set the SelectedIndexperhaps as much as get the SelectedIndex. Even so, if you read the documentation and look at the examples provided in the links, you should have enough information to know what to do.
Basically, one of the <option> elements in the <select> on the client (the HTML code) will be selected when the data is posted back to the server. If your <asp:DropDownList> is AutoPostBack="True" you can go for a callback in the OnSelectedIndexChanged event, but there are other ways too, with or without auto-post-back. (You don't really need the view state, or even the <asp:DropDownList> at all, but can trigger a POST by submitting the form data in any way that suits your needs or preferences, and then read any values your interested in server-side.)
It seems that you found your solution in checking IsPostback in the Page, and not re-populate the list if the value is true. That's good. If you don't need to data-bind every time you render the page (even after a POST), that's a viable and common solution.
Another option, of course, would be to read the posted data in any event that happens before you do the data-binding. You may also want to handle the value of SelectedIndex to re-select the correct option in your drop-down after having populating it again, if you don't like having ASP.NET doing it for you.
When you are clicking the button, the entire page is refreshing that why you got the first index all the time
The best solution is :
if(IsPostBack == false)
{
//Save your data code here
}
You have other tricky solution which is :
put the dropboxmenu inside an update panel control
While binding datasource to combo, mention DataMember and DataValue property for combo box so that selecting elements from combo you get selectedValue as DataValue.
Well i have solved my problem, my problem was that when i clicked the button, the pageLoad method executed again, and there was where i had the code to fill my drop-down-list. so i just added:
if(!IsPostBack)
{
//here goes the code to fill the Drop down list
}

ComboBox Items Empty but DataSource Full

After binding a list to combobox, its dataSource.Count is 5 but, combobox item count is 0.
how can it be?
I'm used to Web programming and this is in Windows Forms.
So no combo.DataBind(); method exists.
The problem here is, I'm trying to set the selected item programmatically. Since I don't see the combo.Items collection filled, I cannot set the desired item.
Update
A total update is needed I guess:
datasource contains 7 items
when bound to combobox, DisplayMember and ValueMember are appropriately implemented
after databound, through the gui, I can clearly see the 7 items in the combobox
combobox.DataSource.Count = 7 and combobox.Items.Count = 0
So the problem is here; since after databound no items are there in the ItemCollection of combobox; I cannot search for one to match and set the appropriate one.
Here is a image for better understanding (But I'm pretty sure I'm missing sth simple)
After adding ddl.BindingContext = new BindingContext(); before the BindingSource assignment, everything worked fine.
If you'd expand DataSource items in debuger, you'd probably notice that 1st element on list is null. That is why DataSource does not render ComboBox Items. Removing null items from the list should do all the work;
I had the same problem, but in my case it was caused by calling
combobox.Sorted = True
in InitializeComponent. I guess that call initializes Items, which then prevents the assignment to DataSource from updating it (Items).

Why isn't my datagrid updating?

I have an object that has as one of its properties, a List. I want to bind a datagrid to that list, such that when I add objects to the grid, the datagrid updates. I tried:
myDataGrid.DataSource = myObject.MyList;
but when I update the datasource with new rows, the grid doesn't update.
Then I tried:
myDataGrid.DataSource = null;
myDataGrid.DataSource = myObject.MyList;
Calling the above code every time I added an item. This resulted in an error when clicking on the grid (specifically, index -1 has no data, something to do with the datagridview.get_current internally. Happens despite the fact that I'm not clicking the -1st row).
So then I tried:
myDataGrid.DataBindings.Add(new Binding("DataSoruce",myObject,"MyList",false,DataSourceUpdateMode.OnPropertyChanged));
That didn't reflect the updates either, so I added:
myDataGrid.DataBindings[0].ReadValue();
whenever I added an item, but it has no effect either. I feel like I'm circling around a simpler solution to this problem, but I can't seem to find it. Any pro tips?
You seem to already know this, but you want to use a BindingList if at all possible here. Any hamfisted attempt to make a List function like a BindingList is just going to be a lot more pain than simply copying the elements from a List you already have to a BindingList.
If I changed my type from List to BindingList, all the problems go away and the grid autoupdates as expected.

How to remove selected items from ListBox when a DataSource is assigned to it in C#?

How to remove selected items from ListBox when a datasource is assigned to it in C#?
When trying to remove, got error
"Items collection cannot be modified when the DataSource property is set."
But when i try to remove item from datasource (datatable) ,
it thorws error as "datarow is not in current row collection".
Find that item in the DataSource object and remove it, then re-bind the ListBox.
EDIT:
Here's how you delete from a DataTable as your DataSource, regardless of the .NET version.
DataRowView rowView = listBox.SelectedItem as DataRowView;
if (null == rowView)
{
return;
}
dt.Rows.Remove(rowView.Row);
I haven't tried with anything other than WinForms DataGridViews, but I highly recommend BindingListView, which is both faster than DataTables/Views and allows you to bind generic List<T>s as your DataSource.
Alternatively, use a list that implements IBindingList or inherits from BindingList. When objects are added or removed from a Binding List, any controls bound to it are automatically notified of the change and will update themselves accordingly. If you are using BindingList and your class also implements INotifyProperty changed, Any changes to class properties will also be updated automatically in the databinding control. For example, if a column in a datagrid(view) is bound to a property, "Name", and you change "Name" in the datasource, the datagrid will automatically update. If you add a new item to the datasource, the datagrid will update automatically. Binding List also supports notification in the other direction. If a user edits the "Name" field ina datagrid, the bound object will be updated automatically. Going off topic slightly, if you go a little further and impliment "SupportsSortingCore" and the associated methods in BindingList, you can add automatic sorting to your data. Clicking on a columnm header will automatically sort the list and display the header sort direction arrow.
If the ListBox has a datasource assigned, you must remove items from the datasource and then rebind the ListBox
You need to modify the data source rather than the Items collection of the control. Depending on what kind of data source you are binding to, there are going to be different things you have to do so that your UI updates.
The best way is find a collection that fits your needs and implements IBindingList or IBindingListView. Those two interfaces implement even handlers that listen for a CollectionChanged event and update your UI accordingly.
If your collection doesn't support those interfaces, you're going to have to re-bind your data source every time somebody adds/removes an item.
when you get the message "Items collection cannot be modified when the DataSource property is set."
setting the datasource to something else, empty list or null does not help when
the code initializecomponent is not completed.
to avoid that error, one must do the change of datasource or the item list during or after form load.
I know it does not seem to make sense. Hoever, the visual studio designer will generate code in the form designer.cs or vb that will add items to the listbox if any code that changes the items is found before end of initialize components
While Chris Doggett posted a valid solution, I ran into problems while using it. By using that method it was not allowing a subsequent GetChanges(DataRowState.Deleted) to work properly.
To better solve my problem, I only had to change a single line - the last line.
DataRowView rowView = listBox.SelectedItem as DataRowView;
if (null == rowView)
{
return;
}
rowView.Row.Delete();
This allowed my GetChanges call to work properly.
This worked for me
DataTable temp = (DataTable)lstBlocks.DataSource;
temp.Rows.RemoveAt(position);
its vary simple , assign a new blank value to listbox
eg..
Dim ABC As New List(Of String)()
ListBox1.DataSource = ABC
ListBox implementation is bugged, you need to create a new data source instance for the component for it to recognize a change.
Eg:
ActivitiesList.DataSource = _activities;
_activities = new List<Activity>(_activities);
_activities.Remove((Activity)ActivitiesList.SelectedItem);
ActivitiesList.DataSource = _activities;

Categories