I'm trying to learn how to use SQL in C#.
I ran into an issue and I can't figure it out. I made a ComboBox which reads data from my database and uses the database's Id as a ValueMember and displays a title.
I want to use the selected title's Id, so I can write the contents of a row to a RichTextBox with the click of a button.
So if I have selected the first title in the combobox, which has Id 1 in the database, I want to use that info to show the corresponding text in the richtextbox. I thought I figured it out, but it gives me an error:
String was not in correct format
The database is very simple:
Id | Title | Author | Story |
---|---|---|---|
1 | aTitle | Me | Random Text |
2 | SomeTitle | NotMe | More Random Text |
Here's my code:
private void LoadData()
{
using (Connection = new SqlConnection(ConnectionString)) //Make the connection
using (Adapter = new SqlDataAdapter("SELECT Title FROM StoryTable", ConnectionString))
{
Connection.Open();
DataTable TitleTable = new DataTable();
Adapter.Fill(TitleTable);
SelectionBox.ValueMember = "Id";
SelectionBox.DisplayMember = "Title";
SelectionBox.DataSource = TitleTable;
}
}
private void LoadButton_Click(object sender, EventArgs e)
{
int Id = Int32.Parse(SelectionBox.ValueMember); //String was not in correct format...
using (Connection = new SqlConnection(ConnectionString))
using (Adapter = new SqlDataAdapter("SELECT Story FROM StoryTable", ConnectionString))
{
Connection.Open();
var TextTable = new DataSet();
Adapter.Fill(TextTable);
StoryTextbox.Text = TextTable.Tables[0].Rows[Id]["Story"].ToString();
}
}
CodePudding user response:
The immediate problem is that this:
int Id = Int32.Parse(SelectionBox.ValueMember);
should be this:
int Id = (int)SelectionBox.SelectedValue;
Actually, I just realised that there's another problem. You do this:
SelectionBox.ValueMember = "Id";
SelectionBox.DisplayMember = "Title";
yet this is your query:
SELECT Title FROM StoryTable
How are you going to bind the Id
column when you're not even retrieving it?
SELECT Id, Title FROM StoryTable