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
    }

编辑我忘记为避免字符串连接的建议添加解释。这里有一篇来自MSDN 的关于 Sql Injection的示例文章,还有一个互联网搜索将解释 sql 命令中字符串连接出现的问题

于 2013-08-19T09:54:57.247 回答