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();
}
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.
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
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.