Reputation: 13
I have problem. I have 2 queries in a stored procedure. Both run on certain condition if condition is true query one executes and returns 7 columns from 3 tables. If condition fail 2nd query returns 4 columns.
On front end I use a datatable to store query result. I assign values to textbox from datatable.
like
dt is data table name
Txt_name.Text=dt.Rows[0][6].ToString();
problem is that when 2nd query executes an error occurs. No columns exists at 6.
How I find dt has column at at index 6 or not?
Upvotes: 1
Views: 819
Reputation:
Try this code
int indx = 6;
if(dt != null and dt.Columns.Count > indx)
{
Txt_name.Text=dt.Rows[0][indx].ToString();
}
Upvotes: 2
Reputation: 2987
Do you have access to modify the stored procedure? And also manage all resources that use this stored procedure? I would recommend that it return the same structure regardless of the result.
If there is a false result, just have the additional fields empty. You can achieve this with the COALESCE
operator, which return a given value (as ''
in case of empty string) if there is NULL (i.e. no records in joined table).
A function that behave different base on a fields-count will nearly works as a Insurance to break the code in future. There will be a magic number "6" which can make behavior of the if-else-clause invert or always evaluate same result. If the stored procedure HAVE to return different structures, evaluate true/false first an then call the adequate stored procedure.
Upvotes: 0
Reputation: 14282
You can check the colums count something like below:
int index = 6;
Txt_name.Text = dt.Columns.Count > index ? dt.Rows[0][index].ToString() : String.Empty;
Upvotes: 1