C# string to combobox issues
What i'm trying to do is read in a header row of a file to a combobox. Here is my code:
private void button4_Click(object sender, EventArgs e)
{
string[] startdelim = File.ReadAllLines(textBox1.Text);
int counter = 1;
foreach (string delim in startdelim)
{
if (counter == 1)
{
string removedelim = delim.Replace("\"", "");
string[] lines = removedelim.IndexOf(",");
foreach (string line in lines)
{
comboBox1.Items.Add(line);
}
}
counter++;
}
}
for some reason it keeps telling me
Error Cannot implicitly convert type 'int' to 'string开发者_如何学运维[]' at
string[] lines = removedelim.IndexOf(",");
IndexOf
returns the first index of the string ","
within removedelim
. You're looking for Split
.
string[] lines =
removedelim.Split(new string[] { "," }, StringSplitOptions.None);
Note that there is not an instance of Split
that takes a single string
(since some languages allow implicit conversion between string
and char[]
, which would make overload resolution ambiguous and not easily corrected), so you have to use the overload that takes an array of delimiters and just provide one.
Well the error is pretty straightforward. IndexOf
returns the integer position of the character you searched for. You need to do a Split
instead of IndexOf
.
String. IndexOf(Char) : Reports the index of the first occurrence of the specified Unicode character in this string.
sting.IndexOf(char) returns a int not a sting array.
Others have already spotted the mistake. Still there are problems with your code. All you need is following lines of code:
string[] startdelim = File.ReadAllLines(textBox1.Text);
comboBox1.Items.AddRange(startdelim[0].Replace("\","").Split(","));
精彩评论