Reputation: 33
command.CommandText = "SELECT * FROM Books WHERE Author='"+Convert.ToString(comboBox1.SelectedItem)+"'";
reader = command.ExecuteReader();
ex.
I select "John"
from the comboBox.
the datagridview will show the data from the database whose Author="John"
.
For example, there are 4 books with the same author(John), how can I display those data to datagridview?
Upvotes: 0
Views: 2194
Reputation: 11287
something like
command.CommandText = "SELECT * FROM Books WHERE Author='"+Convert.ToString(comboBox1.SelectedItem)+"'";
var reader = command.ExecuteReader();
var list = new List<string>();
while(reader.Read())
{
list.Add(reader["Author"].ToString())
}
datagridview.DataSource = list;
there are many (many!) things wrong with doing it this way - but it wil properly get you on your way.
First of all - try to avoid having your GUI so "close" to the db code. Secondly, as mentionsed, this code is vulnerable to SQL injection.
My suggestion:
public List<string> GetAuthors(string aurtherName)
{
using(var con = CreateConnection()//somehow )
{
var command = con.CreateCommand();
string sql = "SELECT * FROM Books WHERE Author='@value'";
command.Parameters.AddWithValue("@value", aurtherName);
command.CommandText = sql ;
var list = new List<string>();
while(reader.Read())
{
list.Add(reader["Author"].ToString())
}
return list;
}
}
that way you can call it like this:
datagridview.DataSource = GetAuthors(comboBox1.SelectedItem);
Upvotes: 1