I'm using a databound listbox in a C# WinForm application.
When I click on an item in the listbox nothing else on the form works, even when I click on the close button the form doesn't close. Everything works fine until I select an item.
What I have tried to do is in the listbox1_SelectedIndexChanged set the listbox1 focus to false but that didn't work.
Code sample: This is the code that assigns the listbox to the data source:
this.ListBox1.DataBindings.Add(new System.Windows.Forms.Binding("SelectedValue", this.table1BindingSource, "PrimaryKeyId", true));
this.ListBox1.DataSource = this.table1BindingSource;
this.ListBox1.DisplayMember = "Name";
开发者_如何转开发this.ListBox1.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.ListBox1.FormattingEnabled = true;
this.ListBox1.ItemHeight = 24;
this.ListBox1.Location = new System.Drawing.Point(185, 28);
this.ListBox1.Name = "ListBox1";
this.ListBox1.Size = new System.Drawing.Size(660, 532);
this.ListBox1.TabIndex = 7;
this.ListBox1.ValueMember = "Name";
this.ListBox1.SelectedIndexChanged += new System.EventHandler(this.ListBox1_SelectedIndexChanged);
ListBox1 isn't referenced anywhere else. This is the initial code I was using before:
private void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
ListBox1.Focus().Equals(false);
}
This is the code I am now running:
private void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
GroupBox1.Focus().Equals(true);
}
Then on Windows load I have: table1TableAdapter.Fill(this.Application1DataSet.Table1);
I've debug the windows load and the listbox1 method so I don't think it's a loop. Also the app doesn't crash so I don't think it's a loop.
This code:
ListBox1.Focus().Equals(false);
...does not "un-focus" the list box.
If you look at the documentation for Focus
, you'll see that it focuses the control, if it can, otherwise it returns false
.
Tacking on .Equals(false)
simply compares the result of that call to the value false
. In other words, it's equivalent to writing this:
!ListBox1.Focus()
Which pretty obviously does not remove focus from the list box, it actually sets focus to the list box in most cases. You are simply making a comparison on the return value and then throwing the result of the comparison away.
As you discovered yourself, there is no method to remove focus from a control. You can only set focus to some other control.
It will work if you write:
listBox1.ValueMember = "PrimaryKeyId";
I have also encountered this when developing an application but thank God, this worked.
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
listBox1.SelectedIndex = -1;
}
What did work was setting the focus to another control on the form. But it's still a weird problem.
精彩评论