Why selected index change on adding data source? - c#

Whenever we add data source to combobox with code below.
comboBoxBusNo.DataSource = busNo.Tables[0];
comboBoxBusNo.DisplayMember = "BusId";
comboBoxBusNo.ValueMember = "Id";
Why private void comboBoxBusNo_SelectedIndexChanged(object sender, EventArgs e) event is called. How we can stop this to be called at loading.

When you bind a list to a ComboBox, the first item is selected by default, which sets the SelectedIndex to 0. There are no items prior to binding so no item is selected, thus the SelectedIndex is -1 to begin with. The SelectedIndex changes from -1 to 0 so the SelectedIndexChanged event is raised.

This will stop the event from firing on load.
comboBoxBusNo.SelectedIndexChanged -= comboBoxBusNo_SelectedIndexChanged;
comboBoxBusNo.DataSource = busNo.Tables[0];
comboBoxBusNo.DisplayMember = "BusId";
comboBoxBusNo.ValueMember = "Id";
comboBoxBusNo.SelectedIndexChanged += comboBoxBusNo_SelectedIndexChanged;

Related

DataBound combobox selected index - 1 issue

I am having issue with resetting my databound combobox to cmb.SelectedIndex = -1
Basically as per the title, the combo box is bound to a datasource and I have a reset button click event which sets the combox box selected index to -1. Main aim is to set the resultant to null.
However when I click the reset button it goes to the first item and then I have to click the button again which then sets the index to -1. So it seems like it goes to selectedIndex 1 and then -1? I am confused?
Here is the code
public SetupBindings()
{
cmb.DataBindings.Add(nameof(ComboBox.SelectedValue), DataSource,
nameof(DataSource.ID), true, DataSourceUpdateMode.OnPropertyChanged);
}
public void Reset_Click(object sender, EventArgs e)
{
cmb.SelectedIndex = -1;
}

ComboBox.Items.IndexOf returns -1

