Saturday, March 24, 2012

Populate drop down list with sql query (contains IF)

I have a drop down list and it is to get it's 'text' and 'value' from a table. The table contains 3 columns:
Title, Name, Id1, Id2
if Id1 is NOT blank then the 'text' value of the drop down list should be:
Name + "(" + Id1 + ")"
else
Name + "(" + Id2 + ")"
I believe the easiest way is to construct the above IF statement is to use SQL query, then pass the parameter to the DataTextField property. However, i seemed to be getting an error. Also any help on the SQL IF statement will be appreciated...
This is what i have so far...(without the IF statement as i'm not sure how to construct the IF statement in SQL)
Sub Page_Load(sender as Object, e as EventArgs)
If Not Page.IsPostBack Then
dropDownList.DataSource = ToGetDataTable()
dropDownList.DataValueField = "MyNewColumn"
dropDownList.DataTextField = "Name"
dropDownList.DataBind()
End if
End Sub

Function ToGetDataTable() As System.Data.IDataReader
Dim connectionString As String = "server='(local)';..................."
Dim dbConnection As System.Data.IDbConnection = New System.Data.SqlClient.SqlConnection(connectionString)

Dim queryString As String = "SELECT Title, Name + ' ( ' + Id1 + ')' AS MyNewColumn FROM MyTableName"
Dim dbCommand As System.Data.IDbCommand = New System.Data.SqlClient.SqlCommand
dbCommand.CommandText = queryString
dbCommand.Connection = dbConnection

dbConnection.Open
Dim dataReader As System.Data.IDataReader = dbCommand.ExecuteReader(System.Data.CommandBehavior.CloseConnection)

Return dataReader
End Function

Do you have sufficient rights on your SQL Server box to create auser-defined function? That seems to be the best way to go aboutthis; you would simply select Title, Name (which is a terrible name fora database field), and MyFunction(Name, Id1, Id2) where MyFunctionwould do the work.
If you don't have this option, you could pull all necessary columns,put them into a DataTable, and then run through it, appending theappropriate values in one particular column.

0 comments:

Post a Comment