2013-12-04 3 views
0

hye, у меня проблема, когда, когда я хочу получить данные на дату «4/12/2013 2:00», я получу ошибку, Конверсия не удалась при преобразовании даты и/или времени с символа строка. но если я буду искать дату «24/11/2013 16:00», я смогу получить данные. есть ли что-то не так с моим кодом, так как я уже создал код, для которого он должен был принять одну дату в первом коде, показанном ниже.Ошибка преобразования была выполнена при преобразовании даты и/или времени из символьной строки. при попытке генерировать gridview

if (Dayrange.Checked == true) 
    { 
     if (txtStart1.Text.Length == 10) 
     { 
      startdate = DateTime.ParseExact(txtStart1.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture); 
     } 
     else if (txtStart1.Text.Length == 9) 
     { 
      try 
      { 
       startdate = DateTime.ParseExact(txtStart1.Text, "%d/MM/yyyy", CultureInfo.InvariantCulture); 
      } 
      catch (FormatException e) 
      { 
       startdate = DateTime.ParseExact(txtStart1.Text, "dd/%M/yyyy", CultureInfo.InvariantCulture); 
      } 
     } 
     else if (txtStart1.Text.Length == 8) 
     { 
      startdate = DateTime.ParseExact(txtStart1.Text, "%d/%M/yyyy", CultureInfo.InvariantCulture); 
     } 

     //check enddate 
     if (txtEnd1.Text.Length == 10) 
     { 
      enddate = DateTime.ParseExact(txtEnd1.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture); 
     } 
     else if (txtEnd1.Text.Length == 9) 
     { 
      try 
      { 
       enddate = DateTime.ParseExact(txtEnd1.Text, "%d/MM/yyyy", CultureInfo.InvariantCulture); 
      } 
      catch (FormatException e) 
      { 
       enddate = DateTime.ParseExact(txtEnd1.Text, "dd/%M/yyyy", CultureInfo.InvariantCulture); 
      } 

     } 
     else if (txtEnd1.Text.Length == 8) 
     { 
      enddate = DateTime.ParseExact(txtEnd1.Text, "%d/%M/yyyy", CultureInfo.InvariantCulture); 
     } 

     //check starttime format 
     if (txtStart2.Text.Length == 1) 
     { 
      starttime = DateTime.ParseExact(txtStart2.Text, "%H", CultureInfo.InvariantCulture); 
     } 
     else if (txtStart2.Text.Length == 2) 
     { 
      starttime = DateTime.ParseExact(txtStart2.Text, "HH", CultureInfo.InvariantCulture); 
     } 
     //check endtime format 
     if (txtEnd2.Text.Length == 1) 
     { 
      endtime = DateTime.ParseExact(txtEnd2.Text, "%H", CultureInfo.InvariantCulture); 
     } 
     else if (txtEnd2.Text.Length == 2) 
     { 
      endtime = DateTime.ParseExact(txtEnd2.Text, "HH", CultureInfo.InvariantCulture); 
     } 

     Label1.Text = startdate.ToShortDateString(); 
     Label2.Text = enddate.ToShortDateString(); 
     Label3.Text = starttime.ToShortTimeString(); 
     Label4.Text = endtime.ToShortTimeString(); 
     Label5.Text = startdate.ToShortDateString() + " " + starttime.ToShortTimeString(); 
     Label6.Text = enddate.ToShortDateString() + " " + endtime.ToShortTimeString(); 
     Label7.Text = Label5.Text.Length.ToString(); 
     Label8.Text = Label6.Text.Length.ToString(); 

     if (Label5.Text.Length == 16) 
     { 
      combdatetime1 = DateTime.ParseExact(Label5.Text, "dd/MM/yyyy HH:mm", CultureInfo.InvariantCulture); 
     } 
     else if (Label5.Text.Length == 15) 
     { 
      combdatetime1 = DateTime.ParseExact(Label5.Text, "dd/MM/yyyy %H:mm", CultureInfo.InvariantCulture); 
     } 

     if (Label6.Text.Length == 16) 
     { 
      combdatetime2 = DateTime.ParseExact(Label6.Text, "dd/MM/yyyy HH:mm", CultureInfo.InvariantCulture); 
     } 
     else if (Label6.Text.Length == 15) 
     { 
      combdatetime2 = DateTime.ParseExact(Label6.Text, "dd/MM/yyyy %H:mm", CultureInfo.InvariantCulture); 
     } 

     Label9.Text = combdatetime1.ToString(); 
     Label10.Text = combdatetime2.ToShortDateString(); 
    } 

вот код для привязки данных к gridview.