I have a ComboBox which is populated on Page Load event. Just after populating the ComboBox I call another method which returns a value that I want to make the default value of the ComboBox when Page loads. How can I change the selectedIndex to a value that is returned when I call another method?
XAML for ComboBox
<ComboBox Name="cboProductType" DisplayMemberPath="ProductTypeName" SelectedValuePath="ProductTypeID" SelectedIndex="0"/>
Page Load event:
void OnProductDetailLoad(object sender, RoutedEventArgs e)
{
GetServiceReference.Service1Client service = new GetServiceReference.Service1Client();
service.GetProductDetailsCompleted += service_GetProductDetailsCompleted;
service.GetProductTypeCompleted += service_GetProductTypeCompleted;
service.GetProductTypeAsync();
service.GetProductDetailsAsync(ProductId);
}
Populating ComboBox when Page Loads:
void service_GetProductTypeCompleted(object sender, GetProductTypeCompletedEventArgs e)
{
cboProductType.ItemsSource = e.Result;
}
Calling the other method which returns a particular ProductTypeName. I tried to get the index of that particular ProductTypeName but returns -1 always.
void service_GetProductDetailsCompleted(object sender, GetServiceReference.GetProductDetailsCompletedEventArgs e)
{
if (e.Result.Count != 0)
{
p.ProductID = e.Result[0].ProductID;
int index = cboProductType.Items.IndexOf(e.Result[0].ProductTypeName);
cboProductType.SelectedIndex = index;
}
Also is this a right approach for setting the SelectedIndex property?
Say I have following items loaded in ComboBox in following Index order:
Index DisplayMemberName(ProductTypeName)
0 Color
1 Size
2 Variant
3 N-size
and e.Result[0].ProductTypeName contains Variant so I now want SelectedIndex = 2 of ComboBox
I hope my question is clear
The SelectedIndex is only valid when you manually fill a combobox. If you are using the ItemsSource to fill the items in a combobox, you must define a SelectedValuePath which will then allows you to use the SelectedItem property to SET/GET the selected item. When using binding to a DataContext to bind the controls, the SelectedValuePath should be the property that links the Parent/Child together.

Is this any way to find selected index id (selected record key value) of selected item of datalist without using SelectedIndexChanged event?

Is this any way to find selected record key value of selected item of datalist?
What is am doing is
protected void dlstSelectedImages_SelectedIndexChanged(object sender, EventArgs e)
{
int indexId = Convert.ToInt32(dlstSelectedImages.DataKeys[dlstSelectedImages.SelectedIndex]);
}
But my datalist SelectedIndexChanged is not firing (Itried with: View State="Enable", AutoEventWireup="true", AutopostBack="true" for firing the event ), so Is there anyother way to get the SelectedIndexChanged id or selected record key value
You should be able to call dlstSelectedImages.SelectedIndex at any time to get the currently selected index. It doesn't have to reside in an SelectedIndexChanged event handler. SelectedIndex is zero based and its default value is -1.
The SelectedIndexChanged event fires whenever the selected index changes (i.e. whenever SelectedIndex is assigned a new value). Typically, this would be on an ItemCommand or some other event:
void Item_Command(Object sender, DataListCommandEventArgs e)
{
// Set the SelectedIndex property to select an item in the DataList.
dlstSelectedImages.SelectedIndex = e.Item.ItemIndex;
// Rebind the data source to the DataList to refresh the control.
dlstSelectedImages.Rebind();
}

how to check whether gridview's row is selected or not in c#.net windows application

I want to know how to check whether a gridview's row got selected or not.
I am working on windows application.
I want to put a if condition ie if a particular row gets selected then fill the textbox with the correspoding cell value.
I am just not getting the way how to give the condition in the if clause.
Handle the DataGridView.SelectionChanged event. Use the DataGridView.SelectedRows property to get the selected rows collection.
private void dataGridView_SelectionChanged(object sender, EventArgs e)
{
// Update the text of TextBox controls.
textBox1.Text = dataGridView.SelectedRows[0].Cells[1].Value.ToString();
textBox2.Text = dataGridView.SelectedRows[0].Cells[2].Value.ToString();
....
}
Check DataGridViewRow.Selected property.
if (dataGridView.Rows[rowIndex].Selected)
{
// Do something ..
}
Check the selected property of DataGridViewRow, it returns true for selected else false.
bool isSelected = dataGridView1.Rows[e.RowIndex].Selected;
You can subscribe to the SelectionChanged event of the control and iterate through each selected row if multi-selection is enabled or just the first one if single-row selection only.
private void MyGridView_SelectionChanged(object sender, EventArgs e)
{
for (int i = 0; i < MyGridView.SelectedRows.Count; i++)
{
MyTextBox.Text = MyGridView.SelectedRows[i].Cells[0].Value.ToString(); //assuming column 0 is the cell you're looking for
// do your other stuff
}
}
More information can be found on the SelectedRows property.

ListBox and Datasource - prevent first item from being selected

Hey. I've got the following code that populates my list box
UsersListBox.DataSource = GrpList;
However, after the box is populated, the first item in the list is selected by default and the "selected index changed" event fires. How do I prevent the item from being selected right after the list box was populated, or how do I prevent the event from firing?
Thanks
To keep the event from firing, here are two options I have used in the past:
Unregister the event handler while setting the DataSource.
UsersListBox.SelectedIndexChanged -= UsersListBox_SelectedIndexChanged;
UsersListBox.DataSource = GrpList;
UsersListBox.SelectedIndex = -1; // This optional line keeps the first item from being selected.
UsersListBox.SelectedIndexChanged += UsersListBox_SelectedIndexChanged;
Create a boolean flag to ignore the event.
private bool ignoreSelectedIndexChanged;
private void UsersListBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (ignoreSelectedIndexChanged) return;
...
}
...
ignoreSelectedIndexChanged = true;
UsersListBox.DataSource = GrpList;
UsersListBox.SelectedIndex = -1; // This optional line keeps the first item from being selected.
ignoreSelectedIndexChanged = false;
Well, it looks like that the first element is automatically selected after ListBox.DataSource is set. Other solutions are good, but they doesn't resolve the problem. This is how I did resolve the problem:
// Get the current selection mode
SelectionMode selectionMode = yourListBox.SelectionMode;
// Set the selection mode to none
yourListBox.SelectionMode = SelectionMode.None;
// Set a new DataSource
yourListBox.DataSource = yourList;
// Set back the original selection mode
yourListBox.SelectionMode = selectionMode;
i using the following, seems to work for me:
List<myClass> selectedItemsList = dataFromSomewhere
//Check if the selectedItemsList and listBox both contain items
if ((selectedItemsList.Count > 0) && (listBox.Items.Count > 0))
{
//If selectedItemsList does not contain the selected item at
//index 0 of the listBox then deselect it
if (!selectedItemsList.Contains(listBox.Items[0] as myClass))
{
//Detach the event so it is not called again when changing the selection
//otherwise you will get a Stack Overflow Exception
listBox.SelectedIndexChanged -= listBox_SelectedIndexChanged;
listBox.SetSelected(0, false);
listBox.SelectedIndexChanged += listBox_SelectedIndexChanged;
}
}
set IsSynchronizedWithCurrentItem="False" and Also SelectedIndex=-1 and every thing should work for you
If you just want to clear the selected value, you can use ClearSelected after you set the DataSource. But if you dont want the event to fire, then you'll have to use one of Joseph's methods.
Perhaps in DataSourceChanged you could check the state of SelectedIndex, if your lucky you could then just force SelectedIndex = -1.

Categories