[英]C# Windows forms Listview selected item
I have a listview in Windows forms populated by a SQL database. 我在Windows表单中有一个由SQL数据库填充的listview。 i have a button to delete records when selected and it's working fine.
我有一个按钮,可以在选择记录时将其删除,并且工作正常。 but if there is no selected item and i click the delete button i get and error.
但是,如果没有选定的项目,并且我单击删除按钮,则会出现错误。 so i add a messagebox and a condition but a always get - Object reference not set to an instance of an object.
所以我添加了一个消息框和一个条件,但始终获取- 对象引用未设置为对象的实例。
so how do i check if there is a selected item in the listview so it enter the If? 所以我如何检查列表视图中是否有选定的项目,以便它输入If?
thanks 谢谢
private void btnDelete_Click(object sender, EventArgs e)
{
bool b = this.lvBrands.FocusedItem.Checked;
if (b == false)
{
MessageBox.Show("You must select a brand .", "Brand Select Error",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
else
{
string sID = this.lvBrands.FocusedItem.Text;
deleteBrand(sID);
clearBrand();
}
You can do 你可以做
if(lvBrands.SelectedItems.Count > 0)
{
//you have something selected
}
You need to check whether FocusedElement
is not null before attempting to reference it. 在尝试引用它之前,您需要检查
FocusedElement
是否不为null。
bool b = false;
if(this.lvBrands.FocusedItem != null)
{
b = this.lvBrands.FocusedItem.Checked;
}
However, as @bobek pointed out if you are looking for the selected item you should be using the SelectedItem
instead of the FocusedItem
property. 但是,正如@bobek指出的那样,如果要查找选定的项目,则应使用
SelectedItem
而不是FocusedItem
属性。 The code would be the same, just using SelectedItem
. 只是使用
SelectedItem
,代码是相同的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.