0

Is there any possible way to make this code shorter?


            int? index = ListOfPeople.BinarySearch(searchBar.Text);
            int? temp = int.TryParse(index.ToString(), out int i) ? (int?)1 : null;
            MyPeopleGrid.SelectionMode = DataGridViewSelectionMode.RowHeaderSelect;
            MyPeopleGrid.Rows[i].Selected = true;
            MyPeopleGrid.CurrentCell = MyPeopleGrid.Rows[i].Cells[0];

1 Answer 1

1

You seem to have seriously overcomplicated things, and you certainly should never convert a number to a string only to parse it back to a number.

int index = ListOfPeople.BinarySearch(searchBar.Text);

This will return a non-negative number when the item isn't found. It does not return int?, it returns int.

So now you can use it:

int index = ListOfPeople.BinarySearch(searchBar.Text);
if (index >= 0)
{
    MyPeopleGrid.SelectionMode = DataGridViewSelectionMode.RowHeaderSelect;
    MyPeopleGrid.Rows[index].Selected = true;
    MyPeopleGrid.CurrentCell = MyPeopleGrid.Rows[index].Cells[0];
}
else
{
    // do something when the item isn't found
}
Sign up to request clarification or add additional context in comments.

3 Comments

OK, what are you actually trying to do then? Why do you need a nullable int? What's that for?
Can you post some more code? I don't understand why you're not just using ArrayList.BinarySearch(searchBar.Text); without the extra stuff.
What are you using temp for?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.