if ((Byday.Checked == true) || (Dayrange.Checked == true)) 
    { 
     if (((Maxdata.Checked == true) && (curdata.Checked == true)) && ((txtStart2.Text.Length == 0) && (txtEnd2.Text.Length == 0))) 
     { 
      gridmaxdata.Visible = true; 
      lblmaxdata.Visible = true; 
      lblcurdata.Visible = true; 
      gridcurdata.Visible = true; 
      lblmaxdata.Text = "Highest Data"; 
      lblcurdata.Text = "Current Data"; 
      // ConnectionString to NorthWind Database. 
      string connectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\shafiq\\Desktop\\history\\App_Data\\Radiation.mdf;Integrated Security=True;User Instance=True"; 

      // Create SQLDataSource. 
      SqlDataSource sqlDataSource = new SqlDataSource(); 
      sqlDataSource.ID = "SqlDataSource123"; 
      this.Page.Controls.Add(sqlDataSource); 

      // Bind ConnectionString to SQLDataSource. 
      sqlDataSource.ConnectionString = connectionString; 
      // Retrieve records with only 5 Columns from Employees table of NorthWind Database. 
      sqlDataSource.SelectCommand = "SELECT top 30 [date], [data] FROM [loc1] WHERE (([data] >= '2') AND ([date] >= '" + startdate.ToLongDateString() + "') AND ([date] < '" + enddate.ToLongDateString() + "')) ORDER BY [data] DESC, [date] DESC"; 

      // Bind SQLDataSource to GridView after retrieving the records. 
      gridmaxdata.DataSource = sqlDataSource; 
      gridmaxdata.DataBind(); 

      // Create SQLDataSource. 
      SqlDataSource sqlDataSource2 = new SqlDataSource(); 
      sqlDataSource2.ID = "SqlDataSource12"; 
      this.Page.Controls.Add(sqlDataSource2); 

      // Bind ConnectionString to SQLDataSource. 
      sqlDataSource2.ConnectionString = connectionString; 
      // Retrieve records with only 5 Columns from Employees table of NorthWind Database. 
      sqlDataSource2.SelectCommand = "SELECT [date], [data] FROM [loc1] WHERE (([date] >= '" + startdate.ToLongDateString() + "') AND ([date] < '" + enddate.ToLongDateString() + "')) ORDER BY [data] DESC, [date] DESC"; 

      // Bind SQLDataSource to GridView after retrieving the records. 
      gridcurdata.DataSource = sqlDataSource2; 
      gridcurdata.DataBind(); 
     } 
     else if (((Maxdata.Checked == true) && (curdata.Checked == true)) && ((txtStart2.Text.Length > 0) && (txtEnd2.Text.Length > 0))) 
     { 
      gridmaxdata.Visible = true; 
      lblmaxdata.Visible = true; 
      lblcurdata.Visible = true; 
      gridcurdata.Visible = true; 
      lblmaxdata.Text = "Highest Data"; 
      lblcurdata.Text = "Current Data"; 
      // ConnectionString to NorthWind Database. 
      string connectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\shafiq\\Desktop\\history\\App_Data\\Radiation.mdf;Integrated Security=True;User Instance=True"; 

      // Create SQLDataSource. 
      SqlDataSource sqlDataSource = new SqlDataSource(); 
      sqlDataSource.ID = "SqlDataSource123"; 
      this.Page.Controls.Add(sqlDataSource); 

      // Bind ConnectionString to SQLDataSource. 
      sqlDataSource.ConnectionString = connectionString; 
      // Retrieve records with only 5 Columns from Employees table of NorthWind Database. 
      sqlDataSource.SelectCommand = "SELECT top 30 [date], [data] FROM [loc1] WHERE (([data] >= '2') AND ([date] >= '" + combdatetime1.ToLongDateString() + "') AND ([date] < '" + combdatetime2.ToLongDateString()+ "')) ORDER BY [data] DESC, [date] DESC"; 

      // Bind SQLDataSource to GridView after retrieving the records. 
      gridmaxdata.DataSource = sqlDataSource; 
      gridmaxdata.DataBind(); 

      // Create SQLDataSource. 
      SqlDataSource sqlDataSource2 = new SqlDataSource(); 
      sqlDataSource2.ID = "SqlDataSource12"; 
      this.Page.Controls.Add(sqlDataSource2); 

      // Bind ConnectionString to SQLDataSource. 
      sqlDataSource2.ConnectionString = connectionString; 
      // Retrieve records with only 5 Columns from Employees table of NorthWind Database. 
      sqlDataSource2.SelectCommand = "SELECT [date], [data] FROM [loc1] WHERE (([date] >= '" + combdatetime1.ToLongDateString() + "') AND ([date] < '" + combdatetime2.ToLongDateString() + "')) ORDER BY [data] DESC, [date] DESC"; 

      // Bind SQLDataSource to GridView after retrieving the records. 
      gridcurdata.DataSource = sqlDataSource2; 
      gridcurdata.DataBind(); 
     } 

ответ

0

удалить % в строках формата

, если вам нужно разрешить один день, то изменить ниже

"%d/MM/yyyy" 

в

"d/MM/yyyy" 

Если вход может быть несколько форматов использовать ниже перегрузки TryParseExact

DateTime dateValue;  
var formatStrings = new string[] { "dd/MM/yyyy", "d/MM/yyyy", "dd/M/yyyy", "d/M/yyyy" }; 
    if (DateTime.TryParseExact(dt, formatStrings, txtStart1.Text, DateTimeStyles.None, out dateValue)) 
     startdate =dateValue; 

когда ввод времени преобразования вы можете просто преобразовать его, как показано ниже

Label4.Text = string.Format("{0}:00:00",txtEnd2.Text); 

вы можете проверить длину и преобразовать в целое значение, для проверки достоверности входных данных.

но мне интересно, почему все эти текстовые поля для начала даты начала и окончания даты? Я бы использовал Timepicker с jQuery UI Datepicker.

http://trentrichardson.com/examples/timepicker/

+0

ли я двигаться% от всего кода или просто несколько ?? потому что я использовал%, чтобы убедиться, что пользователь, который вводит один вход (например, 1), по-прежнему будет приемлемым в качестве даты/времени. – newbie88

+0

yes удалить со всех мест – Damith

+0

У меня есть попытка удалить% для всех стартовых и конечных, но все же безрезультатно. если я удалю с момента времени% H, приложение не распознает его как формат даты и времени для времени. – newbie88

Смежные вопросы

 Смежные вопросы