Darren Young
Darren Young

Reputation: 11090

C# Returning Types from a method

If I have a method that returns a datagridview and the flow is similar to this:

if (ds.Tables.Count == 0)
        {
            SharedMethods.updateStatus("There are no excluded results to display");
            //return dgv;
        }
        else
        {
            dgv.DataSource = ds.Tables[0];
            dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
            dgv.AllowUserToAddRows = false;

            return dgv;
        }

If the if condition is true then I do not want to return a datagridview(as there is no data), what can I return in this case? If I return null, then the calling method has a null datagridview that causes later problems.

Thanks.

Upvotes: 1

Views: 137

Answers (5)

Hans Passant
Hans Passant

Reputation: 941218

Just set the grid's Visible property to false if you have nothing to show.

Upvotes: 1

Nobody
Nobody

Reputation: 4841

You could set the return type of the method to return an error code (enum) and have the DataGridView as an out or ref parameter.

Upvotes: 2

Dercsár
Dercsár

Reputation: 1694

I would not return anything from a data binding method. Why do you need that? (This code won't even compile because the true block has nothing to return.)

Simply make it a method.

Upvotes: 0

ChrisF
ChrisF

Reputation: 137108

The way I see it you have two solutions:

  1. Return a null DataGridView and modify your calling code with that.

  2. Return a DataGridView but with a null DataSource (as there's no data) and make sure your calling code can cope with that.

Personally I'd go with 2. You still have a view but no data, so you still need a DataGridView but it's empty.

Upvotes: 0

CodesInChaos
CodesInChaos

Reputation: 108790

You can

  1. throw an exception
  2. null and add special case handling for null to the caller
  3. If DataGridView supports it, an empty list

You usually use 3) with IEnumerables<T>, but I don't know if your return type supports it. This solution is best if you want your to behave the same way in your first case as if you got no results from your query.

Upvotes: 2

Related Questions