Thursday, March 22, 2012

Setting the data source for a dropdown list within a repeater

I'm trying to set the data source of a dropdownlist with a repeater control. Can someone help with me with the syntax of how to do it when looping through the repeater?First, put a DropDownList inside the Repeater.

Second, create a datasourse for it using a function call like


<asp:DropDownList ID="ddlBookPublisher" DataValueField="pub_id"
DataTextField="pub_name" DataSource='<%# getBookPublisher() %>'
SelectedIndex='<%# getBookPublisherIndex(Convert.ToString(DataBinder.Eval
(Container.DataItem,"pub_id"))) %>'
runat="server"></asp:DropDownList>

Here, getBookPublisher() function to get the item list, and display as the DropDownList list
items. Another function getBookPublisherIndex to get the selected item according to the data loaded to th Repeater. (You can take it off if you don't need it). And, set DataValueField and DataTextField to the table column.

Then, code the function like


DataSet getBookPublisher()
{
SqlDataAdapter myCommand = new SqlDataAdapter
("BookPublisher",myConnection);

myCommand.SelectCommand.CommandType =
CommandType.StoredProcedure;

DataSet DS = new DataSet();

try
{
myCommand.Fill(DS, "Publisher");
return DS;
}
catch (Exception ex)
{
throw (ex);
}
finally
{
myConnection.Close();
}
}


BookPublisher is a Stored Procedure. You can use a query instead.

I use SQL Server sample database pubs as example. You can run it too.

0 comments:

Post a Comment