bind data to checkboxlist - asp.net

I am trying to bind data to checkboxlist and am getting the below Error:
Data source is an invalid type. It must be either an IListSource,
IEnumerable, or IDataSource.
The Code i am using is:
for(var day = fromdate; day.Date <= todate; day = day.AddDays(1))
{
LeaveDtl.DataSource = day;
LeaveDtl.DataBind ();
}

If you want to add individual items in a loop, do it like this:
for (var day = fromdate; day.Date <= todate; day = day.AddDays(1))
{
LeaveDtl.Items.Insert(LeaveDtl.Items.Count, new ListItem(day.ToShortDateString(), day.ToShortDateString()));
}

Related

How to bind gridview with some conditions in asp.net?

DataTable dtbind = new DataTable();
dtbind = objvehicleBAL.GetTaxdetails();
for (int i = 0; i < dtbind.Rows.Count; i++)
{
DateTime dt1 = DateTime.ParseExact(dtbind.Rows[i]["todate"].ToString(), "dd/MM/yyyy", null);
if (dt1 < ((DateTime.Now.AddDays(15))))
{
GVTax.DataSource = dtbind.Rows[i];
GVTax.DataBind();
}
}
I had written my conditions in if(). I want to bind only satisfied rows in grid. How can I write this?
You do not need to bind the Grid in loop on the Row of data table rather filter the DataTable by the condition you want and bind it once. You can get DataView from the data table and use its property DataView.RowFilter to apply the date filter.
dtbind = objvehicleBAL.GetTaxdetails(); //Filter the record in GetTaxdetails
DataView dv = dtbind.DefaultView; //or use DataView with RowFilter
dv .RowFilter = "todate = #" + DateTime.Now.AddDays(15).ToString() + "#";
GVTax.DataSource = dv;
GVTax.DataBind();
DataTable dtbind1 = objvehicleBAL.GetTaxdetails();
DataTable dtbind2 = new DataTable();
foreach (DataRow row in dtbind1.Rows)
{
DateTime dt1 = DateTime.ParseExact(row["todate"].ToString(), "dd/MM/yyyy", null);
if (dt1 < ((DateTime.Now.AddDays(15))))
dtbind2.Rows.Add(row);
}
}
GVTax.DataSource = dtbind2;
GVTax.DataBind();
No need to bind each row and call DataBind mehtod each time.
Just use the following:
protected void BindGrid()
{
DataTable dtbind = new DataTable();
dtbind=objvehicleBAL.GetTaxdetails();//get the rows filtered in SQL
if(dtbind!=null && dtbind.Rows.Count>0)//always check for null for preventing exception
{
GVTax.DataSource = dtbind;
}
GVTax.DataBind();
}
Hope this helps you!
You can use the Select method of DataTable along with a filtering expression, to get the rows which match your criteria. Then, bind it to to your GridView.
string filterExp = "todate < dateadd(day,15,getdate())";
var filtered = dtBind.Select(filterExp);
GVTax.DataSource = filtered ;
GVTax.DataBind();
You can create another datatable and fill the rows satisfying your condition in the second datatable and bind your gridview with second datatable (having filtered rows)
dttableNew = dttableOld.Clone();
foreach (DataRow drtableOld in dttableOld.Rows)
{
if (/*put some Condition */)
{
dtTableNew.ImportRow(drtableOld);
}
}
GVTax.DataSource = dtTableNew;
GVTax.DataBind();

dealing with a null date field

I have a date field on an XPage, this control may contain a date or be blank. In a repeat control I have this code:
var doc:NotesDocument = detailData.getDocument();
var sDate = doc.getItemValue("ACAutoStart");
doc.recycle()
return "Start Date = " + sDate
If ACAutoStart contains a date then it is displayed as [10/10/2013 12:34:15 AM MDT] if it is blank it displays as []. As I understand it the [] indicates that the result is an array but if I try using sDate[0] there is an error. I can't use getItemValueDateTime as it does not like the null return. How do I get this into a simple string value?
Replace your last line with return "Start Date = " + sDate.firstElement().
doc.getItemValue() returns an object of class java.util.Vector. As it is not an Array you get the first element with firstElement() instead of [0] .
UPDATE:
As you mentioned in your comment it has to work also for empty values and you added try:
var sDate = "";
try {sDate = doc.getItemValue("ACAutoStart").firstElement()} catch (e) {};
return "Start Date = " + sDate
...just as another way (returns converted NotesDateTime to Date):
function getJavaDateData(doc:NotesDocument, field:string)
{
var item:NotesItem = doc.getFirstItem(field);
if (item != null){
var dt:NotesDateTime = item.getDateTimeValue();
if (dt != null){
return dt.toJavaDate();
}
}
return null;
}
Off-course need to be adapted for your logic...

DATE BIND IN DROP DOWN LIST

