Ошибка времени выполнения input string was not in a correct format

eromerom

0 / 0 / 0

Регистрация: 12.02.2020

Сообщений: 2

1

12.02.2020, 12:31. Показов 4061. Ответов 2

Метки паскаль abc.net (Все метки)


Студворк — интернет-сервис помощи студентам

Добрый день! Не могу понять, в чем ошибка(
Пишет: спорт.pas(44) : Ошибка времени выполнения: Input string was not in a correct format.
Буду очень рада Вашей помощи

Pascal
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
type perepis=record
  name:string[45];
  imya:string[45];
  god:integer;
  zanyatie:string[45];
  let:integer;
end;
var p:perepis;
   f8,r8:text;
   c:char;
begin
assign(f8,'C:UsersUserDesktopinput8.txt');
reset(f8);
assign(r8,'C:UsersUserDesktopr8.txt');
rewrite(r8);
writeln;
readln(f8);
writeln(r8,' Фамилия:      Имя:          Возраст:       Лет_посвящено:');
writeln('    Фамилия:      Имя:      Возраст:       Занятие:      Лет_посвящено:');
   while not eof(f8) do
   begin
   p.name:='';
   repeat
       read(f8,c);
       p.name:=p.name+c
   until c=' ';
 
  repeat read (f8,c); until c<>' ';
   p.imya:=c;
   repeat
       read(f8,c);
       p.imya:=p.imya+c
   until c=' ';
   
   readln(f8,p.god);
 
    repeat read (f8,c); until c<>' ';
   p.zanyatie:=c;
   repeat
       read(f8,c);
       p.zanyatie:=p.zanyatie+c
   until c=' ';
   
   readln(f8,p.let);
   
   if p.zanyatie='плавание '
     then begin
      write(p.name:15);
      write(p.imya:10);
      writeln(p.god:10);
      write(p.zanyatie:10);
      writeln(p.let:10);
      write(r8,'  ',p.name:10);
      writeln(r8,p.imya:10);
      writeln(r8,p.god:10);
      writeln(r8,p.let:10);
      end;
   end;
close(f8);  close(r8);
end.

Фамилия Имя Возраст Занятие Лет_посвящено
Петров Иван 20 плавание 15
Сидорова Алена 15 дайвинг 3
Ненашева Татьяна 22 плавание 15
Степанова Кристина 10 прыжки в воду 6

Вложения

Тип файла: txt input8.txt (347 байт, 4 просмотров)



0



mr-Crocodile

2909 / 1558 / 625

Регистрация: 19.03.2019

Сообщений: 5,158

12.02.2020, 14:11

2

Лучший ответ Сообщение было отмечено eromerom как решение

Решение

в строке 35 замени ReadLn на Read:

Pascal
1
    read(f8, p.god);

но проблема в другом.
ты выбрала очень странный алгоритм чтения — разделяешь поля ввода по пробелам.
и всё бы хорошо, НО в последней строке «Степанова Кристина 10 прыжки в воду 6»
в p.zanyatie попадает всё до первого пробела.
Это слово «прыжки».
а потом ты пытаешься через

Pascal
1
readln(f8, p.let)

прочитать туда строку «в» и у Паскаля это не выходит.

я бы поменял процедуру чтения. Раз у тебя текст по столбцам, то там заданная ширина на каждое поле.
поэтому читай один раз в строку через ReadLn(f8, s) а потом через Copy(s, .., ..) забирай нужное значение в каждое поле.



1



JuriiMW

5061 / 2634 / 2347

Регистрация: 10.12.2014

Сообщений: 10,000

13.02.2020, 04:28

3

А не проще ли читать строку целиком и парсить её по правилам:
→ первые два слова — это фамилия и имя
→ третье — возраст
→ начиная с четвёртого до предпоследнего — вид спорта
→ последнее — число лет

Pascal
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
type perepis=record
  name:string[45];
  imya:string[45];
  god:integer;
  zanyatie:string[45];
  let:integer;
end;
 
function parse(s : String) : perepis;
begin
  var w := s.ToWords;
  Result.name := w[0];
  Result.imya := w[1];
  Result.god  := StrToInt(w[2]);
  Result.zanyatie := w[3:w.Length-1].JoinIntoString;
  Result.let := StrToInt(w.Last);
end;
 
function perepisToStr(p : perepis) :=
  $'{p.name,-10} {p.imya,-10} {p.god,2} {p.zanyatie,-15} {p.let,2}';
 
begin
  var a := ReadAllLines('input8.txt');
  for var i := 1 to a.Length-1 do
    begin
      //a[i].Println;
      var p := parse(a[i]);
      if p.zanyatie = 'плавание' then
        perepisToStr(p).PrintLn;
    end;
end.



1



I had trouble doing something like this myself not too long ago. There are a couple of things here that need to be modified in your format string.

  1. Since the TimeSpan type refers to hours in the time passage sense and not the hour-of-day sense (even though, yes, it is used to show the time of day as well), you want lowercase hs. Uppercase means 24-hour clock, and that’s irrelevant when you don’t have the concept of AM and PM, which TimeSpans don’t.
  2. You need to escape the colon to make it persist through the parse as a literal.

Given that, you can do this instead:

TimeSpan newEventStartTime = TimeSpan.ParseExact(Start_Time, @"hh:mm", CultureInfo.InvariantCulture);

You can review the Custom TimeSpan Format Strings MSDN page if you need help past this, but I definitely agree that this isn’t the best-documented or easiest to overcome bug in the world.


This is most likely irrelevant to you, but I’m including it just in good practice. That’s only if you really want to preserve that exact format string. If you’re okay being a little more lenient, you could use the "c" format-designator instead. That allows for more details to be preserved from an incoming string. The choice between those options is really just up to you and the circumstances in which you’re hoping to use this. But again, since you even thought to use ParseExact over Parse in the first place, I suspect the example I gave above with @"hh:mm" is what you’re looking for.

eromerom

0 / 0 / 0

Регистрация: 12.02.2020

Сообщений: 2

1

12.02.2020, 12:31. Показов 3723. Ответов 2

Метки паскаль abc.net (Все метки)


Добрый день! Не могу понять, в чем ошибка(
Пишет: спорт.pas(44) : Ошибка времени выполнения: Input string was not in a correct format.
Буду очень рада Вашей помощи

Pascal
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
type perepis=record
  name:string[45];
  imya:string[45];
  god:integer;
  zanyatie:string[45];
  let:integer;
end;
var p:perepis;
   f8,r8:text;
   c:char;
begin
assign(f8,'C:UsersUserDesktopinput8.txt');
reset(f8);
assign(r8,'C:UsersUserDesktopr8.txt');
rewrite(r8);
writeln;
readln(f8);
writeln(r8,' Фамилия:      Имя:          Возраст:       Лет_посвящено:');
writeln('    Фамилия:      Имя:      Возраст:       Занятие:      Лет_посвящено:');
   while not eof(f8) do
   begin
   p.name:='';
   repeat
       read(f8,c);
       p.name:=p.name+c
   until c=' ';
 
  repeat read (f8,c); until c<>' ';
   p.imya:=c;
   repeat
       read(f8,c);
       p.imya:=p.imya+c
   until c=' ';
   
   readln(f8,p.god);
 
    repeat read (f8,c); until c<>' ';
   p.zanyatie:=c;
   repeat
       read(f8,c);
       p.zanyatie:=p.zanyatie+c
   until c=' ';
   
   readln(f8,p.let);
   
   if p.zanyatie='плавание '
     then begin
      write(p.name:15);
      write(p.imya:10);
      writeln(p.god:10);
      write(p.zanyatie:10);
      writeln(p.let:10);
      write(r8,'  ',p.name:10);
      writeln(r8,p.imya:10);
      writeln(r8,p.god:10);
      writeln(r8,p.let:10);
      end;
   end;
close(f8);  close(r8);
end.

Фамилия Имя Возраст Занятие Лет_посвящено
Петров Иван 20 плавание 15
Сидорова Алена 15 дайвинг 3
Ненашева Татьяна 22 плавание 15
Степанова Кристина 10 прыжки в воду 6

Вложения

Тип файла: txt input8.txt (347 байт, 4 просмотров)

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь

0

mr-Crocodile

2801 / 1480 / 594

Регистрация: 19.03.2019

Сообщений: 4,904

12.02.2020, 14:11

2

Лучший ответ Сообщение было отмечено eromerom как решение

Решение

в строке 35 замени ReadLn на Read:

Pascal
1
    read(f8, p.god);

но проблема в другом.
ты выбрала очень странный алгоритм чтения — разделяешь поля ввода по пробелам.
и всё бы хорошо, НО в последней строке «Степанова Кристина 10 прыжки в воду 6»
в p.zanyatie попадает всё до первого пробела.
Это слово «прыжки».
а потом ты пытаешься через

Pascal
1
readln(f8, p.let)

прочитать туда строку «в» и у Паскаля это не выходит.

я бы поменял процедуру чтения. Раз у тебя текст по столбцам, то там заданная ширина на каждое поле.
поэтому читай один раз в строку через ReadLn(f8, s) а потом через Copy(s, .., ..) забирай нужное значение в каждое поле.

1

JuriiMW

5017 / 2605 / 2331

Регистрация: 10.12.2014

Сообщений: 9,920

13.02.2020, 04:28

3

А не проще ли читать строку целиком и парсить её по правилам:
→ первые два слова — это фамилия и имя
→ третье — возраст
→ начиная с четвёртого до предпоследнего — вид спорта
→ последнее — число лет

Pascal
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
type perepis=record
  name:string[45];
  imya:string[45];
  god:integer;
  zanyatie:string[45];
  let:integer;
end;
 
function parse(s : String) : perepis;
begin
  var w := s.ToWords;
  Result.name := w[0];
  Result.imya := w[1];
  Result.god  := StrToInt(w[2]);
  Result.zanyatie := w[3:w.Length-1].JoinIntoString;
  Result.let := StrToInt(w.Last);
end;
 
function perepisToStr(p : perepis) :=
  $'{p.name,-10} {p.imya,-10} {p.god,2} {p.zanyatie,-15} {p.let,2}';
 
begin
  var a := ReadAllLines('input8.txt');
  for var i := 1 to a.Length-1 do
    begin
      //a[i].Println;
      var p := parse(a[i]);
      if p.zanyatie = 'плавание' then
        perepisToStr(p).PrintLn;
    end;
end.

1

What

String cmd = String.Format(data, id.toString(), newData);  

does is: trying to format the String data , using just 2 strings..not 22!!
Which ones?…1)id.ToString() and 2)newData.ToString()
Thats obviously wrong

