Ale*_*son 2 c# windows foreach
无论出于何种原因,这似乎都很简单.特别是Foreach循环给我这个错误"错误1无法将类型'char'转换为'string'".我做了一些研究,虽然它不想揭示它的自我.希望你们知道,非常感谢你的帮助.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace A_HtmlEditor
{
public partial class Form1 : Form
{
AutoCompleteStringCollection data = new AutoCompleteStringCollection();
public Form1()
{
InitializeComponent();
}
// The error occurs in the foreach loop below
private void textBox1_TextChanged(object sender, EventArgs e)
{
webBrowser1.DocumentText = textBox1.Text;
foreach(string s in textBox1.Text)
{
data.Add(s);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
顺便说一下,当我在这里时,我想知道你们是否有可能知道是否有可能找出是否有按钮点击,例如关机按钮?或者,如果不可能,有一种方法可以知道计算机何时即将关闭.
我再一次感激,谢谢.
textBox1.Text是一个字符串(不是字符串的集合).所以当你这样做时:
foreach (string s in textBox1.Text)
{
data.Add(s);
}
Run Code Online (Sandbox Code Playgroud)
它试图将字符串视为集合.这实际上是有效的,因为a实际上string是一个数组char.问题是你在申报时试图将每个转换char为a .stringstring s
如果你真的想要添加每个字符data,那么你可以将每个字符转换char为string:
// This takes each character from textBox1.Text,
// converts it to a string, and adds it to data
foreach (char chr in textBox1.Text)
{
data.Add(chr.ToString());
}
Run Code Online (Sandbox Code Playgroud)
或者,如果您textBox1是一个多行文本框并且您尝试添加每一行data,您可以拆分字符上的文本NewLine以获取字符串列表,并添加它们,如下所示:
// This takes each line from a multi-line text box and adds it to data
foreach (string line in textBox1.Text.Split(new[] { '\n' }))
{
data.Add(line);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
21564 次 |
| 最近记录: |