[英]The input string was not in correct format
我是C#編程的新手,但是我找不到此代碼。 我得到的錯誤是
輸入的字符串格式不正確。
我知道這是一個重復的問題,但是到目前為止我發現的內容並沒有太大幫助。 我正在使用以下代碼,以便將某些數據插入mssql數據庫。
public void btnAdauga_Click(object sender, EventArgs e)
{
try
{
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand(insert, con);
cmd.Parameters.AddWithValue("@IDAutocar", txtID.Text);
cmd.Parameters.AddWithValue("@IDTipAutocar", txtIDTip.Text);
cmd.Parameters.AddWithValue("@TipAutocar", int.Parse(cmbTip.SelectedValue.ToString()));
int val = cmd.ExecuteNonQuery();
MessageBox.Show(val + "Autocarul a fost adaugat cu succes!");
con.Close();
this.Dispose();
}
}
catch (Exception er){MessageBox.Show(er.Message);}
}
insert語句: string insert = "INSERT INTO Autocare (IDAutocar, IDTipAutocar, TipAutocar) VALUES (@IDAutocar, @IDTipAutocar, @TipAutocar)";
錯誤在以下代碼行: cmd.Parameters.AddWithValue("@TipAutocar", int.Parse(cmbTip.SelectedValue.ToString()));
有人可以啟發我我所缺少的嗎? 謝謝
嘗試使用Int.TryParse函數而不是Int.Parse並在該行之前處理解析異常。 像這樣:
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand(insert, con);
cmd.Parameters.AddWithValue("@IDAutocar", txtID.Text);
cmd.Parameters.AddWithValue("@IDTipAutocar", txtIDTip.Text);
int tipAutocar = 0;
if (int.TryParse(cmbTip.SelectedValue.ToString(), out tipAutocar))
{
//if successful
cmd.Parameters.AddWithValue("@TipAutocar", tipAutocar));
}
else
{
//if not successful, do sth else
}
int val = cmd.ExecuteNonQuery();
MessageBox.Show(val + "Autocarul a fost adaugat cu succes!");
con.Close();
this.Dispose();
}
如果您的組合框包含int值作為字符串,請使用
int.Parse(cmbTip.Text);
如果要選擇文本的索引,請使用
int.Parse(cmbTip.SelectedIndex);
根據Yeldar的建議,我刪除了int.Parse
並僅使用combo.SelectedValue
,它起作用了!
cmbTip.SelectedValue.ToString()
] cmbTip.SelectedValue.ToString()
可能是導致異常的原因。 cmbTip
即使選擇了值后錯誤仍然存在,或者selectedValue
為NULL
,請嘗試使用SelectedText
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.