I've searched all through the internet, and there is no way that I have found to do what I'm asking for. Here's my code:
using (MySqlConnection connection = new MySqlConnection(verbindung))
{
connection.Open();
string query = $@"show tables like '%{tbSearch.Text}%'";
MySqlCommand command = new MySqlCommand(query, connection);
using (MySqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
listR.Add(reader.GetString(0));
btnAccount.Text = listR[0];
btnAccount2.Text = listR[1];
}
}
}
What I expect:
- To get two strings if there is more than one Table available.
- I add in the values separately using the code below, considering when I tried using an AutoCompleteMenu it was able to separate each string e.g. PrX#0000 and PxL#0000 are not in the same line or value.
- Display the values on buttons (I can do this part myself, I just gotta know how to separate values from the Query into separate strings.
What I got:
An error at: btnAccount2.Text = listR1; with the error being:
System.ArgumentOutOfRangeException: 'Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index'
I guess that's because of the string not being separated into 2 by itself
I tried pretty much everything and searched all around the internet, and was still not able to find any way to do this.
Here's the data I'm trying to get from the reader:
Here's what I get when I show the data of GetString(0)
in a MessageBox.
I get 2 MessageBoxes when I do MessageBox.Show(reader.GetString(0));
One normally after I type the first letter of the table in the Textbox, the second after I close the first MessageBox.
CodePudding user response:
You will "get two strings if there is more than one Table available." The loop (around reader.Read()
) will provide a separate string for each row in the dataset, i.e., each table in your database.
You need to move the access of the two strings outside the loop. The first time the loop runs, you only have one string, so you can't access both of them yet.
listR.Clear();
using (MySqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
listR.Add(reader.GetString(0));
}
btnAccount.Text = listR[0];
btnAccount2.Text = listR[1];
Note that this code will still crash if there are fewer than two tables, it will ignore any tables past the first two, and it will pick the first two tables in arbitrary order (because there's no ORDER BY
in your query).