Domanda

I created win forms, and I wanna insert sql commands and get data from database. If I put query directly into code sql commands, everything is ok, if I put query by textbox I have a lot of bugs like:

$exception {"Could not find stored procedure 'select * from uczniowie'."}
System.Exception {System.Data.SqlClient.SqlException } this {MateuszLab4.connectDB} MateuszLab4.connectDB question "\"select * from uczniowie\"" string dataTable {} System.Data.DataTable sqlDataReader null System.Data.SqlClient.SqlDataReader sqlCommand {System.Data.SqlClient.SqlCommand} System.Data.SqlClient.SqlCommand

Here is my code:

  private void buttonSearch_Click(object sender, EventArgs e)        
  {
        string query = textBoxQuery.Text;
        connectDB databaseWin = new connectDB("(localdb)\\v11.0", "Mat");
        dataGridViewAdvanced.DataSource = databaseWin.DataDownload(query);                      
  }

When I put into string query sql commands (for example string query = "select * from students" ) everything is working very well. If I replaced with data from textbox sth is wrong. Could you give me some tips guys?

here is my class with datadownloada:

 public DataTable DataDownload(string question)
 {
        DataTable dataTable = new DataTable();
        SqlDataReader sqlDataReader; 
        SqlCommand sqlCommand; 

        sqlCommand = new SqlCommand(question);
        sqlCommand.Connection = this.DBconnection; 
        sqlDataReader = sqlCommand.ExecuteReader(); 
        dataTable.Load(sqlDataReader); 

        return dataTable; 
  }
È stato utile?

Soluzione

Try this code. 
public DataTable DataDownload(string question)
 {
       using (var ada = new SqlDataAdapter(question, DBconnection))
        {               
            // Use DataAdapter to fill DataTable
            DataTable dt = new DataTable();
            ada.Fill(dt);
            return dt;


        }
  }
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top