if i use = instead of > in line below
TextBox1.Text = "regdate > '12/12/2012 8:27:09'";
it return me zero rows . Any reason ?
DataView dv1 = new DataView ();
DataSet ds = new DataSet ();
DataTable dt = new DataTable();
/*
col1 col2 col3 col4 col5
1 sw#yahoo.com sw Stephen Walther 12/12/2012 8:27:09 PM
2 as#yahoo.com as Al Stevens 12/12/2012 8:27:09 PM
*/
// Here is the code and criteria for selecting few rows based on datetime .
TextBox1.Text = "regdate > '12/12/2012'";
//connection created
SqlConnection con = new SqlConnection(SqlDataSource1.ConnectionString);
con.Open();
SqlDataAdapter da = new SqlDataAdapter ("SELECT * FROM users",con);
da.Fill (ds);
// filtering criteria applied .
DataRow[] dr = ds.Tables["Table"].Select(TextBox1.Text);
//columns created
dt.Columns.Add("col1", typeof(int));
dt.Columns.Add("col2", typeof(string));
dt.Columns.Add("col3", typeof(string));
dt.Columns.Add("col4", typeof(string));
dt.Columns.Add("col5", typeof(DateTime));
// data added
foreach (DataRow item in dr)
{
dt.Rows.Add(item.ItemArray);
}
// view created
dv1 = dt.DefaultView ;
GridView1.DataSourceID = string.Empty;
GridView1.DataSource = dv1 ;
Page.DataBind();
Because it's a datetime field, so it will compare the whole date and time value, not just the date.
The value 12/12/2012 8:27:09 PM and 12/12/2012 are not the same, because the 12/12/2012 gets expanded to the 12/12/2012 12:00:00 AM value to be comparable to the datetime value. The datetime value doesn't get truncated to be comparable to the date value.
Generally when data types doesn't match for a comparison or calculation, the smaller type gets expanded to the larger type, so that there is no unintentional data loss.
Because the time component is stopping the match - it is trying to match the date AND time.
You could try to use some kind of DATEDIFF function to just match the date portion
How to test two datetimes for equality in T-SQL (ignoring their time components)?
BUT - when amending the code just be really careful with this - not to start putting text box input into the SQL statement. Injection attack risk aplenty.
I think you are OK as it stands but....
The database stores the date in (about) millisecond resolution. When "12/12/2012 8:27:09 PM" is displayed, there is probably a millisecond part that is not displayed, but will throw off a comparison with a date that doesn't specify those milliseconds.
The ">" comparison will succeed because the stored date is higher than your specified date, precisely because of those milliseconds.
Related
I have list of all days in a month (as GridView header) refer to which month is selected by user which then be displayed in GridView.
Display list of Days in a month
Dim dt As New DataTable
Dim col As New DataColumn
dt.Columns.AddRange(New DataColumn(0) {New DataColumn("Date")})
For i As Integer = 1 To gsTotalDD 'gsTotalDD is total of days in a month
dt.Columns.Add(i)
Next
dt.Rows.Add("Status")
gvRptStatus.DataSource = dt
gvRptStatus.DataBind()
I had a table named tblUpload inside the database which storing data that been uploaded together with date of data uploaded.
What I am trying to do is looping through all the header value (list of days) and check either there is day matching with the date of data uploaded. When there is matching value, the status row on the code dt.Rows.Add("Status") will show status done and leave cell empty if no matching days found.
Example : GridView date (fist row), second header column is 1 and check with database has matching value or not. If yes then on (second row) status, at second column will display done.
EDIT
So I came up with checking the matching value like this :
Dim lCnn As New SqlConnection(gsConnString)
Dim lCmd As New SqlCommand
Dim lsCmd As String
Dim dt As New DataTable
Dim newDt As New DataTable
Dim sda As New SqlDataAdapter
Dim dtrow As DataRow = newDt.NewRow()
lCnn.Open()
lCmd.Connection = lCnn
lsCmd = "SELECT DISTINCT DATEPART (d, [date])"
lsCmd &= " FROM dbUpload..tblUpload"
lCmd.CommandText = lsCmd
sda.SelectCommand = lCmd
sda.Fill(newDt)
dt.Columns.AddRange(New DataColumn(0) {New DataColumn("Date")})
For i As Integer = 1 To gsTotalDD 'gsTotalDD is total of days in a month
dt.Columns.Add(i)
value2 = i
For Each col As DataColumn In newDt.Columns
value = newDt.Rows(i - 1).Item(col)
If value = value2 Then
MsgBox("Same value")
End If
Next
Next
By doing this, I manage to check the value but it's not the right way to do it since I wanted to set the status as done if got matching value or leave status empty if vice versa.
Thank you.
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.
I have three select statements,
select 1 from tbl1;
select 2 from tbl2;
select 3 from tbl3;
and in my front end i use a Datatable to retrieve the value from sql.
datatable dt = new datatable(); dt = obj.funcgetval();
gridview.DataSource = dt; gridview.Databind();
I want to select a particular data from the datatable like in a dataset we use ds.tables[0], how can we apply the same in a datatable?
You can use combination of Rows and Columns to read / write particular cell of datatable.
dataTable.Rows[rowsIndex].Column["ColumnName"] = "SomeValue";
string strValue = dataTable.Rows[rowsIndex].Column["ColumnName"].ToString();
To iterate through dataTable
foreach(DataRow row in dt.Rows)
{
string name = row["name"].ToString();
string description = row["description"].ToString();
}
If you want to select any row then use
DataRow dr=dt.Rows[Rowindex];
If you want to get any column value then
object obj=dt.Rows[Rowindex][columnindex];
or
object obj=dt.Rows[Rowindex]["ColumnName"];
This should work for you:
dt.Rows[rowindex]["ColumnName"].ToString();
If you want select specific cell value from Datatable,you can use..
dt.Rows[row index]["Column name"].TOString();
like if you want to select 1st row value from column say Name then use
dt.Rows[1]["Name"].TOString();
if u want select particular row itself you can use Select with filtercondition.
string FilterCond = ur condition;
DataRow[] myrow = dt.Select(FilterCond);
i got a select query that returns one row.
here is my DAL function:
public Test.RequestsDataTable getRequestById2(int rid)
{
RequestsTableAdapter adapter2 = new RequestsTableAdapter();
Test.RequestsDataTable dt2 = adapter2.GetData(rid);
return (dt2);
}
Test.xsd is tableAdapter.
my question is how do i call it from code behind file and get each cell value and store it in textbox.
It's a method. Call it.
It returns a Test.RequestsDataTable. If your table has columns Column1 and Column2, then you can do:
var dt = getRequestById2(123);
string col1 = dt.Column1;
int col2 = dt.Column2;
If that doesn't answer your question, then you need to be more clear in your question.
i wrote it in cs file:
Test.RequestsDataTable rdt = new DalObj().getRequestById2(111);
rdt.Columns[0] -> returns DataColumn so i defined
DataColumn c1 = rdt.Columns[0];
but i get the column name and not it's value.
I have a dropdownlist that displays time. For example 8:00AM or 8:30AM.
When I save this time to database, I want to save as todays date + time.
eg: 8:00AM as 03/30/2009 8:00:00:000. Can anybody give appropriate code to convert as shown above?
I tried
Convert.ToDateTime(ddlStartTime.SelectedItem.Text)
But there is an error stating "String was not recognized as a valid DateTime."
VB.NET answer for Portmans Solution. Too many chars for comment so included here.
Dim time As String() = Me.DropDownList1.SelectedValue.Split(New Char() {":", " "})
Dim hours As Integer = Integer.Parse(time(0))
Dim minutes As Integer = Integer.Parse(time(1))
Dim ampm As Integer = 12
If time(2).ToLower() = "am" Then
ampm = 0
End If
Dim dt As DateTime = DateTime.Today.AddHours(hours + ampm).AddMinutes(minutes)
Have a look at DateTime.TryParse and DateTime.Today. Using them should be enough to do what you want.
Untested Code.
DateTime dt;
if (DateTime.TryParse(Dropdown1.SelectedValue, out dt))
{
DateTime result = DateTime.Today.AddHours(dt.Hour).AddMinutes(dt.Minute);
}
Basically, you just need to parse the time string. It will be automatically resolved to the current date.
Dim strTime As String = "8.30am"
Dim parsedTime As DateTime
If DateTime.TryParseExact(strTime, "h.mmtt", New System.Globalization.DateTimeFormatInfo(), Globalization.DateTimeStyles.None, parsedTime) = True Then
'Parse was successful.
Else
'Handle the error.
End If
Store as the value for each drop down item the number of minutes from midnight that the time represents. Then:-
valueToStore = DateTime.Today + TimeSpan.FromMinutes(Int32.Parse(value))
By storing using the value attribute of a HTML option to store a simple representation of the value you eliminate the codes dependancy on the actual format used to simply display the set of values. If it decided that the representation of the times be changed to use different format the rest of the code will continue to work unmodified.
var time = this.DropDownList1.SelectedValue.Split(':', ' ');
var hours = Int32.Parse(time[0]);
var minutes = Int32.Parse(time[1]);
var ampm = (time[2] == "PM") ? 12 : 0;
var dt = DateTime.Today.AddHours(hours + ampm).AddMinutes(minutes);
Parse your DropDownList for Hours and Minutes, then add them to DateTime.Today.
Read the parts of the time so you have hours and minutes, then use the following code:
DateTime myDate = DateTime.Now.Date;
myDate = myDate.AddHours(hours);
myDate = myDate.AddMinutes(minutes);
Use ParseExact so that you can specify the format that you are using.
h = hours in 12-hour clock format
. = literal character
mm = minutes as two digits
tt = AM/PM designator
Dim time As DateTime = DateTime.ParseExact(dropdown.SelectedValue, "h.mmtt", CultureInfo.InvariantCulture)
The components of the DateTime value that you don't specify in the string (year, month, date, seconds, time zone, era) uses DateTime.Today as default, which is exactly what you want in this case.
This always seems to work for me. May not be the most elegant way, but I have not had any issues so far.
dTime = DateTime.Now;
string time = this.DropDownList1.SelectedValue;
DateTime FormattedDateTime = Convert.ToDateTime(dTime.Date.ToShortDateString() +
" " + time);