I am new at C# and it seems the following code below does not seem to select my combobox value:
private void button1_Click(object sender, EventArgs e)
{
cbPortNumber.SelectedValue = 3;
or
cbPortNumber.setValue("3");
or
cbPortNumber.SelectedIndex = cbPortNumber.FindString("3");
or
cbPortNumber.SelectedIndex = cbPortNumber.Items.IndexOf(cbPortNumber.Items.FindByValue("HDMI 4"));
}
The dropdown looks like this:
All code above does not seem to select HDMI 4 on the list... I dont have any errors but i also don't have it being selected.
Any help would be great!
update showing combobox
UPDATE 2
//
// cbPortNumber
//
this.cbPortNumber.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Append;
this.cbPortNumber.Enabled = false;
this.cbPortNumber.FormattingEnabled = true;
this.cbPortNumber.Location = new System.Drawing.Point(174, 40);
this.cbPortNumber.Name = "cbPortNumber";
this.cbPortNumber.Size = new System.Drawing.Size(133, 21);
this.cbPortNumber.TabIndex = 11;
this.cbPortNumber.Text = "global_hdmi_port";
this.helpPortNumber.SetToolTip(this.cbPortNumber, "The HDMI port number, to which you connected your USB-CEC adapter.");
this.cbPortNumber.SelectedIndexChanged += new System.EventHandler(this.cbPortNumber_SelectedIndexChanged);
#region Global settings
public CECSettingByte HDMIPort
{
get
{
if (!_settings.ContainsKey(KeyHDMIPort))
{
CECSettingByte setting = new CECSettingByte(KeyHDMIPort, "HDMI port", 1, _changedHandler) { LowerLimit = 1, UpperLimit = 15, EnableSetting = EnableHDMIPortSetting };
setting.Format += delegate(object sender, ListControlConvertEventArgs args)
{
ushort tmp;
if (ushort.TryParse((string)args.Value, out tmp))
args.Value = "HDMI " + args.Value;
};
Load(setting);
_settings[KeyHDMIPort] = setting;
}
return _settings[KeyHDMIPort].AsSettingByte;
}
}
Update 3
And this is what fires the action after selecting something in that dropdown:
private void OnSettingChanged(CECSetting setting, object oldValue, object newValue)
{
if (setting.KeyName == CECSettings.KeyHDMIPort)
{
CECSettingByte byteSetting = setting as CECSettingByte;
if (byteSetting != null)
{
if (!Settings.OverridePhysicalAddress.Value)
Config.HDMIPort = byteSetting.Value;
CECActions.SetConnectedDevice(Settings.ConnectedDevice.Value, byteSetting.Value);
}
}
So this code is working fine for me:
private void button1_Click(object sender, EventArgs e)
{
comboBox1.SelectedIndex = 2;
}
you can not access a ItemSource if there are no items to access. The simple way is to Init the items over the Desinger
( Sory for the nonlocalized IDE ) than you can set the Property SelectedIndex to a Index that exits. The other way is to Add all HDMI items with the Combobox1.Items.Add function.
If you ever used Forms in VB ... its still the same
public Form1()
{
InitializeComponent();
var hdmi = "HDMI";
for (int i = 1; i < 15; i++)
{
comboBox1.Items.Add( hdmi + i);
}
}
private void button1_Click(object sender, EventArgs e)
{
if (comboBox1.Items.Count >= 2)
comboBox1.SelectedIndex = 2;
}
Related
I'm new on C# and i have many difulties, but now i'm still trying add an eventhandler to declared control like a variable, but if i use the delegate instruction i cant put this events because when i use the declaration:
private delegate void listView1_MouseUp(object sender, MouseEventArgs e)
Many error appears in a procedure that i caught in this forum, but i will put all procedure to you see.
private void Form1_Load(object sender, EventArgs e)
{
// Set the view to show details.
listView1.View = View.Details;
// Allow the user to edit item text.
listView1.LabelEdit = true;
// Allow the user to rearrange columns.
listView1.AllowColumnReorder = true;
// Select the item and subitems when selection is made.
listView1.FullRowSelect = false;
// Display grid lines.
listView1.GridLines = true;
// Sort the items in the list in ascending order.
listView1.Sorting = SortOrder.Ascending;
//Hide Column Header
listView1.HeaderStyle = ColumnHeaderStyle.None;
// Create three items and three sets of subitems for each item.
ListViewItem[] ItemsView = new ListViewItem[Quant_Items];
while (Item_Number <= (Quant_Items - 1))
{
ItemsView[Item_Number] = new ListViewItem(Item_name + Item_Number);
while (Sub_Item <= (Quant_SubItems - 1))
{
ItemsView[Item_Number].SubItems.Add("SubItem" + Sub_Item);
Sub_Item++;
}
Item_Number++;
}
Sub_Item = 0;
while (Sub_Item <= (Quant_SubItems - 1))
{
listView1.Columns.Add("Coluna" + Sub_Item);
Sub_Item++;
}
//Add the items to the ListView.
listView1.Items.AddRange(ItemsView);
//Autosize ListView
listView1.Bounds = new Rectangle(new Point(10, 10), new Size(Quant_SubItems * 70, Quant_Items * 18));
// Add the ListView to the control collection.
this.Controls.Add(listView1);
listView1.MouseUp += new EventHandler(listView1_MouseUp);
}
//____________________________________________________________________
private delegate void listView1_MouseUp(object sender, MouseEventArgs e)
{
ListViewHitTestInfo i = listView1.HitTest(e.X, e.Y);
SelectedLSI = i.SubItem;
if (SelectedLSI == null)
return;
int border = 0;
switch (listView1.BorderStyle)
{
case BorderStyle.FixedSingle:
border = 1;
break;
case BorderStyle.Fixed3D:
border = 2;
break;
}
int CellWidth = SelectedLSI.Bounds.Width;
int CellHeight = SelectedLSI.Bounds.Height;
int CellLeft = border + listView1.Left + i.SubItem.Bounds.Left;
int CellTop = listView1.Top + i.SubItem.Bounds.Top;
// First Column
if (i.SubItem == i.Item.SubItems[0])
CellWidth = listView1.Columns[0].Width;
TxtEdit.Location = new Point(CellLeft, CellTop);
TxtEdit.Size = new Size(CellWidth, CellHeight);
TxtEdit.Visible = true;
TxtEdit.BringToFront();
TxtEdit.Text = i.SubItem.Text;
TxtEdit.Select();
TxtEdit.SelectAll();
}
private void listView2_MouseDown(object sender, MouseEventArgs e)
{
HideTextEditor();
}
private void listView2_Scroll(object sender, EventArgs e)
{
HideTextEditor();
}
private void TxtEdit_Leave(object sender, EventArgs e)
{
HideTextEditor();
}
private void TxtEdit_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return)
HideTextEditor();
}
private void HideTextEditor()
{
TxtEdit.Visible = false;
if (SelectedLSI != null)
SelectedLSI.Text = TxtEdit.Text;
SelectedLSI = null;
TxtEdit.Text = "";
}
}
}
Thanks for your help!
Just use this:
private void listView1_MouseUp(object sender, MouseEventArgs e)
{
...
}
The delegate keyword doesn't belong in the method declaration, it's not valid in that context.
When you handle an event, you must supply a handler that matches the delegate type expected by this event. Loosley speaking, you need a method with the same signature expected by the handler.
For MouseUp, you need to supply a MouseEventHandler, see https://msdn.microsoft.com/en-us/library/system.windows.forms.mouseeventhandler(v=vs.110).aspx
You need to change the event subscription to
listView1.MouseUp += new MouseEventHandler(listView1_MouseUp);
Then change the signature of your handler to
private void listView1_MouseUp(object sender, MouseEventArgs e) { /*..*/}
I have a comoboBox that is binded to sql database, and I added a default text at index 0 like this
string s = "< -------------Select an application ----------->";
applicationComboBox.Items.Insert(0, s);
applicationComboBox.SelectedIndex = 0;
I am wondering if there is a way to disable my button if the the string s at index 0 is select? In my comboBox, I binded the data with the while(SQLReader.Read()) method instead of using ValueMember and `DisplayMember
Here is what I tried but no luck
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
for (int i = 1; i < applicationComboBox.Items.Count; i++)
{
string value = applicationComboBox.GetItemText(applicationComboBox.Items[0]);
string s = "<------------- Select an application ----------->";
if (value == s)
{
exportButton.Enabled = false;
MessageBox.Show(value); //nothing happen
this.teacherCheckListBox.DataSource = null;
teacherCheckListBox.Items.Clear();
}
else
{
exportButton.Enabled = true;
}
}
}
}
Use SelectedIndex property to know which item is selected and disable the button if it is first item.
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedIndex == 0)
{
exportButton.Enabled = false;
}
}
I'm trying to display an image using a button click and increment a variable when a certain image is shown, but with the code below the variable num is always 0.
my code
int num = 0;
int i = 0;
int x = 0;
PictureBox[] pictureBoxs = new PictureBox[4];
Random rnd = new Random();
public UserControl1()
{
InitializeComponent();
pictureBoxs[0] = pbimg1;
pictureBoxs[1] = pbimg2;
pictureBoxs[2] = pbimg3;
pictureBoxs[3] = pbimg4;
x = rnd.Next(2);
}
public void displaypics()
{
pictureBoxs[i].Image = imageList1.Images[x];
}
private void btn2_Click(object sender, EventArgs e)
{
i=1;
displaypics();
if (pictureBoxs[i].Image == imageList1.Images[1])
{
num++;
}
if (num == 2)
{
tb1.Visible = true;
tb1.Text = "GAME OVER!" + num;
}
}
The reason is most likely that num is being instantiated to zero everytime the class is being instantiated
What happens when you set breakpoints and step through the code? Is the int set as 0, or does it contain the updated value?
I'm not sure what the context is in which that piece of code is used. So I guess what should solve this would be adding x = rnd.Next(2) to the btn2_Click method. Making it look like this:
private void btn2_Click(object sender, EventArgs e)
{
x = rnd.Next(2);
displaypics();
if (pictureBoxs[i].Image == imageList1.Images[1])
{
num++;
}
if (num == 2)
{
tb1.Visible = true;
tb1.Text = "GAME OVER!" + num;
}
i++;
}
Maybe you could give some more details on what that control should do/how it's used.
I have a form with databound combobox, with dropstyle set as dropdown, so users could type in the combobox.
My problem is that when users type in the combobox and the value typed matches one of the values bound to the combobox it won't change the selectedindex, even though I've tried too. Instead, it sets the selected index to -1 (and thus the selected value is null).
Can anyone help? here's my code (one of my tries, i tried other approaches but none helped).
private void setCombo()
{
comboFromOther.DisplayMember = "tbl10_KupaID";
comboFromOther.ValueMember = "tbl10_KupaID";
comboFromOther.DataSource = dsKupotGemel.Tables[0];
}
private void comboToOther_TextChanged(object sender, EventArgs e)
{
comboDetail = changedComboText(2, comboToOther.Text);
textToOther.Text = comboDetail[0];
if (comboDetail[0] == "")
{
}
else
{
comboToOther.SelectedIndex = System.Int32.Parse(comboDetail[1]);
comboToOther.SelectedValue = System.Int32.Parse(comboDetail[2]);
}
}
private string[] changedComboText(int iComboType, string comboString)
{
if (groupCalculate.Visible == true)
{
groupCalculate.Visible = false;
}
string[] kupaDetail = new string[3];
kupaDetail[0] = "";
kupaDetail[1] = "";
kupaDetail[2] = "";
for (int i = 0; i <= dsKupotGemel.Tables[0].Rows.Count - 1; i++)
{
if (comboString == dsKupotGemel.Tables[0].Rows[i][0].ToString())
{
kupaDetail[0] = dsKupotGemel.Tables[0].Rows[i][1].ToString();
kupaDetail[1] = i.ToString();
kupaDetail[2] = comboString;
break;
}
else
{
}
}
return kupaDetail;
}
Maybe there is an error in your code?
Here is a working sample:
// Fields
private const string NameColumn = "Name";
private const string IdColumn = "ID";
private DataTable table;
Next, initialization
// Data source
table = new DataTable("SomeTable");
table.Columns.Add(NameColumn, typeof(string));
table.Columns.Add(IdColumn, typeof(int));
table.Rows.Add("First", 1);
table.Rows.Add("Second", 2);
table.Rows.Add("Third", 3);
table.Rows.Add("Last", 4);
// Combo box:
this.comboBox1.DisplayMember = NameColumn;
this.comboBox1.ValueMember = IdColumn;
this.comboBox1.DataSource = table;
this.comboBox1.DropDownStyle = ComboBoxStyle.DropDown;
this.comboBox1.TextChanged += comboBox1_TextChanged;
this.comboBox1.SelectedIndexChanged += this.comboBox1_SelectedIndexChanged;
Event handlers - TextChanged:
private void comboBox1_TextChanged(object sender, EventArgs e)
{
for (int i = 0; i < table.Rows.Count; i++)
{
if (table.Rows[i][NameColumn].ToString() == this.comboBox1.Text)
{
this.comboBox1.SelectedValue = table.Rows[i][IdColumn];
break;
}
}
}
Event handlers - SelectedIndexChanged:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
// Do here what is required
}
With this code, as soon as user types full name of item into combo box, SelectedIndexChanged is invoked through TextChanged.
There is also such thing as AutoCompleteMode, AutoCompleteSource. Don't know where they fit into your application.
I have created a code for my combobox, that can search addresses in a very large table on Sql Server with the help of stored procedure (i'm working with Entity framework). My stored procedure returns 10 hits and my code fills the combobox with search results. For doing this I'm using BackgroundWorker.
But here I'm now having big problems:
- although the combobox is filled with my search results, it always has the first item selected. Even if I type in only a letter, the whole text gets selected;
After that searching for the address doesn't work anymore. It searches only among these 10 results and I'm having no idea how to solve this. Here is my whole code, that causes me problems:
public String searchedItem = "";
public delegate void DelegateUpdateComboboxSelection(ComboBox myCombo,string value,int count);
BackgroundWorker m_bgworker = new BackgroundWorker();
static AutoResetEvent resetWorker = new AutoResetEvent(false);
m_bgworker.WorkerSupportsCancellation = true;
m_bgworker.DoWork += new DoWorkEventHandler(FillComboboxBindingList);
m_bgworker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(m_bgworker_RunWorkerCompleted);
BindingList<spIskalnikNaslovi_Result1> m_addresses = new BindingList<SP_Result1>();
void m_bgworker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
int count = (int)((object[])e.Result)[0];
string value = (string)((object[])e.Result)[1];
ComboBox myCombo = (ComboBox)((object[])e.Result)[2];
DelegateUpdateComboboxSelection ndelegate = new DelegateUpdateComboboxSelection(UpdateComboSelection);
if (this.InvokeRequired)
{
Invoke(ndelegate, new object[] {myCombo, value, count});
return;
}
else
{
UpdateComboSelection(myCombo, value, count);
return;
}
}
private void UpdateComboSelection(ComboBox myCombo, String value, int count)
{
myCombo = comboBox9;
myCombo.DataSource = m_addresses;
searchedItem = myCombo.Text;
if (count > 0)
{
myCombo.SelectionStart = value.Length;
myCombo.SelectionLength = searchedItem.Length - value.Length;
myCombo.DroppedDown = true;
}
else
{
myCombo.DroppedDown = false;
myCombo.SelectionStart = value.Length;
}
}
public void FillComboboxBindingList(object sender, DoWorkEventArgs e)
{
if (m_bgworker.CancellationPending)
{
resetWorker.Set();
e.Cancel = true;
return;
}
else
{
string value = (String)((Object[])e.Argument)[0];
List<SP_Result1> result;
result = _vsebina.SP_searcher(value).ToList<SP_Result1>();
m_addresses = new BindingList<SP_Result1>();
foreach (SP_Result1 rez in result)
{
if (m_addresses.Contains(rez))
{
continue;
}
else
{
m_addresses.Add(rez);
}
}
foreach (SP_Result1 r in m_addresses.ToArray())
{
if (!result.Contains(r))
{
m_addresses.Remove(r);
}
}
e.Result = new object[] { rezultat.Count, vrednost, null };
return;
}
}
private void comboBox9_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Back)
{
int searchStart = comboBox9.SelectionStart;
if (searchStart > 0)
{
searchStart--;
if (searchStart == 0)
{
comboBox9.Text = "";
}
else
{
comboBox9.Text = comboBox9.Text.Substring(0, searchStart + 1);
}
}
else
{
searchStart = 0;
}
e.Handled = true;
}
}
private void comboBox9_Enter(object sender, EventArgs e)
{
comboBox9.SelectionStart = 0;
comboBox9.SelectionLength = 0;
}
private void comboBox9_Click(object sender, EventArgs e)
{
comboBox9.Text = "";
}
private void comboBox9_KeyPress(object sender, KeyPressEventArgs e)
{
Search();
}
public void Search()
{
if (comboBox9.Text.Length < 4)
{
return;
}
else
{
if (m_bgworker.IsBusy)
{
m_bgworker.CancelAsync();
m_bgworker = new BackgroundWorker();
m_bgworker.WorkerSupportsCancellation = true;
m_bgworker.DoWork += new DoWorkEventHandler(FillComboboxBindingList);
m_bgworker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(m_bgworker_RunWorkerCompleted);
}
m_bgworker.RunWorkerAsync(new object[] { comboBox9.Text, comboBox9 });
}
}
Maybe can someone enlighten me, what I'm doing wrong. This is first time, that I'm using BackgroundWorker. I have no idea, how
to achieve "search as you type" with combobox in any other way, because my datatable with addresses is quite large (million records).
Thanks in advance for any kind of help or code example.
Vladimir
Edit 1:
Ok, here is my code, before I have used BackGroundWorker. It worked, but it searches very very slow (it can take up to 10 seconds):
private void comboBox9_TextChanged(object sender, EventArgs e)
{
if (comboBox9.Text.Length < 4)
{
return;
}
else
{
FillCombobox(comboBox9.Text, comboBox9);
}
}
public void FillCombobox(string value, ComboBox myCombo)
{
List<spIskalnikNaslovi_Result1> result;
result = _vsebina.spIskalnikNaslovi1(value).ToList();
if (result.Count() > 0)
{
myCombo.DataSource = result;
myCombo.ValueMember = "HS_MID";
myCombo.DisplayMember = "NASLOV1";
var searchedItem = myCombo.Items[0].ToString();
myCombo.SelectionStart = value.Length;
myCombo.SelectionLength = searchedItem.Length - value.Length;
myCombo.DroppedDown = true;
}
else
{
myCombo.DroppedDown = false;
myCombo.SelectionStart = value.Length;
}
return;
}
Is there a way to speed this up without having backgroundworker?
make a button you will call searchbutton
and in click_event of this button call your search() method that run your backgroundworker
that fill the combobox
clear you key_press event of your combobox and it will work
the mistake is you key_press event that call every key stroke happening your search method
so retrieve it
You should get your items in a list, use that list to populate your combobox.
then set AutoCompleteMode property value to Suggest or Append or SuggestAppend and set AutoCompleteSoucre property value to ListItems.
For "Search as you Type", which is actually "Filter as you Type" more than search, you need to implement the OnKeyDown or KeyPressed event.
What you would do is take the search string, which is the current text at the time of the event, then filter the master list using that string. Normally one would use "Starts With" for the filtering, but you could also simply use "Contains". Then you live update the contents of the box with the results from the filter. This is accomplished by changing and refreshing the Datasource.
Here is my final solution without BackGroundWorker. It works quick with my large table, and is upgraded for using a stored procedure on SQL Server (if you use Entity Framework). I use Timer to make sure the user can find a value, that he is searching.
Here you can see the original solution, that I found on this site (thanks to Max Lambertini and algreat for the idea and working concept):
C# winforms combobox dynamic autocomplete
My solution:
private bool _canUpdate = true;
private bool _needUpdate = false;
List<spIskalnikNaslovi_Result1> dataFound;
private void comboBox12_TextChanged(object sender, EventArgs e)
{
if (_needUpdate)
{
if (_canUpdate)
{
_canUpdate = false;
refreshData();
}
else
{
restartTimer();
}
}
}
private void comboBox12_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Back)
{
int searchStart = comboBox12.SelectionStart;
if (searchStart > 0)
{
searchStart--;
if (searchStart == 0)
{
comboBox12.Text = "";
}
else
{
comboBox12.Text = comboBox12.Text.Substring(0, searchStart + 1);
}
}
else
{
searchStart = 0;
}
e.Handled = true;
}
}
private void comboBox12_TextUpdate(object sender, EventArgs e)
{
_needUpdate = true;
}
private void timer1_Tick(object sender, EventArgs e)
{
_canUpdate = true;
timer1.Stop();
refreshData();
}
private void refreshData()
{
if (comboBox12.Text.Length > 1)
{
FillCombobox(comboBox12.Text, comboBox12);
}
}
private void restartTimer()
{
timer1.Stop();
_canUpdate = false;
timer1.Start();
}
private void FillCombobox(string value, ComboBox myCombo)
{
dataFound = _vsebina.spIskalnikNaslovi1(value).ToList();
if (dataFound.Count() > 0)
{
myCombo.DataSource = dataFound;
myCombo.ValueMember = "HS_MID";
myCombo.DisplayMember = "NASLOV1";
var searchedItem = myCombo.Items[0].ToString();
myCombo.SelectionStart = value.Length;
myCombo.SelectionLength = searchedItem.Length - value.Length;
myCombo.DroppedDown = true;
return;
}
else
{
myCombo.DroppedDown = false;
myCombo.SelectionStart = value.Length;
return;
}
}