0
command.CommandText = "SELECT * FROM Books WHERE Author='"+Convert.ToString(comboBox1.SelectedItem)+"'";

reader = command.ExecuteReader();

前任。我"John"从组合框中选择。datagridview 将显示来自数据库的数据,其Author="John". 例如,同一作者(John)有 4 本书,如何将这些数据显示到 datagridview?

4

1 回答 1

1

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);
于 2013-02-12T11:52:02.480 回答