使用switch语句调整文本框的大小

本文关键字:文本 switch 语句 调整 使用 | 更新日期: 2023-09-27 18:28:14

嗨,我有下面的代码,需要在我的应用程序中设置文本框的最大长度。代码看起来不错,但不起作用。有人能看到问题出在哪里吗。

        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);
        } 

    } 

使用switch语句调整文本框的大小

打开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
    }

EDIT我忘了为建议添加解释以避免字符串串联。这里有一篇来自MSDN的关于Sql Injection的示例文章,也是一篇互联网搜索文章,将解释Sql命令

中字符串串联所出现的问题