Fill combo by an array on a web form in c # .net

2019-07-15 23:12发布

问题:

I have four variables of Long DateTime type, I want to fill combo with the help of these four values on a web page (using c sharp), The combo should show the name of Month of corresponding datetime variable, How can ido that?

回答1:

You can also use a Datatable for this purpose. Simply say,

 ddlName.DataSource = dataableName;

 ddl.DataValueField = "ColumnName";

 ddl.DataTextField = "ColumnName"; 

Store the desired Values in respective columns and simply write their names against text or value fields.



回答2:

It sounds like you are trying to populate the combobox at runtime on your ASP.NET page in an unbound manner. If this is the case, you would use the following code:

yourCombo.Items.Add(date1.ToString("MMMM"));
yourCombo.Items.Add(date2.ToString("MMMM"));
yourCombo.Items.Add(date3.ToString("MMMM"));
yourCombo.Items.Add(date4.ToString("MMMM"));

This will show your four variables in the combobox with their full month name.



回答3:

Action<DateTime> addItem = dateTime => 
    dropDownList.Items.Add(new ListItem(dateTime.ToString("MMMM"), dateTime.ToString("O")));

addItem(dateTime1);
addItem(dateTime2);
addItem(dateTime3);
addItem(dateTime4);

or just add a mentod

private void AddItem(DateTime dateTime)
{
    dropDownList.Items.Add(new ListItem(dateTime.ToString("MMMM"), dateTime.ToString("O")));
}

protected void Page_Load(object sender, EventArgs e)
{
    AddItem(dateTime1);
    AddItem(dateTime2);
    AddItem(dateTime3);
    AddItem(dateTime4);
}