Adeel Aslam
Adeel Aslam

Reputation: 1294

html Select List add values with c#

I have following manual code to open the URLs:

<select type="text" name="sel_veh" id="Select1" runat="server"  onchange="window.open('http://appsrv01.shakarganj.com.pk:7778/reports/rwservlet?reptest&report=eth_fleet_dtl&veh_num='+ sel_veh.value,'mywindow4');" language="javascript" onclick="return sel_veh_onclick()" style="font-size: 10pt">
    <option value="">Please Select</option>
    <option value="01-01-12">01-Jan</option>
    <option value="01-02-12">02-Jan</option>
    <option value="01-02-12">03-Jan</option>
    <option value="01-02-12">04-Jan</option>
</select>

I have this select list with hard-coded date values. The problem is that when date changes, I have to update the code with new dates. Is there any way in C# that I can add values to this select list by c3 code dynamically that date values should auto change with system date?

Upvotes: 2

Views: 15685

Answers (2)

Shai
Shai

Reputation: 25619

Yes, you can. if you're looking into a more coder-friendly control, use the DropDownList control

if you're using a <select />, you can add items by

Select1.Items.Add("01-01-12","01-Jan");

for example

if you're using a DropDownList, you can add items by

dropDownList1.Items.Add(new ListItem("01-Jan", "01-01-12"));

Upvotes: 3

Shadow Wizard
Shadow Wizard

Reputation: 66388

First, as Shai correctly said use DropDownList control instead:

 <asp:DropDownList ID="ddlDates" runat="server"></asp:DropDownList>

Now populate it from code behind with such code:

DateTime now = DateTime.Now;
DateTime past = now.AddDays(-7);
List<DateTime> dates = new List<DateTime>();
for (DateTime curDate = past; curDate <= now; curDate = curDate.AddDays(1))
    dates.Add(curDate);
ddlDates.Attributes["onchange"] = "window.open('http://appsrv01.shakarganj.com.pk:7778/reports/rwservlet?reptest&report=eth_fleet_dtl&veh_num='+ this.value, 'mywindow4');";
ddlDates.Attributes["onclick"] = "return sel_veh_onclick();";
ddlDates.Items.Clear();
ddlDates.Items.Add(new ListItem("Please Select", ""));
ddlDates.Items.AddRange(dates.ConvertAll(dt => new ListItem(dt.ToString("dd-MMM"), dt.ToString("MM-dd-yy"))).ToArray());

Upvotes: 0

Related Questions