I want to add a string from a textbox to an array, but when I tried to add it to the array it gives me an error (Cannot convert char[] to string[]) what is it that I'm doing wrong, and is it maybe a better way to do it?
public string[] users = { "username" };
public string[] passwords = { "password" };
string[] users = textBox1.Text.ToArray();
string[] passwords= textBox2.Text.ToArray();
You want to use char array, not string array. This is because textBox1.Text
returns a string type, not a string array type. Calling ToArray()
on a string results in a char array type.
char[] user = textBox1.Text.ToArray();
char[] password= textBox2.Text.ToArray();
You should also consider changing string[] user
and string[] password
to string type instead, since I'm assuming you are only storing one username in user. If you are trying to store a collection of users, then you should name your variable correctly, such as string[] users
, to not cause confusion.
user
and password
have been allocated as single element arrays. Arrays are immutable and cannot be appended to, so you cannot do this:
public string[] user = { "username" };
public string[] password = { "password" };
//...
user.Append(textBox1.Text);
password.Append(textBox2.Text);
But you could reallocate the user
and password
arrays with something like this:
public string[] user = { "username" };
public string[] password = { "password" };
//...
user = new[] { user[0], textBox1.Text };
password = new[] { password[0], textBox2.Text };
This is rather clumsy, though. You would probably be better off defining user
and password
as List<String>
, ie:
public List<string> user = new List<string>() { "username" };
public List<string> password = new List<string>() { "password" };
//...
user.Add(textBox1.Text);
password.Add(textBox2.Text);
You should use char arrays instead of string array :
public string[] users = { "username" };
public string[] passwords = { "password" };
-
char[] users = textBox1.Text.ToArray();
char[] passwords= textBox2.Text.ToArray();
And instead of string arrays you can use List<string>
for users and passwords.
Tip : It's better to rename your textBoxes something like txtUserName
for clearify and better code.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.