Hi..I am trying to import .csv file data to datagridview.I am getting an error:System.FormatException «String must be exactly one character long.».I am posting my code.The one which i have highlighted in bold is showing the error.May i know where
i am going wrong.And what does this actually mean.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace Excel_app
{
public partial class Form4 : Form
{
char delimiter;
Boolean dataloaded = false;
public Form4()
{
InitializeComponent();
}
private void btnBrowse_Click(object sender, EventArgs e)
{
openFileDialog1.InitialDirectory = «C:»;
openFileDialog1.Filter = «CSV files(*.csv)|*.CSV»;
openFileDialog1.FilterIndex = 2;
openFileDialog1.ShowDialog();
txtFileName.Text = openFileDialog1.FileName;
}
private void btnLoad_Click(object sender, EventArgs e)
{
string fileRow;
string[] fileDataField;
int count = 0;
if (dataloaded == false)
{
try
{
delimiter = Convert.ToChar(txtdelimiter.Text); ——>System.FormatException
}
catch (Exception exObject)
{
MessageBox.Show(exObject.ToString());
this.Close();
}
try
{
if (File.Exists(txtFileName.Text))
{
StreamReader fileReader = new StreamReader(txtFileName.Text);
if (fileReader.Peek() != -1)
{
fileRow = fileReader.ReadLine();
fileDataField = fileRow.Split(delimiter);
count = fileDataField.Count();
count = count — 1;
for (int i = 0; i <= count; i++)
{
DataGridViewTextBoxColumn columnDataGridTextBox = new DataGridViewTextBoxColumn();
columnDataGridTextBox.Name = fileDataField[i];
columnDataGridTextBox.HeaderText = fileDataField[i];
columnDataGridTextBox.Width = 120;
dataGridView1.Columns.Add(columnDataGridTextBox);
}
}
else
{
MessageBox.Show(«File is Empty.»);
}
while (fileReader.Peek() != -1)
{
fileRow = fileReader.ReadLine();
fileDataField = fileRow.Split(delimiter);
dataGridView1.Rows.Add(fileDataField);
}
fileReader.Close();
}
else
{
MessageBox.Show(«No File Is Selected.»);
}
dataloaded = true;
}
catch (Exception ExObject)
{
MessageBox.Show(ExObject.ToString());
}
}
else
{
MessageBox.Show(«Clear DataGridView First.»);
}
}
private void btnSave_Click(object sender, EventArgs e)
{
try
{
delimiter = Convert.ToChar(txtdelimiter.Text);
}
catch(Exception ExObject)
{
MessageBox.Show(ExObject.ToString());
this.Close();
}
try
{
StreamWriter fileWriter = new StreamWriter(txtFileName.Text, false);
string columnHeaderText = «»;
int countColumn = dataGridView1.ColumnCount — 1;
if (countColumn >= 0)
{
columnHeaderText = dataGridView1.Columns[0].HeaderText;
}
for (int i = 1; i <= countColumn; i++)
{
columnHeaderText = columnHeaderText + delimiter + dataGridView1.Columns[i].HeaderText;
}
fileWriter.WriteLine(columnHeaderText);
foreach (DataGridViewRow dataRowObject in dataGridView1.Rows)
{
if (!dataRowObject.IsNewRow)
{
string dataFromGrid = «»;
dataFromGrid = dataRowObject.Cells[0].Value.ToString();
for (int i = 1; i <= countColumn; i++)
{
dataFromGrid = dataFromGrid + delimiter + dataRowObject.Cells[i].Value.ToString();
}
fileWriter.WriteLine(dataFromGrid);
}
}
MessageBox.Show(«Data Is Successfully saved in file.»);
fileWriter.Flush();
fileWriter.Close();
}
catch (Exception ExObject)
{
MessageBox.Show(ExObject.ToString());
}
}
private void btnClear_Click(object sender, EventArgs e)
{
new Form4().Show();
this.Dispose(false);
}
}
}
|
Kotnor1998 0 / 0 / 0 Регистрация: 15.01.2017 Сообщений: 31 |
||||
|
1 |
||||
|
16.10.2020, 15:14. Показов 2573. Ответов 6 Метки string (Все метки)
Добрый день, в общем есть задание, нужно перевести математическую формулу на C#, вот что получилось у меня, но я не уверен, правильно ли всё я сделал, прошу вас, что бы вы подсказали мне есть ли ошибки в коде.
Миниатюры
__________________
0 |
|
bite 3264 / 2852 / 659 Регистрация: 13.04.2015 Сообщений: 6,727 |
|
|
16.10.2020, 15:31 |
2 |
|
есть ли ошибки в коде Есть Добавлено через 47 секунд
0 |
|
0 / 0 / 0 Регистрация: 15.01.2017 Сообщений: 31 |
|
|
16.10.2020, 15:36 [ТС] |
3 |
|
Какой-то баг с темой, писал про совсем другое, а у меня описание из моего прошлого вопроса, прошу модератора удалить тему.
0 |
|
I can bite 3264 / 2852 / 659 Регистрация: 13.04.2015 Сообщений: 6,727 |
||||
|
16.10.2020, 15:38 |
4 |
|||
|
Как минимум так должно быть
0 |
|
Kotnor1998 0 / 0 / 0 Регистрация: 15.01.2017 Сообщений: 31 |
||||
|
16.10.2020, 15:40 [ТС] |
5 |
|||
|
Тема багнутая. У меня другая проблема. Есть вводимое число с плавающей точкой, но если его ввести в консоль, то выбивает ошибку «String must be exactly one character long».
Если попробовать ввести 36.5, то выбьет ошибку, если же ввести целое, то всё ок. Можете с этим помочь.
0 |
|
bite 3264 / 2852 / 659 Регистрация: 13.04.2015 Сообщений: 6,727 |
|
|
16.10.2020, 15:41 |
6 |
|
Решение
36.5 36,5
1 |
|
0 / 0 / 0 Регистрация: 15.01.2017 Сообщений: 31 |
|
|
16.10.2020, 15:45 [ТС] |
7 |
|
Кликните здесь для просмотра всего текста я даун….. Спасибо вам.
0 |
Hi All,
I created a script for formatting the drive and assigning the drive label on remote servers. It works fine if I manually change the details. But when trying to import the values from a CSV input its throwing the error mentioned below.
Error:
Cannot process argument transformation on parameter ‘DriveLetter’. Cannot convert value «$DriveLetter» to type «System.Char». Error: «String must be exactly one character long.»
+ CategoryInfo : InvalidData: (:) [New-Partition], ParameterBindin…mationException
+ FullyQualifiedErrorId : ParameterArgumentTransformationError,New-Partition
+ PSComputerName : 123Remote server
*************************************************************
CSV input :
DiskNumber DriveLetter NewFileSystemLabel AllocationUnitSize
7 N Drive_N 4096
*************************************************************
My Script:
# New Partation/Drive letter/Farmat/Lable/Allocation
Measure-Command{
Clear
$Data = Import-csv ‘C:UsersU142008DesktopStorage_Data_Input.csv’
$DiskNumber=$Data.DiskNumber
$DriveLetter=$Data.DriveLetter
$NewFileSystemLabel=$Data.NewFileSystemLabel
$AllocationUnitSize=$Data.AllocationUnitSize
#$c=Get-Credential Admin
$ServerList = Get-Content ‘H:My DocumentsMy Powershellserverlist.txt’
foreach ($ServerName in $ServerList){
Invoke-Command -ComputerName $ServerName -Credential $c -ScriptBlock {
# New Partation/Drive letter/Farmat/Lable/Allocation
Stop-Service -Name ShellHWDetection
New-Partition -DiskNumber «$DiskNumber» -UseMaximumSize -DriveLetter ‘$DriveLetter’ | Format-Volume -FileSystem NTFS -NewFileSystemLabel «$NewFileSystemLabel»
-AllocationUnitSize «$AllocationUnitSize» -Force -Confirm:$false
Start-Service -Name ShellHWDetection
}}}
-
Edited by
Thursday, July 28, 2016 12:33 PM
Я пытаюсь получить ввод от пользователя с помощью Microsoft.VisualBasic.dll. Затем преобразуйте ввод из [ строки ] в тип [ char ]. Но когда я запускаю код, возникает эта ошибка:
*An exception of type 'System.FormatException' occurred in mscorlib.dll but was not handled in user code
String must be exactly one character long.*
Образец кода:
string directions = Microsoft.VisualBasic.Interaction.InputBox("1 = Buy, 2 = Sell", "Select side", "Default", 700, 400);
char direction = System.Convert.ToChar(directions);
Есть идеи, как это решить? Заранее спасибо.
2 ответа
Лучший ответ
Вы можете сделать это: всегда настоятельно рекомендуется перехватывать FormatException и ArgumentNullException, как по этой ссылке:
https://docs.microsoft.com/en-us/dotnet/api/system.convert.tochar?view=netframework-4.7.2#System_Convert_ToChar_System_String_
char direction;
string directions = Microsoft.VisualBasic.Interaction.InputBox("1 = Buy, 2 = Sell", "Select side", "Default", 700, 400);
if(!string.IsNullOrEmpty(directions) && directions.Trim().Length == 1)
direction = System.Convert.ToChar(directions);
else {
direction = directions.FirstOrDefault(); // if thats what your logic
}
Или вы можете использовать:
char direction = directions.FirstOrDefault();
2
Gauravsa
8 Ноя 2018 в 03:26
Почему вы выбрали ответ по умолчанию «По умолчанию»? Вы либо оставляете поле пустым, либо ставите «1» или «2».
Также проверьте ответ пользователя перед преобразованием в направление:
If directions <> "1" And directions <> "2" Then
'display error message to user
Else
char direction = System.Convert.ToChar(directions);
'proceed with your business logic
End If
0
Daniel Wu
8 Ноя 2018 в 03:40
char.Parse("<br />")
will give you a FormatException as char.Parse expects a string with a length of exactly 1 as the error message tells you.
You want to simply use string.Split(string)
var outPutArray = ieoutput.Split("<br />");
or for multiple separator options e.g. string.Split(string[])
var outPutArray = ieoutput.Split(new []{"<br />", "<br>", "<br/>"});
since most commonly the <br> tag is actually used without the closing /.
Since in general there are multiple ways how to exactly write these HTML tags in order to match all the different ways to write this you could also rather use Regex.Split like e.g.
var outPutArray = Regex.Split(ieoutput, "<br.*?>", RegexOptions.IgnoreCase | RegexOptions.SingleLine);
Here you match anything that
- Begins with
<br(or<BR,<Bretc) - Ends with the next
>
not matter what comes between these, even if it is line breaks (see RegexOptions.SingleLine
See Regex Example and further Explanation on regex101.com
However as was already suggested, if you can change the output format actually the simplest solution of all would be rather use line breaks (n). It is a single character so you can simply use
var outPutArray = ieoutput.Split('n');

Сообщение было отмечено Kotnor1998 как решение