2017-05-06 93 views
0

代碼:轉換失敗而轉換爲varchar到int背後

protected void DropDownList3_SelectedIndexChanged(object sender, EventArgs e) 
{ 
    string countryid = Convert.ToString(DropDownList3.SelectedValue); 
    con.Open(); 

    SqlCommand cmd = new SqlCommand("select * from states where countryID=" + countryid, con); 

    SqlDataAdapter da = new SqlDataAdapter(cmd); 
    DataSet ds = new DataSet(); 
    da.Fill(ds); 

    con.Close(); 

    DropDownList4.DataSource = ds; 
    DropDownList4.DataTextField = "stateName"; 
    DropDownList4.DataValueField = "stateID"; 
    DropDownList4.DataBind(); 

    DropDownList4.Items.Insert(0,new ListItem("--select--","0")); 

    if (DropDownList4.SelectedValue == "0") 
    { 
     DropDownList6.Items.Clear(); 
     DropDownList6.Items.Insert(0, new ListItem("--select--", "0")); 
    } 

表結構:

CREATE TABLE countries 
(
    countryID varchar(3) NOT NULL, 
    countryName nvarchar(100) NOT NULL, 
    localName nvarchar(100), 
    webCode varchar(2), 
    region varchar(50), 
    continent varchar(25), 
    latitude float NOT NULL, 
    longitude float NOT NULL, 
    surfaceArea float NOT NULL, 
    population int NOT NULL, 

    PRIMARY KEY (countryID), 
    UNIQUE (webCode), 
    UNIQUE (countryName) 
); 

錯誤:

System.Data.SqlClient.SqlException: Conversion failed when converting the varchar value 'USA' to data type int.

+1

小鮑比表警報! –

+0

countryid變齲'美國'值,修復它。 –

+1

[SQL注入警報](http://msdn.microsoft.com/en-us/library/ms161953%28v=sql.105%29.aspx) - 你應該**不**連接你的SQL語句 - 使用**參數化查詢**,而不是爲了避免SQL注入 - 檢查[小Bobby表](https://xkcd.com/327/) –

回答

0

使用這一個:

SqlCommand cmd = new SqlCommand("select * from states where countryID='" + countryid + "'", con); 

其實你錯過了單引號和你的表CountryIDvarchar所以你必須使用單引號

+1

仍然小鮑比表容易。 –

+0

非常感謝... Dinesh ..它的工作原理!!! :) –

+0

歡迎如果它工作接受我的答案。 @shanifaS – Dinesh

相關問題