2013-08-19 19 views
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); 
     } 


    } 
+9

描述「但它不工作」。不清楚。 –

+0

輸出sxt到txtDesc中,可能會幫助 – athabaska

+1

調試代碼。在交換機上,sType的值是多少? – stevepkr84

回答

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 [email protected]"; 
    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 on Sql Injection的樣本文章,也是一個因特網搜索,將解釋在sql命令中字符串連接出現的問題。

+0

謝謝你的回答。 – user2631662