0

こんにちは、アプリケーションでテキストボックスの MaxLength を設定するために必要な以下のコードがあります。コードは問題ないようですが、機能していません。誰が問題が何であるかを見ることができますか。

        private void cbType_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        string constring = "Data Source=.;Initial Catalog=db.MDF;Integrated Security=True";

        string Query = "select * from RePriorities where Priority='" + cbType.SelectedItem.ToString() + "' ;";
        SqlConnection conDataBase = new SqlConnection(constring);
        SqlCommand cmdDataBase = new SqlCommand(Query, conDataBase);
        SqlDataReader myReader;

        try
        {

            conDataBase.Open();
            myReader = cmdDataBase.ExecuteReader();

            string sType = myReader.ToString();

            switch (sType)

            {
                case "Low": txtDesc.MaxLength = 5; break;
                case "Medium": txtDesc.MaxLength = 10; break;
                case "High": txtDesc.MaxLength = 1; break;
            }


        }

        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        } 


    } 
4

1 に答える 1

3

SqlDataReader を開いた後、Read メソッドを呼び出して、内部レコード ポインターを最初のレコードに配置する必要があります。その後、リーダーから値を抽出できます

        myReader = cmdDataBase.ExecuteReader();
        if(myReader.Read())
        {
            string sType = myReader["name_of_field"].ToString();
            switch (sType)
            {
                case "Low": txtDesc.MaxLength = 5; break;
                case "Medium": txtDesc.MaxLength = 10; break;
               case "High": txtDesc.MaxLength = 1; break;
            }
        }

また、読み返したいフィールドの名前 (またはインデックス) を読者に伝える必要があります。

コードの大きな問題を指摘させてください。これは、コマンド テキストを準備するためにメソッドの最初に作成する文字列連結です。文字列の連結は使用しないでください。常にパラメーター化されたクエリを使用してください。

    string constring = "Data Source=.;Initial Catalog=db.MDF;Integrated Security=True";
    string Query = "select * from RePriorities where Priority=@priority";
    using(SqlConnection conDataBase = new SqlConnection(constring))
    using(SqlCommand cmdDataBase = new SqlCommand(Query, conDataBase))
    {
        conDataBase.Open();
        cmdDataBase.Parameters.AddWithValue("@priority", cbType.SelectedItem.ToString());

        ......

        // the rest of your code
    }

編集文字列の連結を避けるための提案の説明を追加するのを忘れていました。ここでは、 SQL インジェクションに関する MSDNの記事のサンプルです。インターネット検索でも、SQL コマンドの文字列連結で発生する問題が説明されています。

于 2013-08-19T09:54:57.247 に答える