2016-06-14 12 views
-2


このエラーをどのように訂正できますか?この行のエラー:readK.Fill(dt1);。ありがとうございました!このコードはFormatExceptioncomboBox5.SelectedValueが整数でない原因となる場合'='付近の構文が正しくない

SqlCommand selK = new SqlCommand("Select * from Kafedra where [email protected]_facultet, conn); 
sqlK.Parameters.Add("@id_facultet", SqlDbType.Int).Value = int.Parse(comboBox5.SelectedValue.ToString()); 

private void comboBox5_SelectedValueChanged(object sender, EventArgs e) 
{ 
    comboBox6.SelectedValueChanged -= comboBox6_SelectedValueChanged; 
    DataTable dt1 = new DataTable(); 
    BindingSource bd = new BindingSource(); 
    conn.Open(); 
    bd.DataSource = dt1; 
    SqlCommand selK = new SqlCommand("Select * from Kafedra where id_fcultet=" + comboBox5.SelectedValue, conn); 
    SqlDataAdapter readK = new SqlDataAdapter(selK); 
    readK.Fill(dt1); 
    comboBox6.DataSource = bd; 
    comboBox6.DisplayMember = "name"; 
    comboBox6.SelectedIndex = -1; 
    comboBox6.ValueMember = "id_kafedra"; 
    textBox2.Text = i + comboBox5.SelectedValue; 
    conn.Close(); 
    comboBox6.SelectedValueChanged += comboBox6_SelectedValueChanged; 
} 
+4

まず、SQLをパラメータ化することから始めてください。現在、あなたはSQLインジェクション攻撃のために広く開かれています。これを済ませたら( 'SqlDbCommand.Parameters'を参照)、問題が既に解決されていることがわかります。 –

+0

_comboBox5.SelectedValue_の値は何ですか? – Steve

+0

そこにcomboBox5.SelectedValue = id_facultet – MSS

答えて

3

この問題を解決する最良の方法も可能で、SQLインジェクションを修正するSQLパラメータを使用することです。最初の場所にある整数の場合(デバッガを使用する場合)は、キャストを使用することもできます。... .Value = (int)comboBox5.SelectedValue;

1

クエリを作成するための文字列連結アプローチは、SQLインジェクションの大きな扉を開きます。パラメータ化クエリを使用することを強くお勧めします。 SQLインジェクションを避ける。ここで同じことを行うための一例である:

SqlCommand selK = new SqlCommand("Select * from Kafedra where [email protected]", conn); 
selK.Parameters.Add("@someID",SqlDbType.Varchar).value= comboBox5.SelectedValue; 

あなたは表内のその特定のフィールドの種類ごとにSqlDbType.Varcharを選択することができます。

+2

「あなたのコマンドは次のようにすべきです」と答えてください。パラメータ化されたSQLは実際にここに行く唯一の方法です。私は強く文字列の連結のアプローチを完全に削除することをお勧めします。 –

+0

@JonSkeet:貴重なアドバイスをいただきありがとうございます。私の答えを改善するのに役立ちます。 –

関連する問題