Reputation: 145
I have a listview in Windows forms populated by a SQL database. 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?
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();
}
Upvotes: 0
Views: 2518
Reputation: 55720
You need to check whether FocusedElement
is not null before attempting to reference it.
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. The code would be the same, just using SelectedItem
.
Upvotes: 0
Reputation: 8020
You can do
if(lvBrands.SelectedItems.Count > 0)
{
//you have something selected
}
Upvotes: 3