RadioButtonList es un interesante control que permite agrupar objetos de tipo RadioButton, dejandolos la seleccionar solamente uno de los que se encuentran agrupados en el (RadioButtonList).
Lo interesante es que también podemos enlazar este control desde una base de datos, creando un «item» por cada registro que tenga la tabla selecciona. Sin más les dejo el código para enlazar. (Es como enlazar un dropdownlist)
Un Saludo desde Guatemala.
<pre><%@ Control Language="C#" ClassName="PollControlAsync" %>
<%@ Import Namespace="System.Collections.Generic" %>
<%@ Import Namespace="System" %>
<%@ Import Namespace="System.Web" %>
<%@ Import Namespace="System.Web.UI" %>
<%@ Import Namespace="System.Web.UI.WebControls" %>
<%@ Import Namespace="System.Text" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.Data" %>
<script runat="server">
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
BindRadioButtonListData(1);
}
private void BindRadioButtonListData(int PollID)
{
// sting de conexion
string connectionString = ConfigurationManager.ConnectionStrings["PollConnectionString"].ConnectionString;
// Inicializacion del objeto sql connection
using (SqlConnection mySqlConnection = new SqlConnection(connectionString))
{
try
{
// abrir conexion sql
mySqlConnection.Open();
// consultamos los datos
SqlCommand mySqlCommand = new SqlCommand("SELECT * FROM [PollAnswers] WHERE ([PollID] = @PollID) ORDER BY [SortOrder]", mySqlConnection);
mySqlCommand.Parameters.AddWithValue("@PollID", PollID);
// utilizamos el objeto Sql Data Adapter object para pasarle el comando sql
SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter(mySqlCommand);
// instanciamos un dataset
DataSet myDataSet = new DataSet();
// llenamos el dataset
mySqlDataAdapter.Fill(myDataSet);
// indicamos el recurso de datos al RadioButtonList
rblPollAnswers.DataSource = myDataSet;
// especificamos el campo (texto que se mostrara)
rblPollAnswers.DataTextField = "DisplayText";
// indicamos el valor de cada objeto
rblPollAnswers.DataValueField = "PollAnswerID";
// enlazamos
rblPollAnswers.DataBind();
}
catch (Exception ex)
{
Label1.Text = ex.Message;
}
finally
{
// cerramos la conexión sql
mySqlConnection.Close();
}
}
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
}
/// <summary>
/// Gets or sets the poll ID.
/// </summary>
/// <value>The poll ID.</value>
public int PollID
{
get
{
if (ViewState["PollID"] == null)
return -1;
else
return (int)ViewState["PollID"];
}
set { ViewState["PollID"] = value; }
}
</script>
<asp:RadioButtonList ID="rblPollAnswers" runat="server" /></pre>