How to display data in a DropDownList?

1

I'm with a project that consists in creating a content manager for an information portal, so far I made the insert to add new articles to the information forums, now I continue with the part of the queries to be able to perform the update and the delete , the problem with the queries is that the ASP.NET language with C # had not been handled before.

I need to know how to make it so that by means of a select or a DropDownList when I display it, it shows me the articles (ids) that are currently in the database so that I can select them and that when I select them, I show in TexrArea and TextBox . The information that I consult and that I put in the TexrArea and TextBox are an image, a title and a paragraph, I am using the layer structure.

    
asked by Izhoka Perez 04.01.2019 в 15:50
source

2 answers

2

One of the solutions is going to be the following example:

load a drop-down list in the form of layers:

In the HTML Code you should add the object:

<asp:DropDownList ID="cboEjemplo" runat="server" OnSelectedIndexChanged="cboEjemplo_SelectedIndexChanged"></asp:DropDownList>

In the Code-Behind you must add the method to load the list for the first time. It must be done in the Page_Load since it is when the page is loaded:

protected void Page_Load(object sender, EventArgs e)
{
        if (!Page.IsPostBack)
        {
            cargarLista();
        }

}

The CargarLista() method contains the following:

public void CargarLista()
{

    IList<coleccionEjemplo> coleccionEjemplo;

        coleccionEjemplo= RepositoryEjemplo.obtener();
        Carga(coleccionEjemplo, cboEjemplo,"Codigo","Nombre");

}

It should be noted that the repository will contain the data layer and that is where you will get the information from.

Finally, the Carga method is the one that will load the datasource of the collection object to the drop-down list

public static void Carga(object coleccion, DropDownList combo, string pDataValueField, string pDataTextField)
{
    try
    {
        combo.Items.Clear();
        combo.DataValueField = pDataValueField;
        combo.DataTextField = pDataTextField;
        combo.DataSource = coleccion;
        combo.DataBind();
        combo.Items.Insert(0, new ListItem("Seleccione Ejemplo", "-1"));
    }
    catch (Exception ex)
    {
        throw new Exception(ex.Message, ex);
    }
}

In the OnSelectedIndexChanged method you must add what you want to do when you select a record. Example:

protected void cboEjemplo_SelectedIndexChanged(object sender, EventArgs e)
{
    txtEjemploNombre.Text = cboEjemplo.SelectedItem.Text; //(el nombre que aparece en pantalla)
    txtEjemploValor.Text = cboEjemplo.SelectedItem.Value; //(el valor que tiene el registro)
}
    
answered by 04.01.2019 / 16:18
source
-1

I do it in the following way, I do not know if it is useful for you but here I am sending it to you, these are examples:

COUNTRIES

IEnumerable<Pais> paises()
    {
        List<Pais> temporal = new List<Pais>();

        SqlCommand cmd = new SqlCommand("Select Idpais, NombrePais from tb_paises", con);

        con.Open();

        SqlDataReader rea = cmd.ExecuteReader();

        while (rea.Read())
        {
            Pais p = new Pais();
            p.Idpais = rea.GetString(0);
            p.NombrePais = rea.GetString(1);

            temporal.Add(p);
        }

        rea.Close();

        con.Close();

        return temporal;
    }

ADD [GET]

public ActionResult Agregar() //Esta es la presentación de la pagina
    {
        //Envío a la pagina la lista de los paises
        ViewBag.paises = new SelectList(paises(), "idpais", "nombrepais");

        //Enviar a la pagina un nuevo Cliente
        return View(new Cliente());
    }

ADD [POST]

[HttpPost]
public ActionResult Agregar(Cliente c)
        {
        ......................

        ViewBag.paises = new SelectList(paises(), "idpais", "nombrepais", c.idpais); //El 4to parametro sirve que se quede seleccionado el ultimo valor que escogí del DropDown al momento de realizar otro "Create"

        return View(c);
    }

VIEW OF ADDING

@using (Html.BeginForm()) 
{
<div class="form-group">
            @Html.LabelFor(model => model.idpais, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("idpais", (SelectList)ViewBag.paises)
            </div>
        </div>
}

You're probably a bit confused but I'll explain, what I do is create a separate method and then call it and fill in the data. The ActionResult "Add" what it does is an insert, but that does not interest us, what matters is the code that is below, in the GET method you see that I am putting a viewBag countries, this viewBag I am sending it to the view with the value "new SelectList (countries ()," idpais "," nombrepais ");", which is a list where the first parameter would be the method that we created, then the second would be the values that are to be sent and the third the values that are going to be shown. When you run it all will be fine, but when you want to send values to the database in the case of a register, we use the POST, in the ActionView Add [POST] what we do is put the same and with a fourth parameter that would be the value that was selected in the GET, remember that in the GET only shows in the "view" and in the POST the data is sent to the database, it would be 2 different views, that is why we put the same. And finally we put the view "@ Html.DropDownList (" idpais ", (SelectList) ViewBag.paises)", this code would be the dropdown and the first parameter would be the id of the selectList that was in the GET and POST, the second parameter would be the ViewBag that we are seeing, also remember that the ViewBag are used to pass data from the controller to the view. And that would be it, if you have questions DO NOT HESITATE TO CONSULT ME. :)

    
answered by 04.01.2019 в 15:56