[英]How to insert values from a masked textbox to the database?
我已經使用了此代碼,但向我顯示了錯誤
輸入的字符串格式不正確
碼:
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["String"].ConnectionString);
try
{
con.Open();
SqlCommand com = new SqlCommand("insert into TableYear where textBoxYear=" + int.Parse(maskedTextBox1.Text) + ";", con);
SqlDataReader reader = com.ExecuteReader();
int count = 0;
while (reader.Read())
{
count++;
string AY = reader.GetString(0);
comboBoxAY.Items.Add(AY);
}
con.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
問題不在於將masked
文本框的內容插入數據庫。 實際上,將蒙版文本parsing
為int
時會發生此問題。 這里:
int.Parse(maskedTextBox1.Text)
您可能在文本框中輸入的掩碼數字為123-34-233等。在這種情況下,您首先需要清除字符串。 (即,刪除空格,破折號和除數字(整數)以外的所有其他字符)。 如果您嘗試使用int.Parse(maskedTextBox1.Text)
將235-145_234
類的文本轉換為int
,則顯然會出現異常,表明input string was not in correct format
。 因為-
無法解析為整數。
嘗試首先從字符串中刪除破折號,然后將其解析為int。 如:
string textBoxText = maskedTextBox1.Text;
textBoxText = textBoxText.Replace("-", "");
int number = int.parse(textBoxText);
然后將其插入數據庫。
T-SQL中的INSERT
不支持WHERE
子句-您應使用類似以下內容的代碼:
INSERT INTO dbo.TableYear(Col1) VALUES(Val1)
在C#中,應始終使用參數化查詢來避免SQL注入攻擊:
SqlCommand com = new SqlCommand("INSERT INTO dbo.TableYear(ColumnName) VALUES(@Value)");
com.Parameters.Add("@Value", SqlDbType.Int).Value = int.Parse(maskedTextBox1.Text);
您還需要對INSERT
, UPDATE
或DELETE
命令使用.ExecuteNonQuery()
,因為這些語句不返回結果集:
com.ExecuteNonQuery();
您的INSERT查詢不正確,請從INSERT語句中刪除where子句
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.