How to make a combo With the days of the month?

Asked

Viewed 922 times

1

What is the best way to make a combobox with the days of the month?

That means the combo has to be from 1 to 31 days.

On the HTML side I have a label called "drpDia", and I need to load this label with numbers from 1 to 31. I know you can do this in Javascript, but I don’t know anything about Javascript, so I was going by C#, where I know more or less that I have to make a list from 1 to 31 and then I have to fill the label "drpDia" with these numbers. correct?

It will be a very important thing to this?

But I’ll have to press the DDA.

int[] numbers = new int[seats];
for (int i = 1; i <= seats; i++)
{
  numbers[i-1] = i;
}
comboBox1.Items.AddRange(numbers);

example:

Only when instead of having the days of the week is to have the days of the month where is Friday becomes 1, Saturday becomes 2 and so on until 31.

inserir a descrição da imagem aqui

  • C# or Javascript?

  • It is in c# to present in back office, the client has to select from 1 to 31 the day he wants

  • 1

    I don’t know what it is back office. It’s to return a SelectList for View, this?

  • Give more details of the requirements, as should be the criterion. Give a context, post the code where it will be used.

  • Right! the goal is to have a combobox to return a selectList

  • 2

    @Ricardogonçalves, you already said that, now tell him what he should be like. We can help, we can make the code for you, which is more than normal, but you need to detail how the code needs to be done. We have no way of guessing. You mean to say what should be in the combobox (or dropdown which I think is what you really want and not a combobox) When should each shape appear, based on what? Post something that is doing for us to see where we will fit what is wanting.

  • I gave an example above, the goal is to create a box where the customer can select day 1, or day 2, or day 3... the box only has to display numbers from 1 to 31 and the customer choose which number he wants.

  • What you’ve codified so far?

  • On the HTML side I have a label called "drpDia", and I need to load this label with numbers from 1 to 31. I know you can do this in Javascript, but I don’t know anything about Javascript, so I was going by C#, where I know more or less that I have to make a list from 1 to 31 and then I have to fill the label "drpDia" with these numbers. correct?

  • 2

    Put all this in the question so people can help you better. It’s about to reopen.

  • edited the question

Show 7 more comments

4 answers

4


Well, I think I understand your question...

Assuming you have the number of the month and a ComboBox empty, we can do this in a few steps :

First : we need to find out how many days are there in the month:

 public static IEnumerable<DateTime> GetDiasNoMes(int mes, int? ano = null)
 {
    ano = ano ?? DateTime.Now.Year;
    return Enumerable.Range(1, DateTime.DaysInMonth(ano, mes))  // Dias: 1, 2 ... 31 etc. É um IEnumerable<int>
                     .Select(dia => new DateTime(ano, mes, dia)) // Mapeia as datas;
 }

According to : we need to popular the ComboBox:

var itens = dataSource.AddRange(GetDiasNoMes(10) //Pega de outubro
                       .Select(data => new SelectListItem
                       {
                           Value = data.Day.ToString(),
                           Text = data.Day.ToString()
                       }); 

comboBox1.Items.Clear(); //Vamos garantir que estaja vazio
comboBox1.Items.AddRange(itens);

Second () : Use jQuery Ajax to update

Controller :

[HttpGet]
public JsonResult Atualizar(int mes)
{
  var itens = GetDiasNoMes(mes) //Pega do mes 
                         .Select(data => data.Day);
  return Json(itens, JsonRequestBehavior.AllowGet);
}

View :

@Html.DropDownList("Mes", String.Empty)
@Html.DropDownList("Dia", null)

<script type="text/javascript">

$(() => {
   $( '#Mes' ).change( function () { //Quando o mês mudar/for selecionado entramos aqui

      let valor = $( this ).val(); //pegamos o valor

      $.ajax({ //Requisição
        url: '@Url.Action("Atualizar","MeuController")',
        data: { mes : valor }, //passamos o parametro para a ação
        success : ( lista ) => { // caso sucesso
           var dias = $( '#Dia' ); //dropdown

           dias.empty(); //limpamos as options

           lista.each( (index, data) => { //foreach
              dias.append( '<option value="' + data + '">' + data + '</option>' ); //adicionamos uma option
           });
        }
      });
   })
})

</script>
  • Thanks for the help!

  • Dear in his first answer the Paramento must be a constant, a common number, pass the method int ano = DateTime.Now.Year will not be accepted, does not compile, the rest is OK!

  • 1

    @Virgilionovic didn’t really notice, I made the whole issue straight in the stackoverflow textarea, thank you.

3

You can do this in two ways:

Adding the 31 days:

List<int> dias = new List<int>();

for (int i = 1; i <= 31; i++)
{
    dias.Add(i);
}

Adding the amount of days of a specific month:

int qtdDias = DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month);

for (int i = 1; i <= qtdDias; i++)
{
    dias.Add(i);
}

Then adding the text on the label in the combobox selectionChanged event:

lblDias.Content = cmbAging.SelectedValue;

Adding the list to the combo:

cmbDias.ItemsSource = dias;

0

Simplest way to fill the combobox with the days of the month and leave the current day selected.

List<int> dias1 = new List<int>();
int diasdomes = DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month);

   /*Preenchendo a lista com os dias do mês atual*/
            for (int i = 1; i <= diasdomes; i++)
            {
                dias1.Add(i);
            }
/*Preenchendo os items da ComboBox*/

            for (int i = 0; i < diasdomes; i++)
            {
                cbVencimento.Items.Insert(i, dias1[i]);
            }

/*Item selecionado da combobox como dia do mês atual*/
    cbVencimento.SelectedItem = DateTime.Today.Day;

0

I ended up doing so, after researching on the net:

  if (string.IsNullOrEmpty(Request["idDiaAmortizacaoCredito"]))
  {
       List<clDays> d = new List<clDays>();
       foreach (int x in Enumerable.Range(1, 31).ToList())                    
           d.Add(new clDays() { day = x });                    
          LoadDropDownList(drpDay, "day", "day", () => d);

          this.lblDay.Visible = this.lblSourceID.Visible = false;
          this.drpDay.Visible = this.drpSourceID.Visible = true;
  }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.