Search code examples
c#asp.net-mvcc#-4.0genericsgeneric-collections

Creating Custom Generic List in C#


Hello Friends i wanna create custom generic list my code is as follows :

public class Dates
{
    string _FromDate;
    string _ToDate;

    public string FromDate
    {
        get { return _FromDate; }
        set { _FromDate = value; }
    }

    public string ToDate
    {
        get { return _ToDate; }
        set { _ToDate = value; }
    }
}

protected void btnsearch_Click(object sender, EventArgs e)
{

    DateTime start = new DateTime(2013,1,5);
    DateTime end = new DateTime(2013,2,2);

    string dayName = drpday.SelectedItem.ToString().ToLower();

     Dates dt = new Dates();
    List<Dates> list = new List<Dates>();
    int i = 0;

   for (DateTime runDate = start; runDate <= end; runDate = runDate.AddDays(1))
    {
        if (runDate.DayOfWeek.ToString().ToLower() == dayName)
        {
            dt.FromDate = runDate.ToShortDateString();
            dt.ToDate = (runDate.AddDays(double.Parse(hd_tourdays.Value)).ToShortDateString());
            list.Insert(i++,dt);
        }
    }
     grd_TourDates.DataSource = list;
     grd_TourDates.DataBind();
 }

in my resultant list , it only shows last item added in loop please help solve the problem..


Solution

  • Try This :----

    protected void btnsearch_Click(object sender, EventArgs e)
        {
    
            DateTime start = new DateTime(2013,1,5);
            DateTime end = new DateTime(2013,2,2);
    
            string dayName = drpday.SelectedItem.ToString().ToLower();
    
             Dates dt = new Dates();
            List<Dates> list = new List<Dates>();
            int i = 0;
    
           for (DateTime runDate = start; runDate <= end; runDate = runDate.AddDays(1))
            {
                if (runDate.DayOfWeek.ToString().ToLower() == dayName)
                {
    
                    list.Add(new Dates{
                          FromDate=runDate.ToShortDateString();
                          ToDate=(runDate.AddDays(double.Parse(hd_tourdays.Value)).ToShortDateString());
        });
    
                }
            }
             grd_TourDates.DataSource = list;
             grd_TourDates.DataBind();
         }