This is Query which i can get all record which is fall between in both dates.
SELECT * FROM tblBooking WHERE
Convert(datetime,'2013-08-20 04:00:00.000') --start date
BETWEEN FromDateWithStartTime AND ToDateWithEndTime
OR Convert(datetime,'2013-08-30 04:00:00.000') --endDate
BETWEEN FromDateWithStartTime AND ToDateWithEndTime
or FromDateWithStartTime BETWEEN Convert(datetime,'2013-08-20 04:00:00.000') --startdate
AND Convert(datetime,'2013-08-30 04:00:00.000') --enddate
or ToDateWithEndTime BETWEEN Convert(datetime,'2013-08-20 04:00:00.000')--start date
AND Convert(datetime,'2013-08-30 04:00:00.000')
and in C# i an fetching start Date and End Date.
FromDateWithStartTime =
Convert.ToDateTime(dt.Rows[0]["Fdate"]).ToString("yyyy/MM/dd
HH:mm:ss");
ToDateWithEndTime = Convert.ToDateTime(dt.Rows[0]["Edate"]).ToString("yyyy/MM/dd
HH:mm:ss");
I want those date which is fall between START DATE AND END DATE.
AND BIND ALL DATES IN THE DRP DOWN LIST.
HOW I CAN DO IT.
you can just iterate through your query with a foreach loop and bind values to your dropdown
foreach (item in queryResults)
{
ddlDate.items.add(item);
}
You can bind dropdown using linq by querying datatable (dtData) you have populated
ddlDate.DataValueField = "date_value";
ddlDepartment.DataTextField = "date_value";
ddlDepartment.DataSource = (from row in dtData.AsEnumerable()
select new { date_value = row["date_Column"].ToString()}).Distinct().ToList();
ddlDate.DataBind();
You can use TimeSpan in C# using that you can get difference between these days. like when you substract one date from another using Date.Substract(AnotherDate) method it will return you Timespan. and you can get number of days between two days like this example:
DateTime StartDate = DateTime.Now;
DateTime EndDate= DateTime.Now.AddMonths(5);
TimeSpan DateDiff = EndDate.Subtract(StartDate);
int Days = DateDiff.Days;
string Date;
for (int i = 1; i <= Days; i++)
{
Date = StartDate.AddDays(double.Parse(i));
}
Try this.

Linq to Entity, selecting group with or without value

Hi Need some help with LINQ query.
I have entity called Shift. This entity has several value field but the ones I am intressted in are ShiftID (int), ShiftDate (DateTime) and GrossMount (decimal(10,2). And this needs to be grouped by month (binding this to a graph in ASP.NET).
I need data for the last 12 months grouped by month.
I have come a bit on the way with this post: Linq to Entity, selecting group without value but not quite all the way.
This is my code for now:
public IQueryable<Shift> GetPastMonths(int months, string accountNumber)
{
_context = new EtaxiEnteties();
var _date = DateTime.Today;
var _firstOfMonth = new DateTime(_date.Year, _date.Month, 31);
var _twelveMonthAgoFirstOfMonth = _firstOfMonth.AddMonths(-12);
// Generate a collection of the months and years for the last 12 months
var _monthYears = Enumerable.Range(-12, 12).Select(monthOffset => { var monthDate = _firstOfMonth.AddMonths(monthOffset); return new { y = monthDate.Year, m = monthDate.Month }; });
var _data = (from _monthYear in _monthYears
join _i in
(from _i in _context.Shifts.Where(acc => acc.Account.AccountNumber == accountNumber)
where _i.ShiftDate >= _twelveMonthAgoFirstOfMonth && _i.ShiftDate < _firstOfMonth
group _i by new { y = _i.ShiftDate.Year, m = _i.ShiftDate.Month } into g
select new { ShiftID = g.Key, GrossAmount = g.Count() }) on _monthYear equals _i.ShiftID into j
from _k in j.DefaultIfEmpty()
select new Shift() { ShiftDate = new DateTime(_monthYear.y, _monthYear.m, 1), GrossAmount = _k != null ? _k.GrossAmount : 0 });
return _data as IQueryable<Shift>;
}
Now I have in return a collection of Shift objects, grouped by month but still missing the GrossAmount. Althoug i would need this from today date (only getting from 1 of current month).
Believe this is my main problem: GrossAmount = g.Count(), but I am not sure
Any LINQ specialist out there that could give me a push?
Use GrossAmount = g.Sum(x => x.GrossAmount) to calculate total GrossAmount value of grouped Shift entities. I believe you have typo in GrossAmount (GrossMount) property name.

Specific row withing a DataTable

I have a data table which has a "Total" column. I want to be able to get a specific rows "Total" not all rows.
public void maxValue()
{
string pass = (String)Session["name"];
DataTable table = (DataTable)Session["CocaCola"];
int total = table.AsEnumerable().Sum(r => r.Field<int>("Total"));
int totalAllowed = table.AsEnumerable().Sum(r => r.Field<Int32>("Total Allowed"));
if (total >= totalAllowed)
{
Label1.Text = "Total value exceeded the maximum of " + totalAllowed;
}
else if (total < totalAllowed)
{
Label1.Text = "Total value which is allowed :" + totalAllowed;
}
if (pass.Equals("Low"))
{
Label1.Text = "You are not allowed any assets at this Stage";
//SNS.Checked = false;
//TT.Checked = false;
//Music.Checked = false;
//SNS.Enabled = false;
//TT.Enabled = false;
//Music.Enabled = false;
}
}
As you can see my method works but add the column up which i dont want to do. How would i go about changing it?
You can do it this way
int yourTargetindex = 0; //Change this to get the value of your target element
int total =(from row in table.AsEnumerable()
select row.Field<int>("Total")).ElementAt(yourTargetindex);
//This will return the first value of "total" in the DataTable
You don't have to use linq. DataTable has built-in methods for this kind of operations:
var selectedTotal = table.Compute("sum(Total)", "columnX == 'x'");
This tell the table to calculate the sum of all Total cells in rows where columnX has the specified value.
Of course you can use linq. You would need to add a Where() before you calculate the sum.

Resources