(回帖给分)在将 varchar 值 转换成数据类型 int 时失败。
在将 varchar 值 'System.Web.UI.HtmlControls.HtmlInputText' 转换成数据类型 int 时失败。
我用datalist写了一个添加的代码
数据表里有字段
在一个表格中添加产品的代码是
protected void btnNew_Click(object sender, ImageClickEventArgs e)
{
DBconn DB = new DBconn();
string strSql = "insert into book (bookname,typeid,write,chubanshename,bookprice,xiancunnumber) values('" + txtBookName.Value + "','" + ddlType.Text + "','" + txtWrite + "','" + txtChuban.Value + "','" + txtBookPrice + "'," +txtBookCount.Value + ")";
DB.ExecuteNonQuery(strSql);
btnNew.Visible = false;
Panel1.Visible = false;
DataList1.Visible = true;
DataBindDataList();
initTable();
}
DBconn.cs文件 用于连接。。倒数第二句话 cmd.ExecuteNonQuery(); 报错 说 在将 varchar 值 'System.Web.UI.HtmlControls.HtmlInputText' 转换成数据类型 int 时失败。
public class DBconn
{
private string strConn;
private SqlConnection con;
private SqlCommand cmd;
private SqlDataAdapter sda;
private DataSet ds;
public DBconn()
{
strConn = CreateConnn();
con = new SqlConnection(strConn);
cmd = new SqlCommand();
sda = new SqlDataAdapter();
ds = new DataSet();
}
public string CreateConnn() {
return ConfigurationManager.ConnectionStrings["libraryConnectionString"].ConnectionString;
}
public DataSet Getds(string StrSql) {
con.Open();
sda = new SqlDataAdapter(StrSql, con);
sda.Fill(ds);
con.Close();
return ds;
}
public void ExecuteNonQuery(string strSql) {
con.Open();
cmd.CommandText = strSql;
cmd.Connection = con;
cmd.ExecuteNonQuery();
con.Close();
}
}
[解决办法]
string strSql = "insert into book (bookname,typeid,write,chubanshename,bookprice,xiancunnumber) values('" + txtBookName.Value + "','" + ddlType.Text + "','" + txtWrite + "','" + txtChuban.Value + "','" + txtBookPrice + "'," +txtBookCount.Value + ")";
红的部分对应你数据库字段都是整型,也要进行类型转换
改成这样试试(先判断这些值ddlType.Text不为空)
string strSql = "insert into book (bookname,typeid,write,chubanshename,bookprice,xiancunnumber) values('" + txtBookName.Value + "','" + Convert.ToInt32(ddlType.SelectedValue.Trim()) + "','" + txtWrite + "','" + txtChuban.Value + "','" + Convert.ToInt32(txtBookPrice.Value.Trim()) + "'," +Convert.ToInt32(txtBookCount.Value.Trim()) + ")";
[解决办法]
1楼正解。从页面读到的数字是string类型的,要强制转换一下,用int.Parse()也可以
[解决办法]
string类型转换成int类型 使用int.Parse()
[解决办法]
你的bookprice把不是int类型吗?
[解决办法]
int.tryparse一下
[解决办法]
private static int ConvertStringToInteger(string s) { int result = 0; int.TryParse(s, out result); return result; }