How you can see that this is the problem…? Leave just {0} and {1} in data string and print it.It compiles ok and see what you get.
Of course you have to use {{ instead of { where you want a string literal

Fully working Solution:

int id = 112;

String[] newData = { id.ToString(),"1", "2", "21", "reidb", "reidb", "reidb", "reidb", "aa", 
                  "Some description", "11", "2012-02-28", "2012-01-29", "true", "1", "1", 
                  "true", "note note note", "true", "1", "2011-12-03", "45"};

String data = "{{ cmd: "save magellan deal", data: {{ id: {0} , AId: {1}, " +
                    "CId: {2}, CCId:{3}, LA: "{4}", BA: "{5}" , " +
                    "LSA: "{6}" , BSA: "{7}" , "path: "{8}"," +
                    "dscp: "{9}", SI: "{10}", CD: "{11}", " +
                    "period: "{12}", IsStatic: {13}, LSD: {14}, LC: {15}, RB: {16},}} " +
                    "Notes: "{17}", IsEE: {18}, RBy: {19}, DPDD: "{20}", LId: {21} }} }}";


String cmd = String.Format(data, newData);

Input string was not in a correct format errorThe input string was not in a correct format error might occur when you try to convert a non-numeric string from the input into an int. Moreover, you’ll get the said error while storing the input values that are larger than the range of the int data type as int. This post explains the causes stated above to give you clarity before you read about the solutions.

Continue reading to see how to solve the error and get your program back on track.

Contents

  • Why the Input String Was Not in a Correct Format Error Occur?
    • – Converting the Non-numeric Data in Text Boxes Into Int
    • – You Are Using Int With Input Values Larger than the Int Range
  • How To Fix the Format Error Found With the Strings?
    • – Use the Int.TryParse() Method
    • – Use Varchar Instead of Int To Fix the Input String Was Not in a Correct Format Error
  • FAQ
    • – What Is an ‘Input’ String?
    • – How To Ensure That the ‘Input’ String Matches a Particular Format?
    • – How To Get Rid of Number Format Exception in Java?
  • Conclusion

Why the Input String Was Not in a Correct Format Error Occur?

The given error occurs when you attempt to convert non-numeric data into an int. Also, exceeding the limit of the int data type to store larger values will give you the same error. Here are the detailed explanations of the causes:

– Converting the Non-numeric Data in Text Boxes Into Int

Are you working on a Windows Form and getting the above error? Well, the issue might be with converting the data of the empty text boxes when the form loads for the first time. So, here the erroneous code might be the one that attempts to convert an empty string from the text box into an int.

This line of code might throw the mentioned error when called inside the constructor:

lucky_number = Int32.Parse(luckyTextBox.Text);

– You Are Using Int With Input Values Larger than the Int Range

If the input provided by the user is larger than the range of int data type and you attempt to store the same in an int column, then the stated error occurs.

How To Fix the Format Error Found With the Strings?

You can fix the given error by putting into use the below solutions as per your need:

– Use the Int.TryParse() Method

As the text boxes are always empty when the form is loaded for the first time, you should use the Int.TryParse() method instead of the Int32.Parse() method. It will ensure that the error isn’t thrown even if the empty strings are attempted to be converted.

Replace the above line of code with the following:

lucky_number = Int.TryParse(luckyTextBox.Text);

– Use Varchar Instead of Int To Fix the Input String Was Not in a Correct Format Error

You should use the varchar data type instead of int to store any values that are larger than the range of int. It will most probably solve the error.

FAQ

Here you’ll find some additional information that will help you in your coding routine:

– What Is an ‘Input’ String?

An ‘input’ string refers to the data passed to a computer through a peripheral device such as a keyboard. A good example of this can be the data that you fill in the text boxes of an online form.

– How To Ensure That the ‘Input’ String Matches a Particular Format?

You can use a variety of methods including the regular expressions and loops to check if the given input string matches a particular format. Indeed, the regular expressions offer a quick and easy way to ensure the correctness of the string format. Moreover, using the loops can be helpful when you want to check each character of the string individually. So, it depends on your program requirements and the logic that you are trying to implement.

– How To Get Rid of Number Format Exception in Java?

You can resolve the number format exception in Java by checking if the string that you are trying to parse contains a numeric value. It is because the given exception occurs when you convert a string that doesn’t fulfill the requirements of an integer data type. Now, the name of the stated exception might be clear to you as well.

Conclusion

You don’t need to be worried anymore regarding the error discussed in this article. Indeed, it can be solved easily if you implement the stated solutions. Please look here for one-liner solutions:

  • Input string was not in a correct format error occurs when you convert non-numeric data into an int or exceed the limit of the int data type.
  • You should use Int.TryParse instead of Int32.Parse method to get rid of the said error
  • You should store large numeric values in a column with a varchar data type

How to fix input string was not in a correct formatNever forget to match the destination data type with input data to avoid such kind of errors in the future.

  • Author
  • Recent Posts

Position is Everything

Position Is Everything: Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL.

Position is Everything

  • Remove From My Forums
  • Question

  • I am trying to convert a null value to a double value using convert function in C#. Can anybody help me in this regards…

    I am getting a null value in a variable named «gridCol1»

    Step 1 — I am doing

                   Convert.ToDouble ( gridCol1.ToString() );

                   Error : «Input string was not in a correct format.»

Answers

  • You can’t convert a null value to a meaningful value through Convert.  Your best option is to check for null first and then assign a value of 0 (or whatever) to the result (whereever Convert was sending its results too).

    However looking at your code you might not be getting a null value.  What is the type of gridCol1?  If it is a DataGridViewCell then it will probably return the type to you in ToString().  You need to get the Value property instead.  If gridCol1 represents the actual value then your code is correct.

    if (gridCol1 != null)
       result = Convert.ToDouble(gridCol1);   //Don’t really need to call ToString() 
    else
       result = 0.0;

    The short form (when you want an expression) is:

    result = (gridCol1 != null) ? Convert.ToDouble(gridCol1) : 0.0;

    Personally I have run across this situation so much that I wrote a custom utility class called Converter that emulates Convert but handles null and a few other sundry values.  This simplifies my code greatly.  Even better is that if I truly want to blow up when getting a null value then I need only change back to Convert.

    Michael Taylor — 8/3/06
      

FormatException: Input string was not in a correct format.
System.Number.StringToNumber (System.String str, System.Globalization.NumberStyles options, System.Number+NumberBuffer& number, System.Globalization.NumberFormatInfo info, System.Boolean parseDecimal) (at <437ba245d8404784b9fbab9b439ac908>:0)
System.Number.ParseInt32 (System.String s, System.Globalization.NumberStyles style, System.Globalization.NumberFormatInfo info) (at <437ba245d8404784b9fbab9b439ac908>:0)
System.Int32.Parse (System.String s) (at <437ba245d8404784b9fbab9b439ac908>:0)
R_Main.Update () (at Assets/Random/R_Main.cs:24)

в чем ошибка вот скрипт:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class R_Main : MonoBehaviour
{

    public InputField inf_ot;
    public InputField inf_do;
    public Text otvet;
    public int str;
    public int str2;
    public int otv;

    public void Random()
    {
        str += str2 = otv;
    }

    // Update is called once per frame
    void Update()
    {
        str = int.Parse(inf_ot.text);
        str2= int.Parse(inf_do.text);
        otvet.text = "Число: " + otv.ToString();
    }
}


  • Вопрос задан

    более двух лет назад

  • 3967 просмотров

Подавать на вход int.Parse нормальное целое число.

Пригласить эксперта

str = int.Parse(inf_ot.text);
str2= int.Parse(inf_do.text);

У вас в inf_ot и ind_do не числа.
Приведите пример текста, который хотите спарсить.

PS: Но вообще код какой-то дикий. Я советую вам отложить юнити на потом и пока учить чистый C#.

Замечания по коду

public void Random()
{
    str += str2 = otv; // Не будет работать, либо будет работать не так, как вам нужно.
}

R_Main — какое-то дикое сокращение, которое ничего не говорит о смысле скрипта. + В C# принято использовать PascalCase — никаких нижних чёрточек
inf_ot, inf_do — То же самое, но ещё и транслит «от» «до»
otvet — то же самое
int str, str1 — лишнее сокращение + обман читателя. str большинство людей расшифровывают, как string, но тут числа
otv — сокращение + транслит.
Ну и парсинг чисел в апдейте — это жирноватая операция.

PPS: вероятно, вам нужно это:

Валидация — сюда можно ввести код, который не позволит пользователю вводит не-числа:
https://docs.unity3d.com/ru/530/ScriptReference/UI…

Событие ввода — чтобы не проверять текст каждый кадр:
https://docs.unity3d.com/ru/530/ScriptReference/UI…

Не забывайте про документацию — в ней хорошо описаны самые нужные моменты.


  • Показать ещё
    Загружается…

30 янв. 2023, в 08:15

20000 руб./за проект

30 янв. 2023, в 08:09

1000 руб./за проект

30 янв. 2023, в 07:48

500 руб./за проект

Минуточку внимания

Input string was not in a correct format errorThe input string was not in a correct format error might occur when you try to convert a non-numeric string from the input into an int. Moreover, you’ll get the said error while storing the input values that are larger than the range of the int data type as int. This post explains the causes stated above to give you clarity before you read about the solutions.

Continue reading to see how to solve the error and get your program back on track.

Contents

  • Why the Input String Was Not in a Correct Format Error Occur?
    • – Converting the Non-numeric Data in Text Boxes Into Int
    • – You Are Using Int With Input Values Larger than the Int Range
  • How To Fix the Format Error Found With the Strings?
    • – Use the Int.TryParse() Method
    • – Use Varchar Instead of Int To Fix the Input String Was Not in a Correct Format Error
  • FAQ
    • – What Is an ‘Input’ String?
    • – How To Ensure That the ‘Input’ String Matches a Particular Format?
    • – How To Get Rid of Number Format Exception in Java?
  • Conclusion

Why the Input String Was Not in a Correct Format Error Occur?

The given error occurs when you attempt to convert non-numeric data into an int. Also, exceeding the limit of the int data type to store larger values will give you the same error. Here are the detailed explanations of the causes:

– Converting the Non-numeric Data in Text Boxes Into Int

Are you working on a Windows Form and getting the above error? Well, the issue might be with converting the data of the empty text boxes when the form loads for the first time. So, here the erroneous code might be the one that attempts to convert an empty string from the text box into an int.

This line of code might throw the mentioned error when called inside the constructor:

lucky_number = Int32.Parse(luckyTextBox.Text);

– You Are Using Int With Input Values Larger than the Int Range

If the input provided by the user is larger than the range of int data type and you attempt to store the same in an int column, then the stated error occurs.

How To Fix the Format Error Found With the Strings?

You can fix the given error by putting into use the below solutions as per your need:

– Use the Int.TryParse() Method

As the text boxes are always empty when the form is loaded for the first time, you should use the Int.TryParse() method instead of the Int32.Parse() method. It will ensure that the error isn’t thrown even if the empty strings are attempted to be converted.

Replace the above line of code with the following:

lucky_number = Int.TryParse(luckyTextBox.Text);

– Use Varchar Instead of Int To Fix the Input String Was Not in a Correct Format Error

You should use the varchar data type instead of int to store any values that are larger than the range of int. It will most probably solve the error.

FAQ

Here you’ll find some additional information that will help you in your coding routine:

– What Is an ‘Input’ String?

An ‘input’ string refers to the data passed to a computer through a peripheral device such as a keyboard. A good example of this can be the data that you fill in the text boxes of an online form.

– How To Ensure That the ‘Input’ String Matches a Particular Format?

You can use a variety of methods including the regular expressions and loops to check if the given input string matches a particular format. Indeed, the regular expressions offer a quick and easy way to ensure the correctness of the string format. Moreover, using the loops can be helpful when you want to check each character of the string individually. So, it depends on your program requirements and the logic that you are trying to implement.

– How To Get Rid of Number Format Exception in Java?

You can resolve the number format exception in Java by checking if the string that you are trying to parse contains a numeric value. It is because the given exception occurs when you convert a string that doesn’t fulfill the requirements of an integer data type. Now, the name of the stated exception might be clear to you as well.

Conclusion

You don’t need to be worried anymore regarding the error discussed in this article. Indeed, it can be solved easily if you implement the stated solutions. Please look here for one-liner solutions:

  • Input string was not in a correct format error occurs when you convert non-numeric data into an int or exceed the limit of the int data type.
  • You should use Int.TryParse instead of Int32.Parse method to get rid of the said error
  • You should store large numeric values in a column with a varchar data type

How to fix input string was not in a correct formatNever forget to match the destination data type with input data to avoid such kind of errors in the future.

  • Author
  • Recent Posts

Position is Everything

Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team

Position is Everything

  • Remove From My Forums
  • Question

  • Mind you… This code has worked for a while.. Now, all of the sudden I get this error:

    ======= BEGIN ERROR

    When converting a string to a DateTime, parse the string to take the date before putting each variable into the DateTime object.

    ———————

    System.FormatException was unhandled by user code
      HResult=-2146233033
      Message=Input string was not in a correct format.
      Source=mscorlib
      StackTrace:
           at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
           at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)
           at MyProject.VideoPage.Page_Load(Object sender, EventArgs e) in C:UsersAdministratorDocumentsVisual Studio 2010ProjectsMyProjectVideoPage.aspx.cs:line 97
           at System.Web.UI.Control.LoadRecursive()
           at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
      InnerException:

    ================ END ERROR

    Here is my code…

    public string _StrVideoID { get; set; } public int _VideoID { get; set; } protected void Page_Load(object sender, EventArgs e) { _StrVideoID = RouteData.Values["VideoID"] as string; //_StrVideoID = HttpUtility.UrlEncode(Request.QueryString["vid"]); _VideoID = (int)Convert.ToInt32(_StrVideoID); //_VideoID = (int)Convert.ToInt32(RouteData.Values["VideoID"] as string); ...

    }

    When I debug this it shows the correct types as I step through, but I get this «DateTime» conversion error…

    What the heck?

    This code has worked perfectly for months!

    • Edited by

      Monday, December 17, 2012 3:32 AM

Answers

  • I’m stumped Paul. This code worked perfectly for months… Now, it hangs (3rd screenshot). I think it has to do with URL Routing. When I change back to «old school» Request.QueryString[«vid»]); insted of RouteData.Values[«VideoID»}… It works fine.

    Yet, in other apps that I have. The same code works fine…

    Anyway, let’s leave it at that. Thanks for your help.

    • Proposed as answer by
      Bob Shen
      Wednesday, December 19, 2012 4:13 AM
    • Marked as answer by
      Bob Shen
      Thursday, December 27, 2012 3:09 AM

  • Ошибка времени выполнения database error occurred
  • Ошибка времени выполнения basic файл не найден
  • Ошибка времени выполнения basic свойство или метод не найдены text
  • Ошибка времени выполнения basic подпрограмма или функция не определена
  • Ошибка времени выполнения basic 449 аргумент является обязательным