I made a JavaScript for date of birth, when debugging you choose your day of birth in three drop down boxes. One for days one for months and one for years. I'm working on C# asp.net. The problem is when i click on test(which is submit or confirm) the date is not taken to the database table. It fills empty! Any help would be appreciated..
here's the code:
DateOfBirth.js:
function date_populate(dayfield, monthfield, yearfield)
{
var today = new Date();
var dayfield = document.getElementById(dayfield);
var monthfield = document.getElementById(monthfield);
var yearfield = document.getElementById(yearfield);
for (var i = 0; i < 32; i++)
{
dayfield.options[i] = new Option(i , i + 1)
dayfield.options[today.getDate()] = new Option(today.getDate(), today.getDate(), true, true)
}
for (var m = 0; m < 12; m++)
{
monthfield.options[m] = new Option(monthtext[m], monthtext[m])
monthfield.options[today.getMonth()] = new Option(monthtext[today.getMonth()], monthtext[today.getMonth()], true, true)
}
var thisyear = today.getFullYear()
for (var y = 0; y < 100; y++)
{
yearfield.options[y] = new Option(thisyear, thisyear)
thisyear -= 1
}
yearfield.options[0] = new Option(today.getFullYear(), today.getFullYear(), true, true)
}
Form.asp.cs
protected void Button1_Click(object sender, EventArgs e)
{
String D, M, Y, Full;
D = Day.Value.ToString();
M = Month.Value.ToString();
Y = Year.Value.ToString();
Full = D + "/" + M + "/" + Y;
}
Don't construct dates as strings. Pass them as dates. For example:
DateTime dob = new DateTime(Year.Value, Month.Value, Day.Value);
...
cmd.Parameters.AddWithValue("dob", dob);
where the cmd.CommandText involves #dob when you want to refer to the date of birth.
Format the date 'yyyy-mm-dd' and it will insert.
Are you using a stored procedure?
Change your SP parameter from SqlDbType.NVarChar to SqlDbType.DateTime and then pass the date as a DateTime object to the parameter. You dont need to worry about conversions anymore.
DateTime dateofbirth = new DateTime(Convert.ToInt32(yearfield.SelectedValue),Convert.ToInt32(monthfield.SelectedValue), Convert.ToInt32(dayfield.SelectedValue));
param[0] = new SqlParameter("#DateOfBirth", SqlDbType.DateTime);
param[0].Value = dateofbirth;
Related
Hey guys im using Npgsql and need to pass parameters to my PostgreSQL stored procedure
my stored procedure expecting Date for my first two parameters:
SELECT wpv.avail_pro_failedbattry_error_powerconv(
<date>,
<date>,
<character varying>,
<character varying>,
<character varying>
);
so i need to pass date parameters :
NpgsqlDateTime DateFrom = NpgsqlDateTime.Parse(dtFrom);
NpgsqlDateTime DateTo = NpgsqlDateTime.Parse(dtTo);
NpgsqlParameter p0 = new NpgsqlParameter("#drfrom", dtFrom);
NpgsqlParameter p1 = new NpgsqlParameter("#dtto",dtTo);
NpgsqlParameter p2 = new NpgsqlParameter("#regionalmanager", regionalManager);
NpgsqlParameter p3 = new NpgsqlParameter("#serviceunder", service_under);
NpgsqlParameter p4 = new NpgsqlParameter("#supervisor", supervisor);
var x = _db.dataInGlance.FromSqlRaw(#"SELECT * from wpv.avail_pro_failedbattry_error_powerconv(#drfrom,#dtto,#regionalmanager,#serviceunder,#supervisor)
res (o_availability double precision, o_production double precision,o_numberofturbines integer, o_errors_disabled integer,o_failed_battery integer,o_power integer,o_crew_present text)",p0,p1,p2,p3,p4
).ToList();
dtfrom and dtto are string date format which is:
dtFrom="2020/07/03"
dtTo="2020/07/07"
but it gives me an error on the line
NpgsqlDateTime DateFrom = NpgsqlDateTime.Parse(dtFrom);
that the format is not correct!any help?
Looking at the source:
NpgsqlDateTime
which calls NpgsqlDate
along with Timespan.Parse() which seems mandatory.
Since you are not using a time, you could use NpgsqlDate.Parse() instead.
The source seems to be expecting the following format for date parsing: yyyy-MM-dd
So if you meant the 3rd of July
dtFrom="2020-07-03"
but if you meant the 7th of March
dtFrom="2020-03-07"
Source code:
try {
var idx = str.IndexOf('-');
if (idx == -1) {
throw new FormatException();
}
var year = int.Parse(str.Substring(0, idx));
var idxLast = idx + 1;
if ((idx = str.IndexOf('-', idxLast)) == -1) {
throw new FormatException();
}
var month = int.Parse(str.Substring(idxLast, idx - idxLast));
idxLast = idx + 1;
if ((idx = str.IndexOf(' ', idxLast)) == -1) {
idx = str.Length;
}
var day = int.Parse(str.Substring(idxLast, idx - idxLast));
if (str.Contains("BC")) {
year = -year;
}
return new NpgsqlDate(year, month, day);
} catch (OverflowException) {
throw;
} catch (Exception) {
throw new FormatException();
}
Additionally if NpgsqlDate.Parse is not accepted, you could use NpgsqlDateTime.Parse with the time part set to zero.
NpgsqlDateTime.Parse("2020-07-03 00:00")
I have to add last 18 months to a drop down in asp.net C#.
I have written the logic to get last 18 months as follows.,
List<string> dateList= new List<string>();
private List<string> GetDateDropDownList(DropDown pDropDown)
{
DateTime dt = DateTime.Now;
for (int i = 1; i <= 18; i++)
{
dt = dt.AddMonths(-1);
var month = dt.ToString("MMMM");
var year = dt.Year;
dateList.Add(String.Format("{0}-{1}", month, year));
}
return dateList;
}
now I need to add this list to drop down. I am trying but it is not working. How can I add it to the drop down?
Similar to what others have said, you just bind your function to it.
However, you have a little issue in your code. You create your dateList outside of your actual method, instead of inside of it. You also do not need to pass a dropdown list into the method.
So your updated method should be:
private List<string> GetDateDropDownList()// get rid of parameter
{
List<string> dateList= new List<string>(); // inside method
DateTime dt = DateTime.Now;
for (int i = 1; i <= 18; i++)
{
dt = dt.AddMonths(-1);
var month = dt.ToString("MMMM");
var year = dt.Year;
dateList.Add(String.Format("{0}-{1}", month, year));
}
return dateList;
}
And you bind your dropdown direct to the method
myDropdown.DataSource = GetDateDropDownList();
myDropdown.DataBind();
Alternatively, with your original method you can do the following - notice it's now a void and does not return a list.
private void GetDateDropDownList(DropDown pDropDown)
{
List<string> dateList= new List<string>();
DateTime dt = DateTime.Now;
for (int i = 1; i <= 18; i++)
{
dt = dt.AddMonths(-1);
var month = dt.ToString("MMMM");
var year = dt.Year;
dateList.Add(String.Format("{0}-{1}", month, year));
}
pDropDown.DataSource = dateList;
pDropDown.DataBind()
}
And you would simply pass in your dropdown list
GetDateDropDownList(myDropdownList);
All you're doing in your method is building a list. You never add it to the drop down. Like this...
pDropDown.DataSource = dateList;
pDropDown.DataBind();
You are currently building a list of strings, but in order to make it visible within your dropdown, you'll need to specifically set the DataSource property and then call DataBind() to apply the changes:
// This sets your data
pDropDown.DataSource = dateList;
// This actually binds the current data to the DropDownList control
pDropDown.DataBind();
Additionally, you likely won't need to be returning any values from this method (unless you need them for some other reason) and could consider making it return void:
private void SetDatesForDropDown(DropDown pDropDown, int monthsBack = 18)
{
List<string> dateList= new List<string>();
DateTime dt = DateTime.Now;
for (int i = 1; i <= monthsBack; i++)
{
dt = dt.AddMonths(-1);
dateList.Add(dt.ToString("MMMM-yyyy"));
}
pDropDown.DataSource = dateList;
pDropDown.DataBind();
}
Or simply removing the DropDown parameter and using the results of the method to set your DataSource:
private void GetDateRanges(int monthsBack = 18)
{
List<string> dateList= new List<string>();
DateTime dt = DateTime.Now;
for (int i = 1; i <= monthsBack; i++)
{
dt = dt.AddMonths(-1);
dateList.Add(dt.ToString("MMMM-yyyy"));
}
return dateList;
}
along with:
YourDropDown.DataSource = GetDateRanges();
YourDropDown.DataBind();
There are a number of ways of doing this, below is one such way.
Just remember to bind it to a dropdownlist.
EDITED - Getting the Selected Value
Frontend - ASPX
<asp:DropDownList ID="DropDownList1" runat="server" OnLoad="DropDownList1_Load" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" AutoPostBack="true"></asp:DropDownList>
Codebehind - C#
//Populate the DropDownList
protected void DropDownList1_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Instantiate your DropDownList
DropDownList drpList = (DropDownList)sender;
List<string> dateList = new List<string>();
DateTime dt = DateTime.Now;
for (int i = 1; i <= 18; i++)
{
dt = dt.AddMonths(-1);
var month = dt.ToString("MMMM");
var year = dt.Year;
dateList.Add(String.Format("{0}-{1}", month, year));
}
// Bind resulting list to the DropDownList
drpList.DataSource = dateList;
drpList.DataBind();
}
}
//Get the Selected Value on change
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
// assign the selected item value to a variable
string value = ((DropDownList)sender).SelectedValue;
}
I am trying to fill a ComboBox with the days in the selected month with this
private void cboSelectMonth_SelectedIndexChanged(object sender, EventArgs e)
{
if (cboSelectMonth.SelectedIndex >= 0)
{
int year = Convert.ToInt32(cboSelectYear.SelectedValue);
int month = Convert.ToInt32(cboSelectMonth.SelectedValue);
this.cboSelectDay.DisplayMember = "Text";
this.cboSelectDay.ValueMember = "Value";
int dayCount = DateTime.DaysInMonth(year, month);
var days = new[ dayCount+1 ] { };
for (int i = 1; i < dayCount +1; i++)
{
days[i] = new { Text = Convert.ToString(i), Value = i };
//cboSelectDay.Items.Add(i);
// days[] { new { Text = Convert.ToString(i), Value = i } };
}
this.cboSelectDay.DataSource = days;
DateTime now = DateTime.Now;
int dayValue = now.Day;
cboSelectDay.SelectedIndex = dayValue - 1;
}
}
So I am trying to end up with a ComboBox that lists all days from the current month. For instance, choosing September is going to add 30 days tot the ComboBox and choosing October would give you 31 etc. I am getting two errors. The first is on the var days = new[ dayCount+1 ] { }; line, which says that a ']' is exptected. The second error is on the days[i] = new { Text = Convert.ToString(i), Value = i };line which says Cannot implicitly convert type 'AnonymousType#1' to 'int'
I am trying to do something similar to what I am doing with the Months, which does work (code block below). What am I doing wrong?
private void FillMonthCombobox()
{
this.cboSelectMonth.DisplayMember = "Text";
this.cboSelectMonth.ValueMember = "Value";
var months = new[]
{
new { Text = "January", Value = 1 },
new { Text = "February", Value = 2 },
new { Text = "March", Value = 3 },
new { Text = "April", Value = 4 },
new { Text = "May", Value = 5 },
new { Text = "June", Value = 6 },
new { Text = "July", Value = 7 },
new { Text = "Aughust", Value = 8 },
new { Text = "September", Value = 9 },
new { Text = "October", Value = 10 },
new { Text = "November", Value = 11 },
new { Text = "December", Value = 12 }
};
this.cboSelectMonth.DataSource = months;
DateTime now = DateTime.Now;
int monthValue = now.Month;
cboSelectMonth.SelectedIndex = monthValue - 1;
}
Edit: I can populate the ComboBox now but how do I add the Text = day and the Value = day to the loop so I can reference the Value later? In the case of this loop they will be the same but in the case of some other loops I am working with they will be different. Essentially I want to do the same thing I am doing in the second code block but with a loop.
It's simple, but you have to specify a year, too. Mind February and leap years!
int year = 2015;
int month = 5;
int[] days = Enumerable.Range(1, DateTime.DaysInMonth(year, month)).ToArray();
You can specify it as a DataSource afterwards:
cboSelectDay.DataSource = days;
cboSelectDay.DataBind();
Using your general approach, this does work:
int thisMonthsDays = DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month);
for (int i = 1; i <= thisMonthsDays; i++) { comboBox1.Items.Add(i); }
It fills a comboBox1 with (for May) with 31 days as expected.
Trying to work through and grasp it better, I think this update will help:
First a small class:
public class YearClass
{
public int IndexOfMonth { get; set; }
public string DayName { get; set; }
}
And now additional code to bind the month's days to a comboBox:
List<YearClass> months = new List<YearClass>();
int thisMonthsDays = DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month);
for (int i = 1; i <= thisMonthsDays; i++)
{
YearClass currentDay = new YearClass();
currentDay.IndexOfMonth = i;
DateTime dt = new DateTime(DateTime.Now.Year, DateTime.Now.Month, i);
currentDay.DayName = dt.DayOfWeek.ToString();
months.Add(currentDay);
}
comboBox1.DataSource = months;
comboBox1.DisplayMember = "DayName";
The output then looks like:
you can do this - I am passing hard coded values for year and month
for (int i = 0; i < DateTime.DaysInMonth(2015, 05); i++)
{
cmbMonth.Items.Add(i.ToString());
}
let me know if you have any other requirement
I am having some problem when trying to format DateTime in Asp.net. I wanted the date to display as 18/1//2014 instead of 18/1/2014 12.00 AM. Here is the code:
DataTable dt = new DataTable();
dt.Columns.Add("totalQuantity");
dt.Columns.Add("deliveryDate");
for (int count = 0; count < catSumList.Count; count++)
{
DataRow dr = dt.NewRow();
dr["totalQuantity"] = catSumList[count].productQuantity;
dr["deliveryDate"] = catSumList[count].deliveryDate;
dt.Rows.Add(dr);
}
string[] deliveryDate = new string[dt.Rows.Count];
decimal[] totalQuantity = new decimal[dt.Rows.Count];
for (int i = 0; i < dt.Rows.Count; i++)
{
totalQuantity[i] = Convert.ToInt32(dt.Rows[i][0]);
deliveryDate[i] = dt.Rows[i][1].ToString("dd/M/yyyy", CultureInfo.InvariantCulture);
}
lcCategory.Series.Add(new AjaxControlToolkit.LineChartSeries { Data = totalQuantity });
lcCategory.CategoriesAxis = string.Join(",", deliveryDate);
lcCategory.ChartTitle = string.Format(categoryName);
lcCategory.Visible = true;
However, it gives me an error message at this line:
deliveryDate[i] = dt.Rows[i][1].ToString("dd/M/yyyy", CultureInfo.InvariantCulture);
The error message is No overload method ToString takes 2 arguments. I wonder is there any other way to format it? My data type for deliveryDate in database is DateTime. Thanks in advance.
Since you are working with DataTables which are weakly typed and not recommended to be used you will need to first cast to a DateTime before being able to apply any format:
deliveryDate[i] = ((DateTime)dt.Rows[i][1]).ToString("dd/M/yyyy", CultureInfo.InvariantCulture);
The Rows property returns an object which you need to cast.
Use:
deliveryDate[i] = ((DateTime)dt.Rows[i[1]).
ToString("dd/M/yyyy",CultureInfo.InvariantCulture);
I've found this way, is there any other simplier?
ClienteAdapter cliente = Cache.CacheManager.Get<ClienteAdapter>();
DataTable dt = cliente.GetDataTable();
DateTime dta = DateTime.Today;
String dia = dta.Day.ToString();
if (dta.Day < 10)
dia = '0'+dia;
String mes = dta.Month.ToString();
if (dta.Month < 10)
mes = '0'+mes;
String aniversario = String.Format("{0}-{1}", dia, mes);
dt = cliente.Get(dt, String.Format("WHERE dtNascCli LIKE '%{0}%'", aniversario));
if (dt.Rows.Count>0) {
String aniversariantes = "Aniversariantes do dia:\n";
for (int i = 0; i < dt.Rows.Count; i++)
{
aniversariantes += ((dt.Rows[i]["nmComprador"] != null) : dt.Rows[i]["nmComprador"] ? dt.Rows[i]["nmRazao"]) + "\n";
}
LINQ could get you started.
from DataRow dr in dt.Rows
where ((Date)dr["birthday"]).Month = Date.Today.Month && ((Date)dr["birthday"]).Day = Date.Today.Day
select dr;
That yields an IEnumerable<DataRow>, which you could iterate over with a foreach.
EDIT: Incorporated bemused's comment regarding previous years.
You could simplify this:
DateTime dta = DateTime.Today;
String dia = dta.Day.ToString();
if (dta.Day < 10)
dia = '0'+dia;
String mes = dta.Month.ToString();
if (dta.Month < 10)
mes = '0'+mes;
String aniversario = String.Format("{0}-{1}", dia, mes);
Into this:
String aniversario = DateTime.UtcNow.ToString("dd'-'MM");
// You *are* storing dates in UTC aren't you?
This doesn't change the fact that this isn't a good way to store or search for dates, but its a good place to start.
That's all I got, besides Jim Dagg's LINQ example.